Actual source code: snes.c
1: #include <petsc/private/snesimpl.h>
2: #include <petsc/private/linesearchimpl.h>
3: #include <petscdmshell.h>
4: #include <petscdraw.h>
5: #include <petscds.h>
6: #include <petscdmadaptor.h>
7: #include <petscconvest.h>
9: PetscBool SNESRegisterAllCalled = PETSC_FALSE;
10: PetscFunctionList SNESList = NULL;
12: /* Logging support */
13: PetscClassId SNES_CLASSID, DMSNES_CLASSID;
14: PetscLogEvent SNES_Solve, SNES_SetUp, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NewtonALEval, SNES_NPCSolve, SNES_ObjectiveEval;
16: /*@
17: SNESSetErrorIfNotConverged - Causes `SNESSolve()` to generate an error immediately if the solver has not converged.
19: Logically Collective
21: Input Parameters:
22: + snes - iterative context obtained from `SNESCreate()`
23: - flg - `PETSC_TRUE` indicates you want the error generated
25: Options Database Key:
26: . -snes_error_if_not_converged (true|false) - cause an immediate error condition and stop the program if the solver does not converge
28: Level: intermediate
30: Note:
31: Normally PETSc continues if a solver fails to converge, you can call `SNESGetConvergedReason()` after a `SNESSolve()`
32: to determine if it has converged. Otherwise the solution may be inaccurate or wrong
34: .seealso: [](ch_snes), `SNES`, `SNESGetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()`
35: @*/
36: PetscErrorCode SNESSetErrorIfNotConverged(SNES snes, PetscBool flg)
37: {
38: PetscFunctionBegin;
41: snes->errorifnotconverged = flg;
42: PetscFunctionReturn(PETSC_SUCCESS);
43: }
45: /*@
46: SNESGetErrorIfNotConverged - Indicates if `SNESSolve()` will generate an error if the solver does not converge?
48: Not Collective
50: Input Parameter:
51: . snes - iterative context obtained from `SNESCreate()`
53: Output Parameter:
54: . flag - `PETSC_TRUE` if it will generate an error, else `PETSC_FALSE`
56: Level: intermediate
58: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()`
59: @*/
60: PetscErrorCode SNESGetErrorIfNotConverged(SNES snes, PetscBool *flag)
61: {
62: PetscFunctionBegin;
64: PetscAssertPointer(flag, 2);
65: *flag = snes->errorifnotconverged;
66: PetscFunctionReturn(PETSC_SUCCESS);
67: }
69: /*@
70: SNESSetAlwaysComputesFinalResidual - tells the `SNES` to always compute the residual (nonlinear function value) at the final solution
72: Logically Collective
74: Input Parameters:
75: + snes - the shell `SNES`
76: - flg - `PETSC_TRUE` to always compute the residual
78: Level: advanced
80: Note:
81: Some solvers (such as smoothers in a `SNESFAS`) do not need the residual computed at the final solution so skip computing it
82: to save time.
84: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSolve()`, `SNESGetAlwaysComputesFinalResidual()`
85: @*/
86: PetscErrorCode SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
87: {
88: PetscFunctionBegin;
90: snes->alwayscomputesfinalresidual = flg;
91: PetscFunctionReturn(PETSC_SUCCESS);
92: }
94: /*@
95: SNESGetAlwaysComputesFinalResidual - checks if the `SNES` always computes the residual at the final solution
97: Logically Collective
99: Input Parameter:
100: . snes - the `SNES` context
102: Output Parameter:
103: . flg - `PETSC_TRUE` if the residual is computed
105: Level: advanced
107: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSolve()`, `SNESSetAlwaysComputesFinalResidual()`
108: @*/
109: PetscErrorCode SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
110: {
111: PetscFunctionBegin;
113: *flg = snes->alwayscomputesfinalresidual;
114: PetscFunctionReturn(PETSC_SUCCESS);
115: }
117: /*@
118: SNESSetFunctionDomainError - tells `SNES` that the input vector, a proposed new solution, to your function you provided to `SNESSetFunction()` is not
119: in the function's domain. For example, a step with negative pressure.
121: Not Collective
123: Input Parameter:
124: . snes - the `SNES` context
126: Level: advanced
128: Notes:
129: This does not need to be called by all processes in the `SNES` MPI communicator.
131: A few solvers will try to cut the step size to avoid the domain error but for other solvers `SNESSolve()` stops iterating and
132: returns with a `SNESConvergedReason` of `SNES_DIVERGED_FUNCTION_DOMAIN`
134: You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
135: `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
137: You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).
139: You can call `SNESSetJacobianDomainError()` during a Jacobian computation to indicate the proposed solution is not in the domain.
141: Developer Note:
142: This value is used by `SNESCheckFunctionDomainError()` to determine if the `SNESConvergedReason` is set to `SNES_DIVERGED_FUNCTION_DOMAIN`
144: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`,
145: `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`,
146: `SNES_DIVERGED_FUNCTION_DOMAIN`, `SNESSetObjectiveDomainError()`, `SNES_DIVERGED_OBJECTIVE_DOMAIN`
147: @*/
148: PetscErrorCode SNESSetFunctionDomainError(SNES snes)
149: {
150: PetscFunctionBegin;
152: snes->functiondomainerror = PETSC_TRUE;
153: PetscFunctionReturn(PETSC_SUCCESS);
154: }
156: /*@
157: SNESSetObjectiveDomainError - tells `SNES` that the input vector, a proposed new solution, to your function you provided to `SNESSetObjective()` is not
158: in the function's domain. For example, a step with negative pressure.
160: Not Collective
162: Input Parameter:
163: . snes - the `SNES` context
165: Level: advanced
167: Notes:
168: This does not need to be called by all processes in the `SNES` MPI communicator.
170: A few solvers will try to cut the step size to avoid the domain error but for other solvers `SNESSolve()` stops iterating and
171: returns with a `SNESConvergedReason` of `SNES_DIVERGED_OBJECTIVE_DOMAIN`
173: You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
174: `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
176: You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).
178: You can call `SNESSetJacobianDomainError()` during a Jacobian computation to indicate the proposed solution is not in the domain.
180: Developer Note:
181: This value is used by `SNESCheckObjectiveDomainError()` to determine if the `SNESConvergedReason` is set to `SNES_DIVERGED_OBJECTIVE_DOMAIN`
183: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`,
184: `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`,
185: `SNES_DIVERGED_OBJECTIVE_DOMAIN`, `SNESSetFunctionDomainError()`, `SNES_DIVERGED_FUNCTION_DOMAIN`
186: @*/
187: PetscErrorCode SNESSetObjectiveDomainError(SNES snes)
188: {
189: PetscFunctionBegin;
191: snes->objectivedomainerror = PETSC_TRUE;
192: PetscFunctionReturn(PETSC_SUCCESS);
193: }
195: /*@
196: SNESSetJacobianDomainError - tells `SNES` that the function you provided to `SNESSetJacobian()` at the proposed step. For example there is a negative element transformation.
198: Logically Collective
200: Input Parameter:
201: . snes - the `SNES` context
203: Level: advanced
205: Notes:
206: If this is called the `SNESSolve()` stops iterating and returns with a `SNESConvergedReason` of `SNES_DIVERGED_JACOBIAN_DOMAIN`
208: You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).
210: You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
211: `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
213: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESVISetVariableBounds()`,
214: `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`
215: @*/
216: PetscErrorCode SNESSetJacobianDomainError(SNES snes)
217: {
218: PetscFunctionBegin;
220: PetscCheck(!snes->errorifnotconverged, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "User code indicates computeJacobian does not make sense");
221: snes->jacobiandomainerror = PETSC_TRUE;
222: PetscFunctionReturn(PETSC_SUCCESS);
223: }
225: /*@
226: SNESSetCheckJacobianDomainError - tells `SNESSolve()` whether to check if the user called `SNESSetJacobianDomainError()` to indicate a Jacobian domain error after
227: each Jacobian evaluation.
229: Logically Collective
231: Input Parameters:
232: + snes - the `SNES` context
233: - flg - indicates if or not to check Jacobian domain error after each Jacobian evaluation
235: Level: advanced
237: Notes:
238: By default, it checks for the Jacobian domain error in the debug mode, and does not check it in the optimized mode.
240: Checks require one extra parallel synchronization for each Jacobian evaluation
242: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESGetCheckJacobianDomainError()`
243: @*/
244: PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg)
245: {
246: PetscFunctionBegin;
248: snes->checkjacdomainerror = flg;
249: PetscFunctionReturn(PETSC_SUCCESS);
250: }
252: /*@
253: SNESGetCheckJacobianDomainError - Get an indicator whether or not `SNES` is checking Jacobian domain errors after each Jacobian evaluation.
255: Logically Collective
257: Input Parameter:
258: . snes - the `SNES` context
260: Output Parameter:
261: . flg - `PETSC_FALSE` indicates that it is not checking Jacobian domain errors after each Jacobian evaluation
263: Level: advanced
265: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESSetCheckJacobianDomainError()`
266: @*/
267: PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
268: {
269: PetscFunctionBegin;
271: PetscAssertPointer(flg, 2);
272: *flg = snes->checkjacdomainerror;
273: PetscFunctionReturn(PETSC_SUCCESS);
274: }
276: /*@
277: SNESLoad - Loads a `SNES` that has been stored in `PETSCVIEWERBINARY` with `SNESView()`.
279: Collective
281: Input Parameters:
282: + snes - the newly loaded `SNES`, this needs to have been created with `SNESCreate()` or
283: some related function before a call to `SNESLoad()`.
284: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
286: Level: intermediate
288: Note:
289: The `SNESType` is determined by the data in the file, any type set into the `SNES` before this call is ignored.
291: .seealso: [](ch_snes), `SNES`, `PetscViewer`, `SNESCreate()`, `SNESType`, `PetscViewerBinaryOpen()`, `SNESView()`, `MatLoad()`, `VecLoad()`
292: @*/
293: PetscErrorCode SNESLoad(SNES snes, PetscViewer viewer)
294: {
295: PetscBool isbinary;
296: PetscInt classid;
297: char type[256];
298: KSP ksp;
299: DM dm;
300: DMSNES dmsnes;
302: PetscFunctionBegin;
305: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
306: PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
308: PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
309: PetscCheck(classid == SNES_FILE_CLASSID, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Not SNES next in file");
310: PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
311: PetscCall(SNESSetType(snes, type));
312: PetscTryTypeMethod(snes, load, viewer);
313: PetscCall(SNESGetDM(snes, &dm));
314: PetscCall(DMGetDMSNES(dm, &dmsnes));
315: PetscCall(DMSNESLoad(dmsnes, viewer));
316: PetscCall(SNESGetKSP(snes, &ksp));
317: PetscCall(KSPLoad(ksp, viewer));
318: PetscFunctionReturn(PETSC_SUCCESS);
319: }
321: #include <petscdraw.h>
322: #if PetscDefined(HAVE_SAWS)
323: #include <petscviewersaws.h>
324: #endif
326: /*@
327: SNESViewFromOptions - View a `SNES` based on values in the options database
329: Collective
331: Input Parameters:
332: + A - the `SNES` context
333: . obj - optional object that provides the options prefix for the checks, pass `NULL` to use the options prefix of `A`
334: - name - command line option
336: Options Database Key:
337: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`
339: Level: intermediate
341: Note:
342: This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
343: rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.
345: .seealso: [](ch_snes), `SNES`, `SNESView()`, `PetscObjectViewFromOptions()`, `SNESCreate()`, `PetscOptionsCreateViewer()`
346: @*/
347: PetscErrorCode SNESViewFromOptions(SNES A, PetscObject obj, const char name[])
348: {
349: PetscFunctionBegin;
351: PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
352: PetscFunctionReturn(PETSC_SUCCESS);
353: }
355: PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES, Vec, Mat, Mat, void *);
357: /*@
358: SNESView - Prints or visualizes the `SNES` data structure.
360: Collective
362: Input Parameters:
363: + snes - the `SNES` context
364: - viewer - the `PetscViewer`
366: Options Database Key:
367: . -snes_view viewer_specification - Calls `SNESView()` at end of `SNESSolve()`, see `PetscOptionsCreateViewer()` for the format of `viewer_specification`
369: Level: beginner
371: Notes:
372: The available visualization contexts include
373: + `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
374: - `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
375: output where only the first processor opens
376: the file. All other processors send their
377: data to the first processor to print.
379: The available formats include
380: + `PETSC_VIEWER_DEFAULT` - standard output (default)
381: - `PETSC_VIEWER_ASCII_INFO_DETAIL` - more verbose output for `SNESNASM`
383: The user can open an alternative visualization context with
384: `PetscViewerASCIIOpen()` - output to a specified file.
386: In the debugger you can do "call `SNESView`(snes,0)" to display the `SNES` solver. (The same holds for any PETSc object viewer).
388: .seealso: [](ch_snes), `SNES`, `SNESLoad()`, `SNESCreate()`, `PetscViewerASCIIOpen()`, `SNESViewFromOptions()`, `PetscOptionsCreateViewer()`
389: @*/
390: PetscErrorCode SNESView(SNES snes, PetscViewer viewer)
391: {
392: SNESKSPEW *kctx;
393: KSP ksp;
394: Vec u;
395: SNESLineSearch linesearch;
396: PetscBool isascii, isstring, isbinary, isdraw;
397: DMSNES dmsnes;
398: #if PetscDefined(HAVE_SAWS)
399: PetscBool issaws;
400: #endif
402: PetscFunctionBegin;
404: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &viewer));
406: PetscCheckSameComm(snes, 1, viewer, 2);
408: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
409: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
410: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
411: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
412: #if PetscDefined(HAVE_SAWS)
413: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
414: #endif
415: if (isascii) {
416: SNESNormSchedule normschedule;
417: DM dm;
418: SNESJacobianFn *cJ;
419: void *ctx;
420: const char *pre = "";
422: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)snes, viewer));
423: if (!snes->setupcalled) PetscCall(PetscViewerASCIIPrintf(viewer, " SNES has not been set up so information may be incomplete\n"));
424: if (snes->ops->view) {
425: PetscCall(PetscViewerASCIIPushTab(viewer));
426: PetscUseTypeMethod(snes, view, viewer);
427: PetscCall(PetscViewerASCIIPopTab(viewer));
428: }
429: if (snes->max_funcs == PETSC_UNLIMITED) {
430: PetscCall(PetscViewerASCIIPrintf(viewer, " maximum iterations=%" PetscInt_FMT ", maximum function evaluations=unlimited\n", snes->max_its));
431: } else {
432: PetscCall(PetscViewerASCIIPrintf(viewer, " maximum iterations=%" PetscInt_FMT ", maximum function evaluations=%" PetscInt_FMT "\n", snes->max_its, snes->max_funcs));
433: }
434: PetscCall(PetscViewerASCIIPrintf(viewer, " tolerances: relative=%g, absolute=%g, solution=%g\n", (double)snes->rtol, (double)snes->abstol, (double)snes->stol));
435: if (snes->usesksp) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of linear solver iterations=%" PetscInt_FMT "\n", snes->linear_its));
436: PetscCall(PetscViewerASCIIPrintf(viewer, " total number of function evaluations=%" PetscInt_FMT "\n", snes->nfuncs));
437: PetscCall(SNESGetNormSchedule(snes, &normschedule));
438: if (normschedule > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " norm schedule %s\n", SNESNormSchedules[normschedule]));
439: if (snes->gridsequence) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of grid sequence refinements=%" PetscInt_FMT "\n", snes->gridsequence));
440: if (snes->ksp_ewconv) {
441: kctx = (SNESKSPEW *)snes->kspconvctx;
442: if (kctx) {
443: PetscCall(PetscViewerASCIIPrintf(viewer, " Eisenstat-Walker computation of KSP relative tolerance (version %" PetscInt_FMT ")\n", kctx->version));
444: PetscCall(PetscViewerASCIIPrintf(viewer, " rtol_0=%g, rtol_max=%g, threshold=%g\n", (double)kctx->rtol_0, (double)kctx->rtol_max, (double)kctx->threshold));
445: PetscCall(PetscViewerASCIIPrintf(viewer, " gamma=%g, alpha=%g, alpha2=%g\n", (double)kctx->gamma, (double)kctx->alpha, (double)kctx->alpha2));
446: }
447: }
448: if (snes->lagpreconditioner == -1) {
449: PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioned is never rebuilt\n"));
450: } else if (snes->lagpreconditioner > 1) {
451: PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioned is rebuilt every %" PetscInt_FMT " new Jacobians\n", snes->lagpreconditioner));
452: }
453: if (snes->lagjacobian == -1) {
454: PetscCall(PetscViewerASCIIPrintf(viewer, " Jacobian is never rebuilt\n"));
455: } else if (snes->lagjacobian > 1) {
456: PetscCall(PetscViewerASCIIPrintf(viewer, " Jacobian is rebuilt every %" PetscInt_FMT " SNES iterations\n", snes->lagjacobian));
457: }
458: PetscCall(SNESGetDM(snes, &dm));
459: PetscCall(DMSNESGetJacobian(dm, &cJ, &ctx));
460: if (snes->mf_operator) {
461: PetscCall(PetscViewerASCIIPrintf(viewer, " Jacobian is applied matrix-free with differencing\n"));
462: pre = "Preconditioning ";
463: }
464: if (cJ == SNESComputeJacobianDefault) {
465: PetscCall(PetscViewerASCIIPrintf(viewer, " %sJacobian is built using finite differences one column at a time\n", pre));
466: } else if (cJ == SNESComputeJacobianDefaultColor) {
467: PetscCall(PetscViewerASCIIPrintf(viewer, " %sJacobian is built using finite differences with coloring\n", pre));
468: /* it slightly breaks data encapsulation for access the DMDA information directly */
469: } else if (cJ == SNESComputeJacobian_DMDA) {
470: MatFDColoring fdcoloring;
471: PetscCall(PetscObjectQuery((PetscObject)dm, "DMDASNES_FDCOLORING", (PetscObject *)&fdcoloring));
472: if (fdcoloring) {
473: PetscCall(PetscViewerASCIIPrintf(viewer, " %sJacobian is built using colored finite differences on a DMDA\n", pre));
474: } else {
475: PetscCall(PetscViewerASCIIPrintf(viewer, " %sJacobian is built using a DMDA local Jacobian\n", pre));
476: }
477: } else if (snes->mf && !snes->mf_operator) {
478: PetscCall(PetscViewerASCIIPrintf(viewer, " Jacobian is applied matrix-free with differencing, no explicit Jacobian\n"));
479: }
480: } else if (isstring) {
481: const char *type;
482: PetscCall(SNESGetType(snes, &type));
483: PetscCall(PetscViewerStringSPrintf(viewer, " SNESType: %-7.7s", type));
484: PetscTryTypeMethod(snes, view, viewer);
485: } else if (isbinary) {
486: PetscInt classid = SNES_FILE_CLASSID;
487: MPI_Comm comm;
488: PetscMPIInt rank;
489: char type[256];
491: PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
492: PetscCallMPI(MPI_Comm_rank(comm, &rank));
493: if (rank == 0) {
494: PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
495: PetscCall(PetscStrncpy(type, ((PetscObject)snes)->type_name, sizeof(type)));
496: PetscCall(PetscViewerBinaryWrite(viewer, type, sizeof(type), PETSC_CHAR));
497: }
498: PetscTryTypeMethod(snes, view, viewer);
499: } else if (isdraw) {
500: PetscDraw draw;
501: char str[36];
502: PetscReal x, y, bottom, h;
504: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
505: PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
506: PetscCall(PetscStrncpy(str, "SNES: ", sizeof(str)));
507: PetscCall(PetscStrlcat(str, ((PetscObject)snes)->type_name, sizeof(str)));
508: PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLUE, PETSC_DRAW_BLACK, str, NULL, &h));
509: bottom = y - h;
510: PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
511: PetscTryTypeMethod(snes, view, viewer);
512: #if PetscDefined(HAVE_SAWS)
513: } else if (issaws) {
514: PetscMPIInt rank;
515: const char *name;
517: PetscCall(PetscObjectGetName((PetscObject)snes, &name));
518: PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
519: if (!((PetscObject)snes)->amsmem && rank == 0) {
520: char dir[1024];
522: PetscCall(PetscObjectViewSAWs((PetscObject)snes, viewer));
523: PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/its", name));
524: PetscCallSAWs(SAWs_Register, (dir, &snes->iter, 1, SAWs_READ, SAWs_INT));
525: if (!snes->conv_hist) PetscCall(SNESSetConvergenceHistory(snes, NULL, NULL, PETSC_DECIDE, PETSC_TRUE));
526: PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/conv_hist", name));
527: PetscCallSAWs(SAWs_Register, (dir, snes->conv_hist, 10, SAWs_READ, SAWs_DOUBLE));
528: }
529: #endif
530: }
531: if (snes->linesearch) {
532: PetscCall(SNESGetLineSearch(snes, &linesearch));
533: PetscCall(PetscViewerASCIIPushTab(viewer));
534: PetscCall(SNESLineSearchView(linesearch, viewer));
535: PetscCall(PetscViewerASCIIPopTab(viewer));
536: }
537: if (snes->npc && snes->usesnpc) {
538: PetscCall(PetscViewerASCIIPushTab(viewer));
539: PetscCall(SNESView(snes->npc, viewer));
540: PetscCall(PetscViewerASCIIPopTab(viewer));
541: }
542: PetscCall(PetscViewerASCIIPushTab(viewer));
543: PetscCall(DMGetDMSNES(snes->dm, &dmsnes));
544: PetscCall(DMSNESView(dmsnes, viewer));
545: PetscCall(PetscViewerASCIIPopTab(viewer));
546: if (snes->usesksp) {
547: PetscCall(SNESGetKSP(snes, &ksp));
548: PetscCall(PetscViewerASCIIPushTab(viewer));
549: PetscCall(KSPView(ksp, viewer));
550: PetscCall(PetscViewerASCIIPopTab(viewer));
551: } else {
552: PetscViewerFormat format;
554: PetscCall(SNESGetSolution(snes, &u));
555: PetscCall(PetscViewerGetFormat(viewer, &format));
556: if (u && isascii) {
557: if (format != PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerPushFormat(viewer, PETSC_VIEWER_ASCII_INFO));
558: PetscCall(PetscViewerASCIIPrintf(viewer, "solution vector:\n"));
559: PetscCall(PetscViewerASCIIPushTab(viewer));
560: PetscCall(VecView(u, viewer));
561: PetscCall(PetscViewerASCIIPopTab(viewer));
562: if (format != PETSC_VIEWER_ASCII_INFO_DETAIL) PetscCall(PetscViewerPopFormat(viewer));
563: }
564: }
565: if (isdraw) {
566: PetscDraw draw;
567: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
568: PetscCall(PetscDrawPopCurrentPoint(draw));
569: }
570: PetscFunctionReturn(PETSC_SUCCESS);
571: }
573: /*
574: We retain a list of functions that also take SNES command
575: line options. These are called at the end SNESSetFromOptions()
576: */
577: #define MAXSETFROMOPTIONS 5
578: static PetscInt numberofsetfromoptions;
579: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);
581: /*@
582: SNESAddOptionsChecker - Adds an additional function to check for `SNES` options.
584: Not Collective
586: Input Parameter:
587: . snescheck - function that checks for options
589: Calling sequence of `snescheck`:
590: . snes - the `SNES` object for which it is checking options
592: Level: developer
594: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`
595: @*/
596: PetscErrorCode SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES snes))
597: {
598: PetscFunctionBegin;
599: PetscCheck(numberofsetfromoptions < MAXSETFROMOPTIONS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %d allowed", MAXSETFROMOPTIONS);
600: othersetfromoptions[numberofsetfromoptions++] = snescheck;
601: PetscFunctionReturn(PETSC_SUCCESS);
602: }
604: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
605: {
606: Mat J;
607: MatNullSpace nullsp;
609: PetscFunctionBegin;
612: if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
613: Mat A = snes->jacobian, B = snes->jacobian_pre;
614: PetscCall(MatCreateVecs(A ? A : B, NULL, &snes->vec_func));
615: }
617: PetscCheck(version == 1 || version == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");
618: if (version == 1) {
619: PetscCall(MatCreateSNESMF(snes, &J));
620: PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
621: PetscCall(MatSetFromOptions(J));
622: /* TODO: the version 2 code should be merged into the MatCreateSNESMF() and MatCreateMFFD() infrastructure and then removed */
623: } else /* if (version == 2) */ {
624: PetscCheck(snes->vec_func, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "SNESSetFunction() must be called first");
625: #if !PetscDefined(USE_COMPLEX) && !PetscDefined(USE_REAL_SINGLE) && !PetscDefined(USE_REAL___FLOAT128) && !PetscDefined(USE_REAL___FP16)
626: PetscCall(MatCreateSNESMFMore(snes, snes->vec_func, &J));
627: #else
628: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
629: #endif
630: }
632: /* attach any user provided null space that was on Amat to the newly created matrix-free matrix */
633: if (snes->jacobian) {
634: PetscCall(MatGetNullSpace(snes->jacobian, &nullsp));
635: if (nullsp) PetscCall(MatSetNullSpace(J, nullsp));
636: }
638: PetscCall(PetscInfo(snes, "Setting default matrix-free operator routines (version %" PetscInt_FMT ")\n", version));
639: if (hasOperator) {
640: /* This version replaces the user provided Jacobian matrix with a
641: matrix-free version but still employs the user-provided matrix used for computing the preconditioner. */
642: PetscCall(SNESSetJacobian(snes, J, NULL, NULL, NULL));
643: } else {
644: /* This version replaces both the user-provided Jacobian and the user-
645: provided preconditioner Jacobian with the default matrix-free version. */
646: if (snes->npcside == PC_LEFT && snes->npc) {
647: if (!snes->jacobian) PetscCall(SNESSetJacobian(snes, J, NULL, NULL, NULL));
648: } else PetscCall(SNESSetJacobian(snes, J, J, MatMFFDComputeJacobian, NULL));
649: }
650: PetscCall(MatDestroy(&J));
651: PetscFunctionReturn(PETSC_SUCCESS);
652: }
654: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine, Mat Restrict, Vec Rscale, Mat Inject, DM dmcoarse, PetscCtx ctx)
655: {
656: SNES snes = (SNES)ctx;
657: Vec Xfine, Xfine_named = NULL, Xcoarse;
659: PetscFunctionBegin;
660: if (PetscLogPrintInfo) {
661: PetscInt finelevel, coarselevel, fineclevel, coarseclevel;
662: PetscCall(DMGetRefineLevel(dmfine, &finelevel));
663: PetscCall(DMGetCoarsenLevel(dmfine, &fineclevel));
664: PetscCall(DMGetRefineLevel(dmcoarse, &coarselevel));
665: PetscCall(DMGetCoarsenLevel(dmcoarse, &coarseclevel));
666: PetscCall(PetscInfo(dmfine, "Restricting SNES solution vector from level %" PetscInt_FMT "-%" PetscInt_FMT " to level %" PetscInt_FMT "-%" PetscInt_FMT "\n", finelevel, fineclevel, coarselevel, coarseclevel));
667: }
668: if (dmfine == snes->dm) Xfine = snes->vec_sol;
669: else {
670: PetscCall(DMGetNamedGlobalVector(dmfine, "SNESVecSol", &Xfine_named));
671: Xfine = Xfine_named;
672: }
673: PetscCall(DMGetNamedGlobalVector(dmcoarse, "SNESVecSol", &Xcoarse));
674: if (Inject) {
675: PetscCall(MatRestrict(Inject, Xfine, Xcoarse));
676: } else {
677: PetscCall(MatRestrict(Restrict, Xfine, Xcoarse));
678: PetscCall(VecPointwiseMult(Xcoarse, Xcoarse, Rscale));
679: }
680: PetscCall(DMRestoreNamedGlobalVector(dmcoarse, "SNESVecSol", &Xcoarse));
681: if (Xfine_named) PetscCall(DMRestoreNamedGlobalVector(dmfine, "SNESVecSol", &Xfine_named));
682: PetscFunctionReturn(PETSC_SUCCESS);
683: }
685: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm, DM dmc, PetscCtx ctx)
686: {
687: PetscFunctionBegin;
688: PetscCall(DMCoarsenHookAdd(dmc, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, ctx));
689: PetscFunctionReturn(PETSC_SUCCESS);
690: }
692: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
693: * safely call SNESGetDM() in their residual evaluation routine. */
694: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp, Mat A, Mat B, PetscCtx ctx)
695: {
696: SNES snes = (SNES)ctx;
697: DMSNES sdm;
698: Vec X, Xnamed = NULL;
699: DM dmsave;
700: void *ctxsave;
701: SNESJacobianFn *jac = NULL;
703: PetscFunctionBegin;
704: dmsave = snes->dm;
705: PetscCall(KSPGetDM(ksp, &snes->dm));
706: if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
707: else {
708: PetscBool has;
710: /* We are on a coarser level, this vec was initialized using a DM restrict hook */
711: PetscCall(DMHasNamedGlobalVector(snes->dm, "SNESVecSol", &has));
712: PetscCheck(has, PetscObjectComm((PetscObject)snes->dm), PETSC_ERR_PLIB, "Missing SNESVecSol");
713: PetscCall(DMGetNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
714: X = Xnamed;
715: PetscCall(SNESGetJacobian(snes, NULL, NULL, &jac, &ctxsave));
716: /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
717: if (jac == SNESComputeJacobianDefaultColor) PetscCall(SNESSetJacobian(snes, NULL, NULL, SNESComputeJacobianDefaultColor, NULL));
718: }
720: /* Compute the operators */
721: PetscCall(DMGetDMSNES(snes->dm, &sdm));
722: if (Xnamed && sdm->ops->computefunction) {
723: /* The SNES contract with the user is that ComputeFunction is always called before ComputeJacobian.
724: We make sure of this here. Disable affine shift since it is for the finest level */
725: Vec F, saverhs = snes->vec_rhs;
727: snes->vec_rhs = NULL;
728: PetscCall(DMGetGlobalVector(snes->dm, &F));
729: PetscCall(SNESComputeFunction(snes, X, F));
730: PetscCall(DMRestoreGlobalVector(snes->dm, &F));
731: snes->vec_rhs = saverhs;
732: snes->nfuncs--; /* Do not log coarser level evaluations */
733: }
734: /* Make sure KSP DM has the Jacobian computation routine */
735: if (!sdm->ops->computejacobian) PetscCall(DMCopyDMSNES(dmsave, snes->dm));
736: PetscCall(SNESComputeJacobian(snes, X, A, B)); /* cannot handle previous SNESSetJacobianDomainError() calls */
738: /* Put the previous context back */
739: if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) PetscCall(SNESSetJacobian(snes, NULL, NULL, jac, ctxsave));
741: if (Xnamed) PetscCall(DMRestoreNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
742: snes->dm = dmsave;
743: PetscFunctionReturn(PETSC_SUCCESS);
744: }
746: /*@
747: SNESSetUpMatrices - ensures that matrices are available for `SNES` Newton-like methods, this is called by `SNESSetUp_XXX()`
749: Collective
751: Input Parameter:
752: . snes - `SNES` object to configure
754: Level: developer
756: Note:
757: If the matrices do not yet exist it attempts to create them based on options previously set for the `SNES` such as `-snes_mf`
759: Developer Note:
760: The functionality of this routine overlaps in a confusing way with the functionality of `SNESSetUpMatrixFree_Private()` which is called by
761: `SNESSetUp()` but sometimes `SNESSetUpMatrices()` is called without `SNESSetUp()` being called. A refactorization to simplify the
762: logic that handles the matrix-free case is desirable.
764: .seealso: [](ch_snes), `SNES`, `SNESSetUp()`
765: @*/
766: PetscErrorCode SNESSetUpMatrices(SNES snes)
767: {
768: DM dm;
769: DMSNES sdm;
771: PetscFunctionBegin;
772: PetscCall(SNESGetDM(snes, &dm));
773: PetscCall(DMGetDMSNES(dm, &sdm));
774: if (!snes->jacobian && snes->mf && !snes->mf_operator && !snes->jacobian_pre) {
775: Mat J;
776: void *functx;
777: PetscCall(MatCreateSNESMF(snes, &J));
778: PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
779: PetscCall(MatSetFromOptions(J));
780: PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
781: PetscCall(SNESSetJacobian(snes, J, J, NULL, NULL));
782: PetscCall(MatDestroy(&J));
783: } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
784: Mat J, B;
785: PetscCall(MatCreateSNESMF(snes, &J));
786: PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
787: PetscCall(MatSetFromOptions(J));
788: PetscCall(DMCreateMatrix(snes->dm, &B));
789: /* sdm->computejacobian was already set to reach here */
790: PetscCall(SNESSetJacobian(snes, J, B, NULL, NULL));
791: PetscCall(MatDestroy(&J));
792: PetscCall(MatDestroy(&B));
793: } else if (!snes->jacobian_pre) {
794: PetscDS prob;
795: Mat J, B;
796: PetscBool hasPrec = PETSC_FALSE;
798: J = snes->jacobian;
799: PetscCall(DMGetDS(dm, &prob));
800: if (prob) PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
801: if (!J && hasPrec) PetscCall(DMCreateMatrix(snes->dm, &J));
802: else PetscCall(PetscObjectReference((PetscObject)J));
803: PetscCall(DMCreateMatrix(snes->dm, &B));
804: PetscCall(SNESSetJacobian(snes, J ? J : B, B, NULL, NULL));
805: PetscCall(MatDestroy(&J));
806: PetscCall(MatDestroy(&B));
807: }
808: {
809: KSP ksp;
810: PetscCall(SNESGetKSP(snes, &ksp));
811: PetscCall(KSPSetComputeOperators(ksp, KSPComputeOperators_SNES, snes));
812: PetscCall(DMCoarsenHookAdd(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
813: }
814: PetscFunctionReturn(PETSC_SUCCESS);
815: }
817: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscMonitorPauseFinal_Internal(PetscInt, PetscCtx);
819: static PetscErrorCode SNESMonitorPauseFinal_Internal(SNES snes)
820: {
821: PetscFunctionBegin;
822: if (!snes->pauseFinal) PetscFunctionReturn(PETSC_SUCCESS);
823: PetscCall(PetscMonitorPauseFinal_Internal(snes->numbermonitors, snes->monitorcontext));
824: PetscFunctionReturn(PETSC_SUCCESS);
825: }
827: /*@
828: SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
830: Collective
832: Input Parameters:
833: + snes - `SNES` object you wish to monitor
834: . name - the monitor type one is seeking
835: . help - message indicating what monitoring is done
836: . manual - manual page for the monitor
837: . monitor - the monitor function, this must use a `PetscViewerFormat` as its context
838: - 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
840: Calling sequence of `monitor`:
841: + snes - the nonlinear solver context
842: . it - the current iteration
843: . r - the current function norm
844: - vf - a `PetscViewerAndFormat` struct that contains the `PetscViewer` and `PetscViewerFormat` to use
846: Calling sequence of `monitorsetup`:
847: + snes - the nonlinear solver context
848: - vf - a `PetscViewerAndFormat` struct that contains the `PetscViewer` and `PetscViewerFormat` to use
850: Options Database Key:
851: . -name - trigger the use of this monitor in `SNESSetFromOptions()`
853: Level: advanced
855: .seealso: [](ch_snes), `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
856: `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
857: `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
858: `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
859: `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
860: `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
861: `PetscOptionsFList()`, `PetscOptionsEList()`
862: @*/
863: 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))
864: {
865: PetscViewer viewer;
866: PetscViewerFormat format;
867: PetscBool flg;
869: PetscFunctionBegin;
870: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, name, &viewer, &format, &flg));
871: if (flg) {
872: PetscViewerAndFormat *vf;
873: PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
874: PetscCall(PetscViewerDestroy(&viewer));
875: if (monitorsetup) PetscCall((*monitorsetup)(snes, vf));
876: PetscCall(SNESMonitorSet(snes, (PetscErrorCode (*)(SNES, PetscInt, PetscReal, PetscCtx))monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
877: }
878: PetscFunctionReturn(PETSC_SUCCESS);
879: }
881: PetscErrorCode SNESEWSetFromOptions_Private(SNESKSPEW *kctx, PetscBool print_api, MPI_Comm comm, const char *prefix)
882: {
883: const char *api = print_api ? "SNESKSPSetParametersEW" : NULL;
885: PetscFunctionBegin;
886: PetscOptionsBegin(comm, prefix, "Eisenstat and Walker type forcing options", "KSP");
887: PetscCall(PetscOptionsInt("-ksp_ew_version", "Version 1, 2 or 3", api, kctx->version, &kctx->version, NULL));
888: PetscCall(PetscOptionsReal("-ksp_ew_rtol0", "0 <= rtol0 < 1", api, kctx->rtol_0, &kctx->rtol_0, NULL));
889: kctx->rtol_max = PetscMax(kctx->rtol_0, kctx->rtol_max);
890: PetscCall(PetscOptionsReal("-ksp_ew_rtolmax", "0 <= rtolmax < 1", api, kctx->rtol_max, &kctx->rtol_max, NULL));
891: PetscCall(PetscOptionsReal("-ksp_ew_gamma", "0 <= gamma <= 1", api, kctx->gamma, &kctx->gamma, NULL));
892: PetscCall(PetscOptionsReal("-ksp_ew_alpha", "1 < alpha <= 2", api, kctx->alpha, &kctx->alpha, NULL));
893: PetscCall(PetscOptionsReal("-ksp_ew_alpha2", "alpha2", NULL, kctx->alpha2, &kctx->alpha2, NULL));
894: PetscCall(PetscOptionsReal("-ksp_ew_threshold", "0 < threshold < 1", api, kctx->threshold, &kctx->threshold, NULL));
895: PetscCall(PetscOptionsReal("-ksp_ew_v4_p1", "p1", NULL, kctx->v4_p1, &kctx->v4_p1, NULL));
896: PetscCall(PetscOptionsReal("-ksp_ew_v4_p2", "p2", NULL, kctx->v4_p2, &kctx->v4_p2, NULL));
897: PetscCall(PetscOptionsReal("-ksp_ew_v4_p3", "p3", NULL, kctx->v4_p3, &kctx->v4_p3, NULL));
898: PetscCall(PetscOptionsReal("-ksp_ew_v4_m1", "Scaling when rk-1 in [p2,p3)", NULL, kctx->v4_m1, &kctx->v4_m1, NULL));
899: PetscCall(PetscOptionsReal("-ksp_ew_v4_m2", "Scaling when rk-1 in [p3,+infty)", NULL, kctx->v4_m2, &kctx->v4_m2, NULL));
900: PetscCall(PetscOptionsReal("-ksp_ew_v4_m3", "Threshold for successive rtol (0.1 in Eq.7)", NULL, kctx->v4_m3, &kctx->v4_m3, NULL));
901: PetscCall(PetscOptionsReal("-ksp_ew_v4_m4", "Adaptation scaling (0.5 in Eq.7)", NULL, kctx->v4_m4, &kctx->v4_m4, NULL));
902: PetscOptionsEnd();
903: PetscFunctionReturn(PETSC_SUCCESS);
904: }
906: /*@
907: SNESSetFromOptions - Sets various `SNES` and `KSP` parameters from user options.
909: Collective
911: Input Parameter:
912: . snes - the `SNES` context
914: Options Database Keys:
915: + -snes_view_pre viewer_specification - view information about the nonlinear solver before the solve
916: . -snes_view viewer_specification - view information about the nonlinear solver after the solve
917: . -snes_type type - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, `SNESType` for complete list
918: . -snes_rtol rtol - relative decrease in tolerance norm from initial
919: . -snes_atol abstol - absolute tolerance of residual norm
920: . -snes_stol stol - convergence tolerance in terms of the norm of the change in the solution between steps
921: . -snes_divergence_tolerance divtol - if the residual goes above divtol*rnorm0, exit with divergence
922: . -snes_max_it max_it - maximum number of iterations
923: . -snes_max_funcs max_funcs - maximum number of function evaluations
924: . -snes_force_iteration force - force `SNESSolve()` to take at least one iteration
925: . -snes_max_fail max_fail - maximum number of line search failures allowed before stopping, default is none
926: . -snes_max_linear_solve_fail num - number of linear solver failures allowed before `SNESSolve()` is stopped
927: . -snes_lag_preconditioner lag - how often preconditioner is rebuilt (use -1 to never rebuild)
928: . -snes_lag_preconditioner_persists (true|false) - retains the `-snes_lag_preconditioner` information across multiple `SNESSolve()`
929: . -snes_lag_jacobian lag - how often Jacobian is rebuilt (use -1 to never rebuild)
930: . -snes_lag_jacobian_persists (true|false) - retains the `-snes_lag_jacobian` information across multiple `SNESSolve()`
931: . -snes_convergence_test (default|skip|correct_pressure) - convergence test in nonlinear solver. default `SNESConvergedDefault()`. `skip` uses `SNESConvergedSkip()` and means continue
932: iterating until `max_it` or some other criterion is reached. `correct_pressure` uses
933: `SNESConvergedCorrectPressure()` and has special handling of a pressure null space.
934: . -snes_monitor viewer_specification - displays residual norm at each iteration. if no filename given prints to stdout
935: . -snes_monitor_solution viewer_specification - displays solution at each iteration
936: . -snes_monitor_residual viewer_specification - displays residual (not its norm) at each iteration
937: . -snes_monitor_solution_update viewer_specification - displays update to solution at each iteration
938: . -snes_monitor_lg_range (true|false) - plots function range at each iteration
939: . -snes_monitor_pause_final (true|false) - Pauses all monitor drawing after the solver ends
940: . -snes_fd (true|false) - use finite differences to compute Jacobian; very slow, only for testing
941: . -snes_fd_color (true|false) - use finite differences with coloring to compute Jacobian
942: . -snes_converged_reason viewer_specification - print the reason for convergence/divergence after each solve
943: . -npc_snes_type type - the `SNES` type to use as a nonlinear preconditioner
944: . -snes_test_jacobian [threshold] - compare the user provided Jacobian with one computed via finite differences to check for errors.
945: If a threshold is given, display only those entries whose difference is greater than the threshold.
946: - -snes_test_jacobian_view viewer_specification - display the user provided Jacobian, the finite difference Jacobian and the difference between them
947: to help users detect the location of errors in the user provided Jacobian.
949: Options Database Keys for Eisenstat-Walker method:
950: + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
951: . -snes_ksp_ew_version ver - version of Eisenstat-Walker method
952: . -snes_ksp_ew_rtol0 rtol0 - Sets rtol0
953: . -snes_ksp_ew_rtolmax rtolmax - Sets rtolmax
954: . -snes_ksp_ew_gamma gamma - Sets gamma
955: . -snes_ksp_ew_alpha alpha - Sets alpha
956: . -snes_ksp_ew_alpha2 alpha2 - Sets alpha2
957: - -snes_ksp_ew_threshold threshold - Sets threshold
959: Level: beginner
961: Notes:
962: See `PetscOptionsCreateViewer()` for the format of `viewer_specification`
964: See `KSPSetFromOptions()` for the `KSP` options database keys
966: To see all options, run your program with the -help option or consult the users manual
968: See `SNESLineSearchSetFromOptions()` for all the line search options available
970: `SNES` supports three approaches for computing (approximate) Jacobians: user provided via `SNESSetJacobian()`, matrix-free using `MatCreateSNESMF()`,
971: and computing explicitly with
972: finite differences and coloring using `MatFDColoring`. It is also possible to use automatic differentiation and the `MatFDColoring` object.
974: .seealso: [](ch_snes), `SNESType`, `SNESSetOptionsPrefix()`, `SNESResetFromOptions()`, `SNES`, `SNESCreate()`, `MatCreateSNESMF()`, `MatFDColoring`, `SNESLineSearchSetFromOptions()`
975: @*/
976: PetscErrorCode SNESSetFromOptions(SNES snes)
977: {
978: PetscBool flg, pcset, persist, set;
979: PetscInt i, indx, lag, grids, max_its, max_funcs;
980: const char *deft = SNESNEWTONLS;
981: const char *convtests[] = {"default", "skip", "correct_pressure"};
982: SNESKSPEW *kctx = NULL;
983: char type[256], monfilename[PETSC_MAX_PATH_LEN], ewprefix[256];
984: PCSide pcside;
985: const char *optionsprefix;
986: PetscReal rtol, abstol, stol;
988: PetscFunctionBegin;
990: PetscCall(SNESRegisterAll());
991: PetscObjectOptionsBegin((PetscObject)snes);
992: if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
993: PetscCall(PetscOptionsFList("-snes_type", "Nonlinear solver method", "SNESSetType", SNESList, deft, type, sizeof(type), &flg));
994: if (flg) PetscCall(SNESSetType(snes, type));
995: else if (!((PetscObject)snes)->type_name) PetscCall(SNESSetType(snes, deft));
997: abstol = snes->abstol;
998: rtol = snes->rtol;
999: stol = snes->stol;
1000: max_its = snes->max_its;
1001: max_funcs = snes->max_funcs;
1002: PetscCall(PetscOptionsReal("-snes_rtol", "Stop if decrease in function norm less than", "SNESSetTolerances", snes->rtol, &rtol, NULL));
1003: PetscCall(PetscOptionsReal("-snes_atol", "Stop if function norm less than", "SNESSetTolerances", snes->abstol, &abstol, NULL));
1004: PetscCall(PetscOptionsReal("-snes_stol", "Stop if step length less than", "SNESSetTolerances", snes->stol, &stol, NULL));
1005: PetscCall(PetscOptionsInt("-snes_max_it", "Maximum iterations", "SNESSetTolerances", snes->max_its, &max_its, NULL));
1006: PetscCall(PetscOptionsInt("-snes_max_funcs", "Maximum function evaluations", "SNESSetTolerances", snes->max_funcs, &max_funcs, NULL));
1007: PetscCall(SNESSetTolerances(snes, abstol, rtol, stol, max_its, max_funcs));
1009: PetscCall(PetscOptionsReal("-snes_divergence_tolerance", "Stop if residual norm increases by this factor", "SNESSetDivergenceTolerance", snes->divtol, &snes->divtol, &flg));
1010: if (flg) PetscCall(SNESSetDivergenceTolerance(snes, snes->divtol));
1012: PetscCall(PetscOptionsInt("-snes_max_fail", "Maximum nonlinear step failures", "SNESSetMaxNonlinearStepFailures", snes->maxFailures, &snes->maxFailures, &flg));
1013: if (flg) PetscCall(SNESSetMaxNonlinearStepFailures(snes, snes->maxFailures));
1015: PetscCall(PetscOptionsInt("-snes_max_linear_solve_fail", "Maximum failures in linear solves allowed", "SNESSetMaxLinearSolveFailures", snes->maxLinearSolveFailures, &snes->maxLinearSolveFailures, &flg));
1016: if (flg) PetscCall(SNESSetMaxLinearSolveFailures(snes, snes->maxLinearSolveFailures));
1018: PetscCall(PetscOptionsBool("-snes_error_if_not_converged", "Generate error if solver does not converge", "SNESSetErrorIfNotConverged", snes->errorifnotconverged, &snes->errorifnotconverged, NULL));
1019: PetscCall(PetscOptionsBool("-snes_force_iteration", "Force SNESSolve() to take at least one iteration", "SNESSetForceIteration", snes->forceiteration, &snes->forceiteration, NULL));
1020: PetscCall(PetscOptionsBool("-snes_check_jacobian_domain_error", "Check Jacobian domain error after Jacobian evaluation", "SNESCheckJacobianDomainError", snes->checkjacdomainerror, &snes->checkjacdomainerror, NULL));
1022: PetscCall(PetscOptionsInt("-snes_lag_preconditioner", "How often to rebuild preconditioner", "SNESSetLagPreconditioner", snes->lagpreconditioner, &lag, &flg));
1023: if (flg) {
1024: 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");
1025: PetscCall(SNESSetLagPreconditioner(snes, lag));
1026: }
1027: PetscCall(PetscOptionsBool("-snes_lag_preconditioner_persists", "Preconditioner lagging through multiple SNES solves", "SNESSetLagPreconditionerPersists", snes->lagjac_persist, &persist, &flg));
1028: if (flg) PetscCall(SNESSetLagPreconditionerPersists(snes, persist));
1029: PetscCall(PetscOptionsInt("-snes_lag_jacobian", "How often to rebuild Jacobian", "SNESSetLagJacobian", snes->lagjacobian, &lag, &flg));
1030: if (flg) {
1031: 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");
1032: PetscCall(SNESSetLagJacobian(snes, lag));
1033: }
1034: PetscCall(PetscOptionsBool("-snes_lag_jacobian_persists", "Jacobian lagging through multiple SNES solves", "SNESSetLagJacobianPersists", snes->lagjac_persist, &persist, &flg));
1035: if (flg) PetscCall(SNESSetLagJacobianPersists(snes, persist));
1037: PetscCall(PetscOptionsInt("-snes_grid_sequence", "Use grid sequencing to generate initial guess", "SNESSetGridSequence", snes->gridsequence, &grids, &flg));
1038: if (flg) PetscCall(SNESSetGridSequence(snes, grids));
1040: PetscCall(PetscOptionsEList("-snes_convergence_test", "Convergence test", "SNESSetConvergenceTest", convtests, PETSC_STATIC_ARRAY_LENGTH(convtests), "default", &indx, &flg));
1041: if (flg) {
1042: switch (indx) {
1043: case 0:
1044: PetscCall(SNESSetConvergenceTest(snes, SNESConvergedDefault, NULL, NULL));
1045: break;
1046: case 1:
1047: PetscCall(SNESSetConvergenceTest(snes, SNESConvergedSkip, NULL, NULL));
1048: break;
1049: case 2:
1050: PetscCall(SNESSetConvergenceTest(snes, SNESConvergedCorrectPressure, NULL, NULL));
1051: break;
1052: }
1053: }
1055: PetscCall(PetscOptionsEList("-snes_norm_schedule", "SNES Norm schedule", "SNESSetNormSchedule", SNESNormSchedules, 5, "function", &indx, &flg));
1056: if (flg) PetscCall(SNESSetNormSchedule(snes, (SNESNormSchedule)indx));
1058: PetscCall(PetscOptionsEList("-snes_function_type", "SNES Norm schedule", "SNESSetFunctionType", SNESFunctionTypes, 2, "unpreconditioned", &indx, &flg));
1059: if (flg) PetscCall(SNESSetFunctionType(snes, (SNESFunctionType)indx));
1061: kctx = (SNESKSPEW *)snes->kspconvctx;
1063: PetscCall(PetscOptionsBool("-snes_ksp_ew", "Use Eisentat-Walker linear system convergence test", "SNESKSPSetUseEW", snes->ksp_ewconv, &snes->ksp_ewconv, NULL));
1065: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1066: PetscCall(PetscSNPrintf(ewprefix, sizeof(ewprefix), "%s%s", optionsprefix ? optionsprefix : "", "snes_"));
1067: PetscCall(SNESEWSetFromOptions_Private(kctx, PETSC_TRUE, PetscObjectComm((PetscObject)snes), ewprefix));
1069: flg = PETSC_FALSE;
1070: PetscCall(PetscOptionsBool("-snes_monitor_cancel", "Remove all monitors", "SNESMonitorCancel", flg, &flg, &set));
1071: if (set && flg) PetscCall(SNESMonitorCancel(snes));
1073: PetscCall(PetscOptionsDeprecated("-snes_monitor_short", "-snes_monitor", "3.26", NULL));
1074: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor", "Monitor norm of function", "SNESMonitorDefault", SNESMonitorDefault, SNESMonitorDefaultSetUp));
1075: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_range", "Monitor range of elements of function", "SNESMonitorRange", SNESMonitorRange, NULL));
1077: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_ratio", "Monitor ratios of the norm of function for consecutive steps", "SNESMonitorRatio", SNESMonitorRatio, SNESMonitorRatioSetUp));
1078: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_field", "Monitor norm of function (split into fields)", "SNESMonitorDefaultField", SNESMonitorDefaultField, NULL));
1079: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_solution", "View solution at each iteration", "SNESMonitorSolution", SNESMonitorSolution, NULL));
1080: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_solution_update", "View correction at each iteration", "SNESMonitorSolutionUpdate", SNESMonitorSolutionUpdate, NULL));
1081: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_residual", "View residual at each iteration", "SNESMonitorResidual", SNESMonitorResidual, NULL));
1082: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_jacupdate_spectrum", "Print the change in the spectrum of the Jacobian", "SNESMonitorJacUpdateSpectrum", SNESMonitorJacUpdateSpectrum, NULL));
1083: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_fields", "Monitor norm of function per field", "SNESMonitorSet", SNESMonitorFields, NULL));
1084: PetscCall(PetscOptionsBool("-snes_monitor_pause_final", "Pauses all draw monitors at the final iterate", "SNESMonitorPauseFinal_Internal", PETSC_FALSE, &snes->pauseFinal, NULL));
1086: PetscCall(PetscOptionsString("-snes_monitor_python", "Use Python function", "SNESMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1087: if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)snes, monfilename));
1089: flg = PETSC_FALSE;
1090: PetscCall(PetscOptionsBool("-snes_monitor_lg_range", "Plot function range at each iteration", "SNESMonitorLGRange", flg, &flg, NULL));
1091: if (flg) {
1092: PetscViewer ctx;
1094: PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, &ctx));
1095: PetscCall(SNESMonitorSet(snes, SNESMonitorLGRange, ctx, (PetscCtxDestroyFn *)PetscViewerDestroy));
1096: }
1098: PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
1099: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_converged_reason", &snes->convergedreasonviewer, &snes->convergedreasonformat, NULL));
1100: flg = PETSC_FALSE;
1101: PetscCall(PetscOptionsBool("-snes_converged_reason_view_cancel", "Remove all converged reason viewers", "SNESConvergedReasonViewCancel", flg, &flg, &set));
1102: if (set && flg) PetscCall(SNESConvergedReasonViewCancel(snes));
1104: flg = PETSC_FALSE;
1105: PetscCall(PetscOptionsBool("-snes_fd", "Use finite differences (slow) to compute Jacobian", "SNESComputeJacobianDefault", flg, &flg, NULL));
1106: if (flg) {
1107: void *functx;
1108: DM dm;
1109: PetscCall(SNESGetDM(snes, &dm));
1110: PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1111: PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
1112: PetscCall(SNESSetJacobian(snes, snes->jacobian, snes->jacobian_pre, SNESComputeJacobianDefault, functx));
1113: PetscCall(PetscInfo(snes, "Setting default finite difference Jacobian matrix\n"));
1114: }
1116: flg = PETSC_FALSE;
1117: PetscCall(PetscOptionsBool("-snes_fd_function", "Use finite differences (slow) to compute function from user objective", "SNESObjectiveComputeFunctionDefaultFD", flg, &flg, NULL));
1118: if (flg) PetscCall(SNESSetFunction(snes, NULL, SNESObjectiveComputeFunctionDefaultFD, NULL));
1120: flg = PETSC_FALSE;
1121: PetscCall(PetscOptionsBool("-snes_fd_color", "Use finite differences with coloring to compute Jacobian", "SNESComputeJacobianDefaultColor", flg, &flg, NULL));
1122: if (flg) {
1123: DM dm;
1124: PetscCall(SNESGetDM(snes, &dm));
1125: PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1126: PetscCall(SNESSetJacobian(snes, snes->jacobian, snes->jacobian_pre, SNESComputeJacobianDefaultColor, NULL));
1127: PetscCall(PetscInfo(snes, "Setting default finite difference coloring Jacobian matrix\n"));
1128: }
1130: flg = PETSC_FALSE;
1131: 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));
1132: if (flg && snes->mf_operator) {
1133: snes->mf_operator = PETSC_TRUE;
1134: snes->mf = PETSC_TRUE;
1135: }
1136: flg = PETSC_FALSE;
1137: PetscCall(PetscOptionsBool("-snes_mf", "Use a Matrix-Free Jacobian with no preconditioner by default", "SNESSetUseMatrixFree", PETSC_FALSE, &snes->mf, &flg));
1138: if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1139: PetscCall(PetscOptionsInt("-snes_mf_version", "Matrix-Free routines version 1 or 2", "None", snes->mf_version, &snes->mf_version, NULL));
1141: PetscCall(PetscOptionsName("-snes_test_function", "Compare hand-coded and finite difference functions", "None", &snes->testFunc));
1142: PetscCall(PetscOptionsName("-snes_test_jacobian", "Compare hand-coded and finite difference Jacobians", "None", &snes->testJac));
1144: flg = PETSC_FALSE;
1145: PetscCall(SNESGetNPCSide(snes, &pcside));
1146: PetscCall(PetscOptionsEnum("-snes_npc_side", "SNES nonlinear preconditioner side", "SNESSetNPCSide", PCSides, (PetscEnum)pcside, (PetscEnum *)&pcside, &flg));
1147: if (flg) PetscCall(SNESSetNPCSide(snes, pcside));
1149: #if PetscDefined(HAVE_SAWS)
1150: /*
1151: Publish convergence information using SAWs
1152: */
1153: flg = PETSC_FALSE;
1154: PetscCall(PetscOptionsBool("-snes_monitor_saws", "Publish SNES progress using SAWs", "SNESMonitorSet", flg, &flg, NULL));
1155: if (flg) {
1156: PetscCtx ctx;
1157: PetscCall(SNESMonitorSAWsCreate(snes, &ctx));
1158: PetscCall(SNESMonitorSet(snes, SNESMonitorSAWs, ctx, SNESMonitorSAWsDestroy));
1159: }
1160: #endif
1161: #if PetscDefined(HAVE_SAWS)
1162: {
1163: PetscBool set;
1164: flg = PETSC_FALSE;
1165: PetscCall(PetscOptionsBool("-snes_saws_block", "Block for SAWs at end of SNESSolve", "PetscObjectSAWsBlock", ((PetscObject)snes)->amspublishblock, &flg, &set));
1166: if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)snes, flg));
1167: }
1168: #endif
1170: for (i = 0; i < numberofsetfromoptions; i++) PetscCall((*othersetfromoptions[i])(snes));
1172: PetscTryTypeMethod(snes, setfromoptions, PetscOptionsObject);
1174: /* process any options handlers added with PetscObjectAddOptionsHandler() */
1175: PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)snes, PetscOptionsObject));
1176: PetscOptionsEnd();
1178: if (snes->linesearch) {
1179: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
1180: PetscCall(SNESLineSearchSetFromOptions(snes->linesearch));
1181: }
1183: /* if user has set the SNES NPC type via options database, create it. */
1184: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1185: PetscCall(PetscOptionsHasName(((PetscObject)snes)->options, optionsprefix, "-npc_snes_type", &pcset));
1186: if (pcset && !snes->npc) PetscCall(SNESGetNPC(snes, &snes->npc));
1188: if (snes->usesksp) {
1189: PC pc;
1190: PCType pctype;
1192: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
1193: PetscCall(KSPSetOperators(snes->ksp, snes->jacobian, snes->jacobian_pre));
1194: PetscCall(KSPGetPC(snes->ksp, &pc));
1195: PetscCall(PCGetType(pc, &pctype));
1196: /* If the first two conditions in the following conditional are true, we know a matrix-free Mat
1197: will be used eventually with the PC, but we cannot provide the matrix-free Mat to the PC here
1198: since we do not have enough information to construct it here (it is constructed after the
1199: start of SNESSetUp()). If we do not set the PCNONE here, then the PCSetFromOptions() called
1200: from KSPSetFromOptions() below will use PCGetDefaultType_Private() to set a PCType
1201: appropriate for the current pc->pmat that will likely not work for the matrix-free Mat, thus
1202: producing a later confusing error message. A significant refactoring of how SNES handles
1203: matrix-free Mat would be needed to eliminate the next line of code. Note that if the PC type
1204: has already been set (third condition), we do not override it. The fourth condition exempts
1205: left-side nonlinear preconditioners, which require a real PC */
1206: if (snes->mf && !snes->mf_operator && !pctype && !(snes->npcside == PC_LEFT && snes->npc)) {
1207: PetscCall(PetscInfo(snes, "Setting PCNONE since no PC type was set and the Jacobian will be matrix-free\n"));
1208: PetscCall(PCSetType(pc, PCNONE));
1209: }
1210: PetscCall(KSPSetFromOptions(snes->ksp));
1211: }
1213: if (snes->npc) PetscCall(SNESSetFromOptions(snes->npc));
1214: snes->setfromoptionscalled++;
1215: PetscFunctionReturn(PETSC_SUCCESS);
1216: }
1218: /*@
1219: SNESResetFromOptions - Sets various `SNES` and `KSP` parameters from user options ONLY if the `SNESSetFromOptions()` was previously called
1221: Collective
1223: Input Parameter:
1224: . snes - the `SNES` context
1226: Level: advanced
1228: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESSetOptionsPrefix()`
1229: @*/
1230: PetscErrorCode SNESResetFromOptions(SNES snes)
1231: {
1232: PetscFunctionBegin;
1233: if (snes->setfromoptionscalled) PetscCall(SNESSetFromOptions(snes));
1234: PetscFunctionReturn(PETSC_SUCCESS);
1235: }
1237: /*@
1238: SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1239: the nonlinear solvers.
1241: Logically Collective; No Fortran Support
1243: Input Parameters:
1244: + snes - the `SNES` context
1245: . compute - function to compute the context
1246: - destroy - function to destroy the context, see `PetscCtxDestroyFn` for the calling sequence
1248: Calling sequence of `compute`:
1249: + snes - the `SNES` context
1250: - ctx - context to be computed
1252: Level: intermediate
1254: Note:
1255: This routine is useful if you are performing grid sequencing or using `SNESFAS` and need the appropriate context generated for each level.
1257: Use `SNESSetApplicationContext()` to see the context immediately
1259: .seealso: [](ch_snes), `SNESGetApplicationContext()`, `SNESSetApplicationContext()`, `PetscCtxDestroyFn`
1260: @*/
1261: PetscErrorCode SNESSetComputeApplicationContext(SNES snes, PetscErrorCode (*compute)(SNES snes, PetscCtxRt ctx), PetscCtxDestroyFn *destroy)
1262: {
1263: PetscFunctionBegin;
1265: snes->ops->ctxcompute = compute;
1266: snes->ops->ctxdestroy = destroy;
1267: PetscFunctionReturn(PETSC_SUCCESS);
1268: }
1270: /*@
1271: SNESSetApplicationContext - Sets the optional user-defined context for the nonlinear solvers.
1273: Logically Collective
1275: Input Parameters:
1276: + snes - the `SNES` context
1277: - ctx - the application context
1279: Level: intermediate
1281: Notes:
1282: Users can provide a context when constructing the `SNES` options and then access it inside their function, Jacobian computation, or other evaluation function
1283: with `SNESGetApplicationContext()`
1285: To provide a function that computes the context for you use `SNESSetComputeApplicationContext()`
1287: Fortran Note:
1288: This only works when `ctx` is a Fortran derived type (it cannot be a `PetscObject`), we recommend writing a Fortran interface definition for this
1289: function that tells the Fortran compiler the derived data type that is passed in as the `ctx` argument. See `SNESGetApplicationContext()` for
1290: an example.
1292: .seealso: [](ch_snes), `SNES`, `SNESSetComputeApplicationContext()`, `SNESGetApplicationContext()`
1293: @*/
1294: PetscErrorCode SNESSetApplicationContext(SNES snes, PetscCtx ctx)
1295: {
1296: KSP ksp;
1298: PetscFunctionBegin;
1300: PetscCall(SNESGetKSP(snes, &ksp));
1301: PetscCall(KSPSetApplicationContext(ksp, ctx));
1302: snes->ctx = ctx;
1303: PetscFunctionReturn(PETSC_SUCCESS);
1304: }
1306: /*@
1307: SNESGetApplicationContext - Gets the user-defined context for the
1308: nonlinear solvers set with `SNESGetApplicationContext()` or `SNESSetComputeApplicationContext()`
1310: Not Collective
1312: Input Parameter:
1313: . snes - `SNES` context
1315: Output Parameter:
1316: . ctx - the application context
1318: Level: intermediate
1320: Fortran Notes:
1321: This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
1322: .vb
1323: type(tUsertype), pointer :: ctx
1324: .ve
1326: .seealso: [](ch_snes), `SNESSetApplicationContext()`, `SNESSetComputeApplicationContext()`
1327: @*/
1328: PetscErrorCode SNESGetApplicationContext(SNES snes, PetscCtxRt ctx)
1329: {
1330: PetscFunctionBegin;
1332: *(void **)ctx = snes->ctx;
1333: PetscFunctionReturn(PETSC_SUCCESS);
1334: }
1336: /*@
1337: SNESSetUseMatrixFree - indicates that `SNES` should use matrix-free finite difference matrix-vector products to apply the Jacobian.
1339: Logically Collective
1341: Input Parameters:
1342: + snes - `SNES` context
1343: . mf_operator - use matrix-free only for the Amat used by `SNESSetJacobian()`, this means the user provided Pmat will continue to be used
1344: - 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
1345: this option no matrix-element based preconditioners can be used in the linear solve since the matrix won't be explicitly available
1347: Options Database Keys:
1348: + -snes_mf_operator - use matrix-free only for the mat operator
1349: . -snes_mf - use matrix-free for both the mat and pmat operator
1350: . -snes_fd_color - compute the Jacobian via coloring and finite differences.
1351: - -snes_fd - compute the Jacobian via finite differences (slow)
1353: Level: intermediate
1355: Notes:
1356: `SNES` supports three approaches for computing (approximate) Jacobians: user provided via `SNESSetJacobian()`, matrix-free using `MatCreateSNESMF()`,
1357: and computing explicitly with
1358: finite differences and coloring using `MatFDColoring`. It is also possible to use automatic differentiation and the `MatFDColoring` object.
1360: When `mf` is used, `SNESSetFromOptions()` sets the `KSP`'s `PC` to `PCNONE` unless a `PC` type has already been selected.
1362: .seealso: [](ch_snes), `SNES`, `SNESGetUseMatrixFree()`, `MatCreateSNESMF()`, `SNESComputeJacobianDefaultColor()`, `MatFDColoring`
1363: @*/
1364: PetscErrorCode SNESSetUseMatrixFree(SNES snes, PetscBool mf_operator, PetscBool mf)
1365: {
1366: PetscFunctionBegin;
1370: snes->mf = mf_operator ? PETSC_TRUE : mf;
1371: snes->mf_operator = mf_operator;
1372: PetscFunctionReturn(PETSC_SUCCESS);
1373: }
1375: /*@
1376: SNESGetUseMatrixFree - indicates if the `SNES` uses matrix-free finite difference matrix vector products to apply the Jacobian.
1378: Not Collective, but the resulting flags will be the same on all MPI processes
1380: Input Parameter:
1381: . snes - `SNES` context
1383: Output Parameters:
1384: + mf_operator - use matrix-free only for the Amat used by `SNESSetJacobian()`, this means the user provided Pmat will continue to be used
1385: - mf - use matrix-free for both the Amat and Pmat used by `SNESSetJacobian()`, both the Amat and Pmat set in `SNESSetJacobian()` will be ignored
1387: Level: intermediate
1389: .seealso: [](ch_snes), `SNES`, `SNESSetUseMatrixFree()`, `MatCreateSNESMF()`
1390: @*/
1391: PetscErrorCode SNESGetUseMatrixFree(SNES snes, PetscBool *mf_operator, PetscBool *mf)
1392: {
1393: PetscFunctionBegin;
1395: if (mf) *mf = snes->mf;
1396: if (mf_operator) *mf_operator = snes->mf_operator;
1397: PetscFunctionReturn(PETSC_SUCCESS);
1398: }
1400: /*@
1401: SNESGetIterationNumber - Gets the number of nonlinear iterations completed in the current or most recent `SNESSolve()`
1403: Not Collective
1405: Input Parameter:
1406: . snes - `SNES` context
1408: Output Parameter:
1409: . iter - iteration number
1411: Level: intermediate
1413: Notes:
1414: For example, during the computation of iteration 2 this would return 1.
1416: This is useful for using lagged Jacobians (where one does not recompute the
1417: Jacobian at each `SNES` iteration). For example, the code
1418: .vb
1419: ierr = SNESGetIterationNumber(snes,&it);
1420: if (!(it % 2)) {
1421: [compute Jacobian here]
1422: }
1423: .ve
1424: can be used in your function that computes the Jacobian to cause the Jacobian to be
1425: recomputed every second `SNES` iteration. See also `SNESSetLagJacobian()`
1427: After the `SNES` solve is complete this will return the number of nonlinear iterations used.
1429: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetLagJacobian()`, `SNESGetLinearSolveIterations()`, `SNESSetMonitor()`
1430: @*/
1431: PetscErrorCode SNESGetIterationNumber(SNES snes, PetscInt *iter)
1432: {
1433: PetscFunctionBegin;
1435: PetscAssertPointer(iter, 2);
1436: *iter = snes->iter;
1437: PetscFunctionReturn(PETSC_SUCCESS);
1438: }
1440: /*@
1441: SNESSetIterationNumber - Sets the current iteration number.
1443: Not Collective
1445: Input Parameters:
1446: + snes - `SNES` context
1447: - iter - iteration number
1449: Level: developer
1451: Note:
1452: This should only be called inside a `SNES` nonlinear solver.
1454: .seealso: [](ch_snes), `SNESGetLinearSolveIterations()`
1455: @*/
1456: PetscErrorCode SNESSetIterationNumber(SNES snes, PetscInt iter)
1457: {
1458: PetscFunctionBegin;
1460: PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
1461: snes->iter = iter;
1462: PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
1463: PetscFunctionReturn(PETSC_SUCCESS);
1464: }
1466: /*@
1467: SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1468: taken by the nonlinear solver in the current or most recent `SNESSolve()` .
1470: Not Collective
1472: Input Parameter:
1473: . snes - `SNES` context
1475: Output Parameter:
1476: . nfails - number of unsuccessful steps attempted
1478: Level: intermediate
1480: Notes:
1481: A failed step is a step that was generated and taken but did not satisfy the requested step criteria. For example,
1482: the `SNESLineSearchApply()` could not generate a sufficient decrease in the function norm (in fact it may have produced an increase).
1484: Taken steps that produce a infinity or NaN in the function evaluation or generate a `SNESSetFunctionDomainError()`
1485: will always immediately terminate the `SNESSolve()` regardless of the value of `maxFails`.
1487: `SNESSetMaxNonlinearStepFailures()` determines how many unsuccessful steps are allowed before the `SNESSolve()` terminates
1489: This counter is reset to zero for each successive call to `SNESSolve()`.
1491: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1492: `SNESSetMaxNonlinearStepFailures()`, `SNESGetMaxNonlinearStepFailures()`
1493: @*/
1494: PetscErrorCode SNESGetNonlinearStepFailures(SNES snes, PetscInt *nfails)
1495: {
1496: PetscFunctionBegin;
1498: PetscAssertPointer(nfails, 2);
1499: *nfails = snes->numFailures;
1500: PetscFunctionReturn(PETSC_SUCCESS);
1501: }
1503: /*@
1504: SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1505: attempted by the nonlinear solver before it gives up and returns unconverged or generates an error
1507: Not Collective
1509: Input Parameters:
1510: + snes - `SNES` context
1511: - maxFails - maximum of unsuccessful steps allowed, use `PETSC_UNLIMITED` to have no limit on the number of failures
1513: Options Database Key:
1514: . -snes_max_fail n - maximum number of unsuccessful steps allowed
1516: Level: intermediate
1518: Note:
1519: A failed step is a step that was generated and taken but did not satisfy the requested criteria. For example,
1520: the `SNESLineSearchApply()` could not generate a sufficient decrease in the function norm (in fact it may have produced an increase).
1522: Taken steps that produce a infinity or NaN in the function evaluation or generate a `SNESSetFunctionDomainError()`
1523: will always immediately terminate the `SNESSolve()` regardless of the value of `maxFails`.
1525: Developer Note:
1526: The options database key is wrong for this function name
1528: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`,
1529: `SNESGetLinearSolveFailures()`, `SNESGetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`, `SNESCheckLineSearchFailure()`
1530: @*/
1531: PetscErrorCode SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1532: {
1533: PetscFunctionBegin;
1536: if (maxFails == PETSC_UNLIMITED) {
1537: snes->maxFailures = PETSC_INT_MAX;
1538: } else {
1539: PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1540: snes->maxFailures = maxFails;
1541: }
1542: PetscFunctionReturn(PETSC_SUCCESS);
1543: }
1545: /*@
1546: SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1547: attempted by the nonlinear solver before it gives up and returns unconverged or generates an error
1549: Not Collective
1551: Input Parameter:
1552: . snes - `SNES` context
1554: Output Parameter:
1555: . maxFails - maximum of unsuccessful steps
1557: Level: intermediate
1559: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1560: `SNESSetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
1561: @*/
1562: PetscErrorCode SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1563: {
1564: PetscFunctionBegin;
1566: PetscAssertPointer(maxFails, 2);
1567: *maxFails = snes->maxFailures;
1568: PetscFunctionReturn(PETSC_SUCCESS);
1569: }
1571: /*@
1572: SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1573: done by the `SNES` object in the current or most recent `SNESSolve()`
1575: Not Collective
1577: Input Parameter:
1578: . snes - `SNES` context
1580: Output Parameter:
1581: . nfuncs - number of evaluations
1583: Level: intermediate
1585: Note:
1586: Reset every time `SNESSolve()` is called unless `SNESSetCountersReset()` is used.
1588: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, `SNESSetCountersReset()`
1589: @*/
1590: PetscErrorCode SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1591: {
1592: PetscFunctionBegin;
1594: PetscAssertPointer(nfuncs, 2);
1595: *nfuncs = snes->nfuncs;
1596: PetscFunctionReturn(PETSC_SUCCESS);
1597: }
1599: /*@
1600: SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1601: linear solvers in the current or most recent `SNESSolve()`
1603: Not Collective
1605: Input Parameter:
1606: . snes - `SNES` context
1608: Output Parameter:
1609: . nfails - number of failed solves
1611: Options Database Key:
1612: . -snes_max_linear_solve_fail num - The number of failures before the solve is terminated
1614: Level: intermediate
1616: Note:
1617: This counter is reset to zero for each successive call to `SNESSolve()`.
1619: .seealso: [](ch_snes), `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1620: @*/
1621: PetscErrorCode SNESGetLinearSolveFailures(SNES snes, PetscInt *nfails)
1622: {
1623: PetscFunctionBegin;
1625: PetscAssertPointer(nfails, 2);
1626: *nfails = snes->numLinearSolveFailures;
1627: PetscFunctionReturn(PETSC_SUCCESS);
1628: }
1630: /*@
1631: SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1632: allowed before `SNES` returns with a diverged reason of `SNES_DIVERGED_LINEAR_SOLVE`
1634: Logically Collective
1636: Input Parameters:
1637: + snes - `SNES` context
1638: - maxFails - maximum allowed linear solve failures, use `PETSC_UNLIMITED` to have no limit on the number of failures
1640: Options Database Key:
1641: . -snes_max_linear_solve_fail num - The number of failures before the solve is terminated
1643: Level: intermediate
1645: Note:
1646: By default this is 0; that is `SNES` returns on the first failed linear solve
1648: Developer Note:
1649: The options database key is wrong for this function name
1651: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`
1652: @*/
1653: PetscErrorCode SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1654: {
1655: PetscFunctionBegin;
1659: if (maxFails == PETSC_UNLIMITED) {
1660: snes->maxLinearSolveFailures = PETSC_INT_MAX;
1661: } else {
1662: PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1663: snes->maxLinearSolveFailures = maxFails;
1664: }
1665: PetscFunctionReturn(PETSC_SUCCESS);
1666: }
1668: /*@
1669: SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1670: are allowed before `SNES` returns as unsuccessful
1672: Not Collective
1674: Input Parameter:
1675: . snes - `SNES` context
1677: Output Parameter:
1678: . maxFails - maximum of unsuccessful solves allowed
1680: Level: intermediate
1682: Note:
1683: By default this is 1; that is `SNES` returns on the first failed linear solve
1685: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1686: @*/
1687: PetscErrorCode SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1688: {
1689: PetscFunctionBegin;
1691: PetscAssertPointer(maxFails, 2);
1692: *maxFails = snes->maxLinearSolveFailures;
1693: PetscFunctionReturn(PETSC_SUCCESS);
1694: }
1696: /*@
1697: SNESGetLinearSolveIterations - Gets the total number of linear iterations
1698: used by the nonlinear solver in the most recent `SNESSolve()`
1700: Not Collective
1702: Input Parameter:
1703: . snes - `SNES` context
1705: Output Parameter:
1706: . lits - number of linear iterations
1708: Level: intermediate
1710: Notes:
1711: This counter is reset to zero for each successive call to `SNESSolve()` unless `SNESSetCountersReset()` is used.
1713: 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
1714: then call `KSPGetIterationNumber()` after the failed solve.
1716: .seealso: [](ch_snes), `SNES`, `SNESGetIterationNumber()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESSetCountersReset()`
1717: @*/
1718: PetscErrorCode SNESGetLinearSolveIterations(SNES snes, PetscInt *lits)
1719: {
1720: PetscFunctionBegin;
1722: PetscAssertPointer(lits, 2);
1723: *lits = snes->linear_its;
1724: PetscFunctionReturn(PETSC_SUCCESS);
1725: }
1727: /*@
1728: SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1729: are reset every time `SNESSolve()` is called.
1731: Logically Collective
1733: Input Parameters:
1734: + snes - `SNES` context
1735: - reset - whether to reset the counters or not, defaults to `PETSC_TRUE`
1737: Level: developer
1739: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1740: @*/
1741: PetscErrorCode SNESSetCountersReset(SNES snes, PetscBool reset)
1742: {
1743: PetscFunctionBegin;
1746: snes->counters_reset = reset;
1747: PetscFunctionReturn(PETSC_SUCCESS);
1748: }
1750: /*@
1751: SNESResetCounters - Reset counters for linear iterations and function evaluations.
1753: Logically Collective
1755: Input Parameters:
1756: . snes - `SNES` context
1758: Level: developer
1760: Note:
1761: It honors the flag set with `SNESSetCountersReset()`
1763: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1764: @*/
1765: PetscErrorCode SNESResetCounters(SNES snes)
1766: {
1767: PetscFunctionBegin;
1769: if (snes->counters_reset) {
1770: snes->nfuncs = 0;
1771: snes->linear_its = 0;
1772: snes->numFailures = 0;
1773: }
1774: PetscFunctionReturn(PETSC_SUCCESS);
1775: }
1777: /*@
1778: SNESSetKSP - Sets a `KSP` context for the `SNES` object to use
1780: Not Collective, but the `SNES` and `KSP` objects must live on the same `MPI_Comm`
1782: Input Parameters:
1783: + snes - the `SNES` context
1784: - ksp - the `KSP` context
1786: Level: developer
1788: Notes:
1789: The `SNES` object already has its `KSP` object, you can obtain with `SNESGetKSP()`
1790: so this routine is rarely needed.
1792: The `KSP` object that is already in the `SNES` object has its reference count
1793: decreased by one when this is called.
1795: .seealso: [](ch_snes), `SNES`, `KSP`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`
1796: @*/
1797: PetscErrorCode SNESSetKSP(SNES snes, KSP ksp)
1798: {
1799: PetscFunctionBegin;
1802: PetscCheckSameComm(snes, 1, ksp, 2);
1803: PetscCall(PetscObjectReference((PetscObject)ksp));
1804: PetscCall(PetscObjectDereference((PetscObject)snes->ksp));
1805: snes->ksp = ksp;
1806: PetscFunctionReturn(PETSC_SUCCESS);
1807: }
1809: /*@
1810: SNESParametersInitialize - Sets the base defaults for parameters in `snes`, updating a parameter's current value when it matches its previously recorded default.
1812: Logically collective
1814: Input Parameter:
1815: . snes - the `SNES` object
1817: Level: developer
1819: Notes:
1821: The base defaults are the non-type-specific values established when the `SNES` is created. A `SNESType` constructor may subsequently replace them with type-specific defaults.
1823: Developer Notes:
1825: `SNESCreate()` calls this routine to establish the base defaults. `SNESSetType()` calls it before constructing a new `SNESType`, so the recorded defaults associated with the previous type are replaced before the new type installs its own defaults.
1827: Default tracking is based on value equality, not on whether a setter was called. Consequently, an explicitly assigned value that equals the recorded default may be updated when the type changes.
1829: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
1830: `PetscObjectParameterSetDefault()`
1831: @*/
1832: PetscErrorCode SNESParametersInitialize(SNES snes)
1833: {
1834: PetscObjectParameterSetDefault(snes, max_its, 50);
1835: PetscObjectParameterSetDefault(snes, max_funcs, 10000);
1836: PetscObjectParameterSetDefault(snes, rtol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1837: PetscObjectParameterSetDefault(snes, abstol, PetscDefined(USE_REAL_SINGLE) ? 1.e-25 : 1.e-50);
1838: PetscObjectParameterSetDefault(snes, stol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1839: PetscObjectParameterSetDefault(snes, divtol, 1.e4);
1840: return PETSC_SUCCESS;
1841: }
1843: /*@
1844: SNESCreate - Creates a nonlinear solver context used to manage a set of nonlinear solves
1846: Collective
1848: Input Parameter:
1849: . comm - MPI communicator
1851: Output Parameter:
1852: . outsnes - the new `SNES` context
1854: Options Database Keys:
1855: + -snes_mf - Activates default matrix-free Jacobian-vector products, with no preconditioner by default
1856: . -snes_mf_operator - Activates default matrix-free Jacobian-vector products, and a user-provided matrix as set by `SNESSetJacobian()`
1857: . -snes_fd_coloring - uses a relative fast computation of the Jacobian using finite differences and a graph coloring
1858: - -snes_fd - Uses (slow!) finite differences to compute Jacobian
1860: Level: beginner
1862: Developer Notes:
1863: `SNES` always creates a `KSP` object even though many `SNES` methods do not use it. This is
1864: unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1865: particular method does use `KSP` and regulates if the information about the `KSP` is printed
1866: in `SNESView()`.
1868: `TSSetFromOptions()` does call `SNESSetFromOptions()` which can lead to users being confused
1869: by help messages about meaningless `SNES` options.
1871: `SNES` always creates the `snes->kspconvctx` even though it is used by only one type. This should be fixed.
1873: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
1874: @*/
1875: PetscErrorCode SNESCreate(MPI_Comm comm, SNES *outsnes)
1876: {
1877: SNES snes;
1878: SNESKSPEW *kctx;
1880: PetscFunctionBegin;
1881: PetscAssertPointer(outsnes, 2);
1882: PetscCall(SNESInitializePackage());
1884: PetscCall(PetscHeaderCreate(snes, SNES_CLASSID, "SNES", "Nonlinear solver", "SNES", comm, SNESDestroy, SNESView));
1885: snes->ops->converged = SNESConvergedDefault;
1886: snes->usesksp = PETSC_TRUE;
1887: snes->norm = 0.0;
1888: snes->xnorm = 0.0;
1889: snes->ynorm = 0.0;
1890: snes->normschedule = SNES_NORM_ALWAYS;
1891: snes->functype = SNES_FUNCTION_DEFAULT;
1892: snes->ttol = 0.0;
1894: snes->rnorm0 = 0;
1895: snes->nfuncs = 0;
1896: snes->numFailures = 0;
1897: snes->maxFailures = 1;
1898: snes->linear_its = 0;
1899: snes->lagjacobian = 1;
1900: snes->jac_iter = 0;
1901: snes->lagjac_persist = PETSC_FALSE;
1902: snes->lagpreconditioner = 1;
1903: snes->pre_iter = 0;
1904: snes->lagpre_persist = PETSC_FALSE;
1905: snes->numbermonitors = 0;
1906: snes->numberreasonviews = 0;
1907: snes->data = NULL;
1908: snes->setupcalled = PETSC_FALSE;
1909: snes->ksp_ewconv = PETSC_FALSE;
1910: snes->nwork = 0;
1911: snes->work = NULL;
1912: snes->nvwork = 0;
1913: snes->vwork = NULL;
1914: snes->conv_hist_len = 0;
1915: snes->conv_hist_max = 0;
1916: snes->conv_hist = NULL;
1917: snes->conv_hist_its = NULL;
1918: snes->conv_hist_reset = PETSC_TRUE;
1919: snes->counters_reset = PETSC_TRUE;
1920: snes->vec_func_init_set = PETSC_FALSE;
1921: snes->reason = SNES_CONVERGED_ITERATING;
1922: snes->npcside = PC_RIGHT;
1923: snes->setfromoptionscalled = 0;
1925: snes->mf = PETSC_FALSE;
1926: snes->mf_operator = PETSC_FALSE;
1927: snes->mf_version = 1;
1929: snes->numLinearSolveFailures = 0;
1930: snes->maxLinearSolveFailures = 1;
1932: snes->vizerotolerance = 1.e-8;
1933: snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE;
1935: /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
1936: snes->alwayscomputesfinalresidual = PETSC_FALSE;
1938: /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
1939: PetscCall(PetscNew(&kctx));
1941: snes->kspconvctx = kctx;
1942: kctx->version = 2;
1943: kctx->rtol_0 = 0.3; /* Eisenstat and Walker suggest rtol_0=.5, but
1944: this was too large for some test cases */
1945: kctx->rtol_last = 0.0;
1946: kctx->rtol_max = 0.9;
1947: kctx->gamma = 1.0;
1948: kctx->alpha = 0.5 * (1.0 + PetscSqrtReal(5.0));
1949: kctx->alpha2 = kctx->alpha;
1950: kctx->threshold = 0.1;
1951: kctx->lresid_last = 0.0;
1952: kctx->norm_last = 0.0;
1954: kctx->rk_last = 0.0;
1955: kctx->rk_last_2 = 0.0;
1956: kctx->rtol_last_2 = 0.0;
1957: kctx->v4_p1 = 0.1;
1958: kctx->v4_p2 = 0.4;
1959: kctx->v4_p3 = 0.7;
1960: kctx->v4_m1 = 0.8;
1961: kctx->v4_m2 = 0.5;
1962: kctx->v4_m3 = 0.1;
1963: kctx->v4_m4 = 0.5;
1965: PetscCall(SNESParametersInitialize(snes));
1966: *outsnes = snes;
1967: PetscFunctionReturn(PETSC_SUCCESS);
1968: }
1970: /*@
1971: SNESSetFunction - Sets the function evaluation routine and function
1972: vector for use by the `SNES` routines in solving systems of nonlinear
1973: equations.
1975: Logically Collective
1977: Input Parameters:
1978: + snes - the `SNES` context
1979: . r - vector to store function values, may be `NULL`
1980: . f - function evaluation routine; for calling sequence see `SNESFunctionFn`
1981: - ctx - [optional] user-defined context for private data for the
1982: function evaluation routine (may be `NULL`)
1984: Level: beginner
1986: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetPicard()`, `SNESFunctionFn`
1987: @*/
1988: PetscErrorCode SNESSetFunction(SNES snes, Vec r, SNESFunctionFn *f, PetscCtx ctx)
1989: {
1990: DM dm;
1992: PetscFunctionBegin;
1994: if (r) {
1996: PetscCheckSameComm(snes, 1, r, 2);
1997: PetscCall(PetscObjectReference((PetscObject)r));
1998: PetscCall(VecDestroy(&snes->vec_func));
1999: snes->vec_func = r;
2000: }
2001: /* update DMSNES
2002: We support incremental information; so update the function context only if r is not specified
2003: (which allows to disable the callbacks when both f and ctx are NULL),
2004: or, if r is specified, when at least one of f and ctx is not NULL */
2005: PetscCall(SNESGetDM(snes, &dm));
2006: if (!r || f || ctx) PetscCall(DMSNESSetFunction(dm, f, ctx));
2007: if (f == SNESPicardComputeFunction) PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
2008: PetscFunctionReturn(PETSC_SUCCESS);
2009: }
2011: /*@
2012: SNESSetInitialFunction - Set an already computed function evaluation at the initial guess to be reused by `SNESSolve()`.
2014: Logically Collective
2016: Input Parameters:
2017: + snes - the `SNES` context
2018: - f - vector to store function value
2020: Level: developer
2022: Notes:
2023: This should not be modified during the solution procedure.
2025: This is used extensively in the `SNESFAS` hierarchy and in nonlinear preconditioning.
2027: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetInitialFunctionNorm()`
2028: @*/
2029: PetscErrorCode SNESSetInitialFunction(SNES snes, Vec f)
2030: {
2031: Vec vec_func;
2033: PetscFunctionBegin;
2036: PetscCheckSameComm(snes, 1, f, 2);
2037: if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2038: snes->vec_func_init_set = PETSC_FALSE;
2039: PetscFunctionReturn(PETSC_SUCCESS);
2040: }
2041: PetscCall(SNESGetFunction(snes, &vec_func, NULL, NULL));
2042: PetscCall(VecCopy(f, vec_func));
2044: snes->vec_func_init_set = PETSC_TRUE;
2045: PetscFunctionReturn(PETSC_SUCCESS);
2046: }
2048: /*@
2049: SNESSetNormSchedule - Sets the `SNESNormSchedule` used in convergence and monitoring
2050: of the `SNES` method, when norms are computed in the solving process
2052: Logically Collective
2054: Input Parameters:
2055: + snes - the `SNES` context
2056: - normschedule - the frequency of norm computation
2058: Options Database Key:
2059: . -snes_norm_schedule (none|always|initialonly|finalonly|initialfinalonly) - set the schedule
2061: Level: advanced
2063: Notes:
2064: Only certain `SNES` methods support certain `SNESNormSchedules`. Most require evaluation
2065: of the nonlinear function and the taking of its norm at every iteration to
2066: even ensure convergence at all. However, methods such as custom Gauss-Seidel methods
2067: `SNESNGS` and the like do not require the norm of the function to be computed, and therefore
2068: may either be monitored for convergence or not. As these are often used as nonlinear
2069: preconditioners, monitoring the norm of their error is not a useful enterprise within
2070: their solution.
2072: .seealso: [](ch_snes), `SNESNormSchedule`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`
2073: @*/
2074: PetscErrorCode SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
2075: {
2076: PetscFunctionBegin;
2079: snes->normschedule = normschedule;
2080: PetscFunctionReturn(PETSC_SUCCESS);
2081: }
2083: /*@
2084: SNESGetNormSchedule - Gets the `SNESNormSchedule` used in convergence and monitoring
2085: of the `SNES` method.
2087: Logically Collective
2089: Input Parameters:
2090: + snes - the `SNES` context
2091: - normschedule - the type of the norm used
2093: Level: advanced
2095: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2096: @*/
2097: PetscErrorCode SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
2098: {
2099: PetscFunctionBegin;
2101: *normschedule = snes->normschedule;
2102: PetscFunctionReturn(PETSC_SUCCESS);
2103: }
2105: /*@
2106: SNESSetFunctionNorm - Sets the last computed residual norm.
2108: Logically Collective
2110: Input Parameters:
2111: + snes - the `SNES` context
2112: - norm - the value of the norm
2114: Level: developer
2116: .seealso: [](ch_snes), `SNES`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2117: @*/
2118: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
2119: {
2120: PetscFunctionBegin;
2122: snes->norm = norm;
2123: PetscFunctionReturn(PETSC_SUCCESS);
2124: }
2126: /*@
2127: SNESGetFunctionNorm - Gets the last computed norm of the residual
2129: Not Collective
2131: Input Parameter:
2132: . snes - the `SNES` context
2134: Output Parameter:
2135: . norm - the last computed residual norm
2137: Level: developer
2139: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2140: @*/
2141: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2142: {
2143: PetscFunctionBegin;
2145: PetscAssertPointer(norm, 2);
2146: *norm = snes->norm;
2147: PetscFunctionReturn(PETSC_SUCCESS);
2148: }
2150: /*@
2151: SNESGetUpdateNorm - Gets the last computed norm of the solution update
2153: Not Collective
2155: Input Parameter:
2156: . snes - the `SNES` context
2158: Output Parameter:
2159: . ynorm - the last computed update norm
2161: Level: developer
2163: Note:
2164: The new solution is the current solution plus the update, so this norm is an indication of the size of the update
2166: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`
2167: @*/
2168: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2169: {
2170: PetscFunctionBegin;
2172: PetscAssertPointer(ynorm, 2);
2173: *ynorm = snes->ynorm;
2174: PetscFunctionReturn(PETSC_SUCCESS);
2175: }
2177: /*@
2178: SNESGetSolutionNorm - Gets the last computed norm of the solution
2180: Not Collective
2182: Input Parameter:
2183: . snes - the `SNES` context
2185: Output Parameter:
2186: . xnorm - the last computed solution norm
2188: Level: developer
2190: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`, `SNESGetUpdateNorm()`
2191: @*/
2192: PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2193: {
2194: PetscFunctionBegin;
2196: PetscAssertPointer(xnorm, 2);
2197: *xnorm = snes->xnorm;
2198: PetscFunctionReturn(PETSC_SUCCESS);
2199: }
2201: /*@
2202: SNESSetFunctionType - Sets the `SNESFunctionType`
2203: of the `SNES` method.
2205: Logically Collective
2207: Input Parameters:
2208: + snes - the `SNES` context
2209: - type - the function type
2211: Level: developer
2213: Values of the function type\:
2214: + `SNES_FUNCTION_DEFAULT` - the default for the given `SNESType`
2215: . `SNES_FUNCTION_UNPRECONDITIONED` - an unpreconditioned function evaluation (this is the function provided with `SNESSetFunction()`
2216: - `SNES_FUNCTION_PRECONDITIONED` - a transformation of the function provided with `SNESSetFunction()`
2218: Note:
2219: Different `SNESType`s use this value in different ways
2221: .seealso: [](ch_snes), `SNES`, `SNESFunctionType`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2222: @*/
2223: PetscErrorCode SNESSetFunctionType(SNES snes, SNESFunctionType type)
2224: {
2225: PetscFunctionBegin;
2227: snes->functype = type;
2228: PetscFunctionReturn(PETSC_SUCCESS);
2229: }
2231: /*@
2232: SNESGetFunctionType - Gets the `SNESFunctionType` used in convergence and monitoring set with `SNESSetFunctionType()`
2233: of the SNES method.
2235: Logically Collective
2237: Input Parameters:
2238: + snes - the `SNES` context
2239: - type - the type of the function evaluation, see `SNESSetFunctionType()`
2241: Level: advanced
2243: .seealso: [](ch_snes), `SNESSetFunctionType()`, `SNESFunctionType`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2244: @*/
2245: PetscErrorCode SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2246: {
2247: PetscFunctionBegin;
2249: *type = snes->functype;
2250: PetscFunctionReturn(PETSC_SUCCESS);
2251: }
2253: /*@
2254: SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2255: use with composed nonlinear solvers.
2257: Input Parameters:
2258: + snes - the `SNES` context, usually of the `SNESType` `SNESNGS`
2259: . f - function evaluation routine to apply Gauss-Seidel, see `SNESNGSFn` for calling sequence
2260: - ctx - [optional] user-defined context for private data for the smoother evaluation routine (may be `NULL`)
2262: Level: intermediate
2264: Note:
2265: The `SNESNGS` routines are used by the composed nonlinear solver to generate
2266: a problem appropriate update to the solution, particularly `SNESFAS`.
2268: .seealso: [](ch_snes), `SNESNGS`, `SNESGetNGS()`, `SNESNCG`, `SNESGetFunction()`, `SNESComputeNGS()`, `SNESNGSFn`
2269: @*/
2270: PetscErrorCode SNESSetNGS(SNES snes, SNESNGSFn *f, PetscCtx ctx)
2271: {
2272: DM dm;
2274: PetscFunctionBegin;
2276: PetscCall(SNESGetDM(snes, &dm));
2277: PetscCall(DMSNESSetNGS(dm, f, ctx));
2278: PetscFunctionReturn(PETSC_SUCCESS);
2279: }
2281: /*@
2282: SNESPicardComputeMFFunction - Matrix-free residual $A(x) x - b(x)$ used by `SNESSetPicard()` when the operator is applied through `-snes_mf_operator`
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: Note:
2297: Uses a duplicate of `snes->jacobian_pre` because `snes->jacobian_pre` cannot be changed during the `KSPSolve()`.
2299: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeFunction()`, `SNESPicardComputeJacobian()`
2300: @*/
2301: PetscErrorCode SNESPicardComputeMFFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2302: {
2303: DM dm;
2304: DMSNES sdm;
2306: PetscFunctionBegin;
2307: PetscCall(SNESGetDM(snes, &dm));
2308: PetscCall(DMGetDMSNES(dm, &sdm));
2309: /* A(x)*x - b(x) */
2310: if (sdm->ops->computepfunction) {
2311: PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2312: PetscCall(VecScale(f, -1.0));
2313: /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2314: if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre, MAT_DO_NOT_COPY_VALUES, &snes->picard));
2315: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2316: PetscCall(MatMultAdd(snes->picard, x, f, f));
2317: } else {
2318: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2319: PetscCall(MatMult(snes->picard, x, f));
2320: }
2321: PetscFunctionReturn(PETSC_SUCCESS);
2322: }
2324: /*@
2325: SNESPicardComputeFunction - Compute the residual $A(x) x - b(x)$ using the callbacks registered by `SNESSetPicard()`
2327: Collective
2329: Input Parameters:
2330: + snes - the `SNES` context
2331: . x - the current iterate
2332: - ctx - unused application context; the Picard callbacks are retrieved from the attached `DMSNES`
2334: Output Parameter:
2335: . f - the residual vector
2337: Level: developer
2339: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeMFFunction()`, `SNESPicardComputeJacobian()`
2340: @*/
2341: PetscErrorCode SNESPicardComputeFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2342: {
2343: DM dm;
2344: DMSNES sdm;
2346: PetscFunctionBegin;
2347: PetscCall(SNESGetDM(snes, &dm));
2348: PetscCall(DMGetDMSNES(dm, &sdm));
2349: /* A(x)*x - b(x) */
2350: if (sdm->ops->computepfunction) {
2351: PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2352: PetscCall(VecScale(f, -1.0));
2353: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2354: PetscCall(MatMultAdd(snes->jacobian_pre, x, f, f));
2355: } else {
2356: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2357: PetscCall(MatMult(snes->jacobian_pre, x, f));
2358: }
2359: PetscFunctionReturn(PETSC_SUCCESS);
2360: }
2362: /*@
2363: SNESPicardComputeJacobian - Trivial Jacobian assembly callback used by `SNESSetPicard()`; the Picard operator is filled in by `SNESPicardComputeFunction()`
2365: Collective
2367: Input Parameters:
2368: + snes - the `SNES` context
2369: . x1 - the current iterate (unused)
2370: . J - the Jacobian matrix to assemble
2371: . B - the preconditioning matrix (unused)
2372: - ctx - unused application context
2374: Level: developer
2376: Note:
2377: Only calls `MatAssemblyBegin()`/`MatAssemblyEnd()` on `J`, because the Picard iteration reuses the operator already assembled by `SNESPicardComputeFunction()`.
2379: .seealso: [](ch_snes), `SNES`, `SNESSetPicard()`, `SNESPicardComputeFunction()`, `SNESPicardComputeMFFunction()`
2380: @*/
2381: PetscErrorCode SNESPicardComputeJacobian(SNES snes, Vec x1, Mat J, Mat B, PetscCtx ctx)
2382: {
2383: PetscFunctionBegin;
2384: /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2385: /* must assembly if matrix-free to get the last SNES solution */
2386: PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
2387: PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
2388: PetscFunctionReturn(PETSC_SUCCESS);
2389: }
2391: /*@
2392: SNESSetPicard - Use `SNES` to solve the system $A(x) x = bp(x) + b $ via a Picard type iteration (Picard linearization)
2394: Logically Collective
2396: Input Parameters:
2397: + snes - the `SNES` context
2398: . r - vector to store function values, may be `NULL`
2399: . bp - function evaluation routine, may be `NULL`, for the calling sequence see `SNESFunctionFn`
2400: . Amat - matrix with which $A(x) x - bp(x) - b$ is to be computed
2401: . Pmat - matrix from which preconditioner is computed (usually the same as `Amat`)
2402: . J - function to compute matrix values, for the calling sequence see `SNESJacobianFn`
2403: - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
2405: Level: intermediate
2407: Notes:
2408: It is often better to provide the nonlinear function $F()$ and some approximation to its Jacobian directly and use
2409: 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.
2411: One can call `SNESSetPicard()` or `SNESSetFunction()` (and possibly `SNESSetJacobian()`) but cannot call both
2413: 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}$.
2414: When an exact solver is used this corresponds to the "classic" Picard $A(x^{n}) x^{n+1} = bp(x^{n}) + b$ iteration.
2416: Run with `-snes_mf_operator` to solve the system with Newton's method using $A(x^{n})$ to construct the preconditioner.
2418: We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
2419: the direct Picard iteration $A(x^n) x^{n+1} = bp(x^n) + b$
2421: 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
2422: 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
2423: different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument \:-).
2425: 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
2426: $A(x^{n})$ is used to build the preconditioner
2428: When used with `-snes_fd` this will compute the true Jacobian (very slowly one column at a time) and thus represent Newton's method.
2430: 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
2431: 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
2432: 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`.
2433: See the comment in src/snes/tutorials/ex15.c.
2435: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`,
2436: `SNESFunctionFn`, `SNESJacobianFn`
2437: @*/
2438: PetscErrorCode SNESSetPicard(SNES snes, Vec r, SNESFunctionFn *bp, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
2439: {
2440: DM dm;
2442: PetscFunctionBegin;
2444: PetscCall(SNESGetDM(snes, &dm));
2445: PetscCall(DMSNESSetPicard(dm, bp, J, ctx));
2446: PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
2447: PetscCall(SNESSetFunction(snes, r, SNESPicardComputeFunction, ctx));
2448: PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESPicardComputeJacobian, ctx));
2449: PetscFunctionReturn(PETSC_SUCCESS);
2450: }
2452: /*@
2453: SNESGetPicard - Returns the context for the Picard iteration
2455: Not Collective, but `Vec` is parallel if `SNES` is parallel. Collective if `Vec` is requested, but has not been created yet.
2457: Input Parameter:
2458: . snes - the `SNES` context
2460: Output Parameters:
2461: + r - the function (or `NULL`)
2462: . f - the function (or `NULL`); for calling sequence see `SNESFunctionFn`
2463: . Amat - the matrix used to defined the operation A(x) x - b(x) (or `NULL`)
2464: . Pmat - the matrix from which the preconditioner will be constructed (or `NULL`)
2465: . J - the function for matrix evaluation (or `NULL`); for calling sequence see `SNESJacobianFn`
2466: - ctx - the function context (or `NULL`)
2468: Level: advanced
2470: .seealso: [](ch_snes), `SNESSetFunction()`, `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunctionFn`, `SNESJacobianFn`
2471: @*/
2472: PetscErrorCode SNESGetPicard(SNES snes, Vec *r, SNESFunctionFn **f, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
2473: {
2474: DM dm;
2476: PetscFunctionBegin;
2478: PetscCall(SNESGetFunction(snes, r, NULL, NULL));
2479: PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
2480: PetscCall(SNESGetDM(snes, &dm));
2481: PetscCall(DMSNESGetPicard(dm, f, J, ctx));
2482: PetscFunctionReturn(PETSC_SUCCESS);
2483: }
2485: /*@
2486: SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the nonlinear problem
2488: Logically Collective
2490: Input Parameters:
2491: + snes - the `SNES` context
2492: . func - function evaluation routine, see `SNESInitialGuessFn` for the calling sequence
2493: - ctx - [optional] user-defined context for private data for the
2494: function evaluation routine (may be `NULL`)
2496: Level: intermediate
2498: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESInitialGuessFn`
2499: @*/
2500: PetscErrorCode SNESSetComputeInitialGuess(SNES snes, SNESInitialGuessFn *func, PetscCtx ctx)
2501: {
2502: PetscFunctionBegin;
2504: if (func) snes->ops->computeinitialguess = func;
2505: if (ctx) snes->initialguessP = ctx;
2506: PetscFunctionReturn(PETSC_SUCCESS);
2507: }
2509: /*@
2510: SNESGetRhs - Gets the vector for solving F(x) = `rhs`. If `rhs` is not set
2511: it assumes a zero right-hand side.
2513: Logically Collective
2515: Input Parameter:
2516: . snes - the `SNES` context
2518: Output Parameter:
2519: . rhs - the right-hand side vector or `NULL` if there is no right-hand side vector
2521: Level: intermediate
2523: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()`
2524: @*/
2525: PetscErrorCode SNESGetRhs(SNES snes, Vec *rhs)
2526: {
2527: PetscFunctionBegin;
2529: PetscAssertPointer(rhs, 2);
2530: *rhs = snes->vec_rhs;
2531: PetscFunctionReturn(PETSC_SUCCESS);
2532: }
2534: /*@
2535: SNESComputeFunction - Calls the function that has been set with `SNESSetFunction()`.
2537: Collective
2539: Input Parameters:
2540: + snes - the `SNES` context
2541: - x - input vector
2543: Output Parameter:
2544: . f - function vector, as set by `SNESSetFunction()`
2546: Level: developer
2548: Notes:
2549: `SNESComputeFunction()` is typically used within nonlinear solvers
2550: implementations, so users would not generally call this routine themselves.
2552: When solving for $F(x) = b$, this routine computes $f = F(x) - b$.
2554: This function usually appears in the pattern.
2555: .vb
2556: SNESComputeFunction(snes, x, f);
2557: VecNorm(f, &fnorm);
2558: SNESCheckFunctionDomainError(snes, fnorm); or SNESLineSearchCheckFunctionDomainError(ls, fnorm);
2559: .ve
2560: to collectively handle the use of `SNESSetFunctionDomainError()` in the provided callback function.
2562: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()`, `SNESSetFunctionDomainError()`
2563: @*/
2564: PetscErrorCode SNESComputeFunction(SNES snes, Vec x, Vec f)
2565: {
2566: DM dm;
2567: DMSNES sdm;
2569: PetscFunctionBegin;
2573: PetscCheckSameComm(snes, 1, x, 2);
2574: PetscCheckSameComm(snes, 1, f, 3);
2575: PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2577: PetscCall(SNESGetDM(snes, &dm));
2578: PetscCall(DMGetDMSNES(dm, &sdm));
2579: 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().");
2580: if (sdm->ops->computefunction) {
2581: if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, f, 0));
2582: PetscCall(VecLockReadPush(x));
2583: /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2584: snes->functiondomainerror = PETSC_FALSE;
2585: {
2586: void *ctx;
2587: SNESFunctionFn *computefunction;
2588: PetscCall(DMSNESGetFunction(dm, &computefunction, &ctx));
2589: PetscCallBack("SNES callback function", (*computefunction)(snes, x, f, ctx));
2590: }
2591: PetscCall(VecLockReadPop(x));
2592: if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, f, 0));
2593: } else /* if (snes->vec_rhs) */ {
2594: PetscCall(MatMult(snes->jacobian, x, f));
2595: }
2596: if (snes->vec_rhs) PetscCall(VecAXPY(f, -1.0, snes->vec_rhs));
2597: snes->nfuncs++;
2598: /*
2599: domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2600: propagate the value to all processes
2601: */
2602: PetscCall(VecFlag(f, snes->functiondomainerror));
2603: PetscFunctionReturn(PETSC_SUCCESS);
2604: }
2606: /*@
2607: SNESComputeMFFunction - Calls the function that has been set with `DMSNESSetMFFunction()`.
2609: Collective
2611: Input Parameters:
2612: + snes - the `SNES` context
2613: - x - input vector
2615: Output Parameter:
2616: . y - output vector
2618: Level: developer
2620: Notes:
2621: `SNESComputeMFFunction()` is used within the matrix-vector products called by the matrix created with `MatCreateSNESMF()`
2622: so users would not generally call this routine themselves.
2624: Since this function is intended for use with finite differencing it does not subtract the right-hand side vector provided with `SNESSolve()`
2625: while `SNESComputeFunction()` does. As such, this routine cannot be used with `MatMFFDSetBase()` with a provided F function value even if it applies the
2626: 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.
2628: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF()`, `DMSNESSetMFFunction()`
2629: @*/
2630: PetscErrorCode SNESComputeMFFunction(SNES snes, Vec x, Vec y)
2631: {
2632: DM dm;
2633: DMSNES sdm;
2635: PetscFunctionBegin;
2639: PetscCheckSameComm(snes, 1, x, 2);
2640: PetscCheckSameComm(snes, 1, y, 3);
2641: PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2643: PetscCall(SNESGetDM(snes, &dm));
2644: PetscCall(DMGetDMSNES(dm, &sdm));
2645: PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, y, 0));
2646: PetscCall(VecLockReadPush(x));
2647: /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2648: snes->functiondomainerror = PETSC_FALSE;
2649: PetscCallBack("SNES callback function", (*sdm->ops->computemffunction)(snes, x, y, sdm->mffunctionctx));
2650: PetscCall(VecLockReadPop(x));
2651: PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, y, 0));
2652: snes->nfuncs++;
2653: /*
2654: domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2655: propagate the value to all processes
2656: */
2657: PetscCall(VecFlag(y, snes->functiondomainerror));
2658: PetscFunctionReturn(PETSC_SUCCESS);
2659: }
2661: /*@
2662: SNESComputeNGS - Calls the Gauss-Seidel function that has been set with `SNESSetNGS()`.
2664: Collective
2666: Input Parameters:
2667: + snes - the `SNES` context
2668: . x - input vector
2669: - b - rhs vector
2671: Output Parameter:
2672: . x - new solution vector
2674: Level: developer
2676: Note:
2677: `SNESComputeNGS()` is typically used within composed nonlinear solver
2678: implementations, so most users would not generally call this routine
2679: themselves.
2681: .seealso: [](ch_snes), `SNESNGSFn`, `SNESSetNGS()`, `SNESComputeFunction()`, `SNESNGS`
2682: @*/
2683: PetscErrorCode SNESComputeNGS(SNES snes, Vec b, Vec x)
2684: {
2685: DM dm;
2686: DMSNES sdm;
2688: PetscFunctionBegin;
2692: PetscCheckSameComm(snes, 1, x, 3);
2693: if (b) PetscCheckSameComm(snes, 1, b, 2);
2694: if (b) PetscCall(VecValidValues_Internal(b, 2, PETSC_TRUE));
2695: PetscCall(PetscLogEventBegin(SNES_NGSEval, snes, x, b, 0));
2696: PetscCall(SNESGetDM(snes, &dm));
2697: PetscCall(DMGetDMSNES(dm, &sdm));
2698: PetscCheck(sdm->ops->computegs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2699: if (b) PetscCall(VecLockReadPush(b));
2700: PetscCallBack("SNES callback NGS", (*sdm->ops->computegs)(snes, x, b, sdm->gsctx));
2701: if (b) PetscCall(VecLockReadPop(b));
2702: PetscCall(PetscLogEventEnd(SNES_NGSEval, snes, x, b, 0));
2703: PetscFunctionReturn(PETSC_SUCCESS);
2704: }
2706: static PetscErrorCode SNESComputeFunction_FD(SNES snes, Vec Xin, Vec G)
2707: {
2708: Vec X;
2709: PetscScalar *g;
2710: PetscReal f, f2;
2711: PetscInt low, high, N, i;
2712: PetscBool flg;
2713: PetscReal h = .5 * PETSC_SQRT_MACHINE_EPSILON;
2715: PetscFunctionBegin;
2716: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_fd_delta", &h, &flg));
2717: PetscCall(VecDuplicate(Xin, &X));
2718: PetscCall(VecCopy(Xin, X));
2719: PetscCall(VecGetSize(X, &N));
2720: PetscCall(VecGetOwnershipRange(X, &low, &high));
2721: PetscCall(VecSetOption(X, VEC_IGNORE_OFF_PROC_ENTRIES, PETSC_TRUE));
2722: PetscCall(VecGetArray(G, &g));
2723: for (i = 0; i < N; i++) {
2724: PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2725: PetscCall(VecAssemblyBegin(X));
2726: PetscCall(VecAssemblyEnd(X));
2727: PetscCall(SNESComputeObjective(snes, X, &f));
2728: PetscCall(VecSetValue(X, i, 2.0 * h, ADD_VALUES));
2729: PetscCall(VecAssemblyBegin(X));
2730: PetscCall(VecAssemblyEnd(X));
2731: PetscCall(SNESComputeObjective(snes, X, &f2));
2732: PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2733: PetscCall(VecAssemblyBegin(X));
2734: PetscCall(VecAssemblyEnd(X));
2735: if (i >= low && i < high) g[i - low] = (f2 - f) / (2.0 * h);
2736: }
2737: PetscCall(VecRestoreArray(G, &g));
2738: PetscCall(VecDestroy(&X));
2739: PetscFunctionReturn(PETSC_SUCCESS);
2740: }
2742: /*@
2743: SNESTestFunction - Computes the difference between the computed and finite-difference functions
2745: Collective
2747: Input Parameter:
2748: . snes - the `SNES` context
2750: Options Database Keys:
2751: + -snes_test_function - compare the user provided function with one compute via finite differences to check for errors.
2752: - -snes_test_function_view - display the user provided function, the finite difference function and the difference
2754: Level: developer
2756: .seealso: [](ch_snes), `SNESTestJacobian()`, `SNESSetFunction()`, `SNESComputeFunction()`
2757: @*/
2758: PetscErrorCode SNESTestFunction(SNES snes)
2759: {
2760: Vec x, g1, g2, g3;
2761: PetscBool complete_print = PETSC_FALSE;
2762: PetscReal hcnorm, fdnorm, hcmax, fdmax, diffmax, diffnorm;
2763: PetscScalar dot;
2764: MPI_Comm comm;
2765: PetscViewer viewer, mviewer;
2766: PetscViewerFormat format;
2767: PetscInt tabs;
2768: static PetscBool directionsprinted = PETSC_FALSE;
2769: SNESObjectiveFn *objective;
2771: PetscFunctionBegin;
2772: PetscCall(SNESGetObjective(snes, &objective, NULL));
2773: if (!objective) PetscFunctionReturn(PETSC_SUCCESS);
2775: PetscObjectOptionsBegin((PetscObject)snes);
2776: PetscCall(PetscOptionsViewer("-snes_test_function_view", "View difference between hand-coded and finite difference function element entries", "None", &mviewer, &format, &complete_print));
2777: PetscOptionsEnd();
2779: PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2780: PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2781: PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2782: PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2783: PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Function -------------\n"));
2784: if (!complete_print && !directionsprinted) {
2785: PetscCall(PetscViewerASCIIPrintf(viewer, " Run with -snes_test_function_view and optionally -snes_test_function <threshold> to show difference\n"));
2786: PetscCall(PetscViewerASCIIPrintf(viewer, " of hand-coded and finite difference function entries greater than <threshold>.\n"));
2787: }
2788: if (!directionsprinted) {
2789: PetscCall(PetscViewerASCIIPrintf(viewer, " Testing hand-coded Function, if (for double precision runs) ||F - Ffd||/||F|| is\n"));
2790: PetscCall(PetscViewerASCIIPrintf(viewer, " O(1.e-8), the hand-coded Function is probably correct.\n"));
2791: directionsprinted = PETSC_TRUE;
2792: }
2793: if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));
2795: PetscCall(SNESGetSolution(snes, &x));
2796: PetscCall(VecDuplicate(x, &g1));
2797: PetscCall(VecDuplicate(x, &g2));
2798: PetscCall(VecDuplicate(x, &g3));
2799: PetscCall(SNESComputeFunction(snes, x, g1)); /* does not handle use of SNESSetFunctionDomainError() correctly */
2800: PetscCall(SNESComputeFunction_FD(snes, x, g2));
2802: PetscCall(VecNorm(g2, NORM_2, &fdnorm));
2803: PetscCall(VecNorm(g1, NORM_2, &hcnorm));
2804: PetscCall(VecNorm(g2, NORM_INFINITY, &fdmax));
2805: PetscCall(VecNorm(g1, NORM_INFINITY, &hcmax));
2806: PetscCall(VecDot(g1, g2, &dot));
2807: PetscCall(VecCopy(g1, g3));
2808: PetscCall(VecAXPY(g3, -1.0, g2));
2809: PetscCall(VecNorm(g3, NORM_2, &diffnorm));
2810: PetscCall(VecNorm(g3, NORM_INFINITY, &diffmax));
2811: PetscCall(PetscViewerASCIIPrintf(viewer, " ||Ffd|| %g, ||F|| = %g, angle cosine = (Ffd'F)/||Ffd||||F|| = %g\n", (double)fdnorm, (double)hcnorm, (double)(PetscRealPart(dot) / (fdnorm * hcnorm))));
2812: PetscCall(PetscViewerASCIIPrintf(viewer, " 2-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffnorm / PetscMax(hcnorm, fdnorm)), (double)diffnorm));
2813: PetscCall(PetscViewerASCIIPrintf(viewer, " max-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffmax / PetscMax(hcmax, fdmax)), (double)diffmax));
2815: if (complete_print) {
2816: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded function ----------\n"));
2817: PetscCall(VecView(g1, mviewer));
2818: PetscCall(PetscViewerASCIIPrintf(viewer, " Finite difference function ----------\n"));
2819: PetscCall(VecView(g2, mviewer));
2820: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded minus finite-difference function ----------\n"));
2821: PetscCall(VecView(g3, mviewer));
2822: }
2823: PetscCall(VecDestroy(&g1));
2824: PetscCall(VecDestroy(&g2));
2825: PetscCall(VecDestroy(&g3));
2827: if (complete_print) {
2828: PetscCall(PetscViewerPopFormat(mviewer));
2829: PetscCall(PetscViewerDestroy(&mviewer));
2830: }
2831: PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2832: PetscFunctionReturn(PETSC_SUCCESS);
2833: }
2835: /*@
2836: SNESTestJacobian - Computes the difference between the computed and finite-difference Jacobians
2838: Collective
2840: Input Parameter:
2841: . snes - the `SNES` context
2843: Output Parameters:
2844: + Jnorm - the Frobenius norm of the computed Jacobian, or `NULL`
2845: - diffNorm - the Frobenius norm of the difference of the computed and finite-difference Jacobians, or `NULL`
2847: Options Database Keys:
2848: + -snes_test_jacobian [threshold] - compare the user provided Jacobian with one compute via finite differences to check for errors.
2849: If a threshold is given, display only those entries whose difference is greater than the threshold.
2850: - -snes_test_jacobian_view viewer_specification - display the user provided Jacobian, the finite difference Jacobian and the difference, see `PetscOptionsCreateViewer()` for the
2851: format of `viewer_specification`
2853: Level: developer
2855: Note:
2856: Directions and norms are printed to stdout if `diffNorm` is `NULL`.
2858: .seealso: [](ch_snes), `SNESTestFunction()`, `SNESSetJacobian()`, `SNESComputeJacobian()`
2859: @*/
2860: PetscErrorCode SNESTestJacobian(SNES snes, PetscReal *Jnorm, PetscReal *diffNorm)
2861: {
2862: Mat A, B, C, D, jacobian;
2863: Vec x = snes->vec_sol, f;
2864: PetscReal nrm, gnorm;
2865: PetscReal threshold = 1.e-5;
2866: void *functx;
2867: PetscBool complete_print = PETSC_FALSE, threshold_print = PETSC_FALSE, flg, istranspose;
2868: PetscBool silent = diffNorm != PETSC_NULLPTR ? PETSC_TRUE : PETSC_FALSE;
2869: PetscViewer viewer, mviewer;
2870: MPI_Comm comm;
2871: PetscInt tabs;
2872: static PetscBool directionsprinted = PETSC_FALSE;
2873: PetscViewerFormat format;
2875: PetscFunctionBegin;
2876: PetscObjectOptionsBegin((PetscObject)snes);
2877: PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold, NULL));
2878: PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display", "-snes_test_jacobian_view", "3.13", NULL));
2879: PetscCall(PetscOptionsViewer("-snes_test_jacobian_view", "View difference between hand-coded and finite difference Jacobians element entries", "None", &mviewer, &format, &complete_print));
2880: PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold", "-snes_test_jacobian", "3.13", "-snes_test_jacobian accepts an optional threshold (since v3.10)"));
2881: 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));
2882: PetscOptionsEnd();
2884: PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2885: PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2886: PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2887: PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2888: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Jacobian -------------\n"));
2889: if (!complete_print && !silent && !directionsprinted) {
2890: PetscCall(PetscViewerASCIIPrintf(viewer, " Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
2891: PetscCall(PetscViewerASCIIPrintf(viewer, " of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
2892: }
2893: if (!directionsprinted && !silent) {
2894: PetscCall(PetscViewerASCIIPrintf(viewer, " Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
2895: PetscCall(PetscViewerASCIIPrintf(viewer, " O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
2896: directionsprinted = PETSC_TRUE;
2897: }
2898: if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));
2900: PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian, MATMFFD, &flg));
2901: if (!flg) jacobian = snes->jacobian;
2902: else jacobian = snes->jacobian_pre;
2904: if (!x) PetscCall(MatCreateVecs(jacobian, &x, NULL));
2905: else PetscCall(PetscObjectReference((PetscObject)x));
2906: PetscCall(VecDuplicate(x, &f));
2908: /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2909: PetscCall(SNESComputeFunction(snes, x, f));
2910: PetscCall(VecDestroy(&f));
2911: PetscCall(PetscObjectTypeCompare((PetscObject)snes, SNESKSPTRANSPOSEONLY, &istranspose));
2912: while (jacobian) {
2913: Mat JT = NULL, Jsave = NULL;
2915: if (istranspose) {
2916: PetscCall(MatCreateTranspose(jacobian, &JT));
2917: Jsave = jacobian;
2918: jacobian = JT;
2919: }
2920: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
2921: if (flg) {
2922: A = jacobian;
2923: PetscCall(PetscObjectReference((PetscObject)A));
2924: } else {
2925: PetscCall(MatComputeOperator(jacobian, MATAIJ, &A));
2926: }
2928: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
2929: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
2931: PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
2932: PetscCall(SNESComputeJacobianDefault(snes, x, B, B, functx));
2934: PetscCall(MatDuplicate(B, MAT_COPY_VALUES, &D));
2935: PetscCall(MatAYPX(D, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2936: PetscCall(MatNorm(D, NORM_FROBENIUS, &nrm));
2937: PetscCall(MatNorm(A, NORM_FROBENIUS, &gnorm));
2938: PetscCall(MatDestroy(&D));
2939: if (!gnorm) gnorm = 1; /* just in case */
2940: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n", (double)(nrm / gnorm), (double)nrm));
2941: if (complete_print) {
2942: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded Jacobian ----------\n"));
2943: PetscCall(MatView(A, mviewer));
2944: PetscCall(PetscViewerASCIIPrintf(viewer, " Finite difference Jacobian ----------\n"));
2945: PetscCall(MatView(B, mviewer));
2946: }
2948: if (threshold_print || complete_print) {
2949: PetscInt Istart, Iend, *ccols, bncols, cncols, j, row;
2950: PetscScalar *cvals;
2951: const PetscInt *bcols;
2952: const PetscScalar *bvals;
2954: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &C));
2955: PetscCall(MatSetOption(C, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
2957: PetscCall(MatAYPX(B, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2958: PetscCall(MatGetOwnershipRange(B, &Istart, &Iend));
2960: for (row = Istart; row < Iend; row++) {
2961: PetscCall(MatGetRow(B, row, &bncols, &bcols, &bvals));
2962: PetscCall(PetscMalloc2(bncols, &ccols, bncols, &cvals));
2963: for (j = 0, cncols = 0; j < bncols; j++) {
2964: if (PetscAbsScalar(bvals[j]) > threshold) {
2965: ccols[cncols] = bcols[j];
2966: cvals[cncols] = bvals[j];
2967: cncols += 1;
2968: }
2969: }
2970: if (cncols) PetscCall(MatSetValues(C, 1, &row, cncols, ccols, cvals, INSERT_VALUES));
2971: PetscCall(MatRestoreRow(B, row, &bncols, &bcols, &bvals));
2972: PetscCall(PetscFree2(ccols, cvals));
2973: }
2974: PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2975: PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2976: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n", (double)threshold));
2977: PetscCall(MatView(C, complete_print ? mviewer : viewer));
2978: PetscCall(MatDestroy(&C));
2979: }
2980: PetscCall(MatDestroy(&A));
2981: PetscCall(MatDestroy(&B));
2982: PetscCall(MatDestroy(&JT));
2983: if (Jsave) jacobian = Jsave;
2984: if (jacobian != snes->jacobian_pre) {
2985: jacobian = snes->jacobian_pre;
2986: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Jacobian for preconditioner -------------\n"));
2987: } else jacobian = NULL;
2988: }
2989: PetscCall(VecDestroy(&x));
2990: if (complete_print) PetscCall(PetscViewerPopFormat(mviewer));
2991: PetscCall(PetscViewerDestroy(&mviewer));
2992: PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2994: if (Jnorm) *Jnorm = gnorm;
2995: if (diffNorm) *diffNorm = nrm;
2996: PetscFunctionReturn(PETSC_SUCCESS);
2997: }
2999: /*@
3000: SNESComputeJacobian - Computes the Jacobian matrix that has been set with `SNESSetJacobian()`.
3002: Collective
3004: Input Parameters:
3005: + snes - the `SNES` context
3006: - X - input vector
3008: Output Parameters:
3009: + A - Jacobian matrix
3010: - B - optional matrix for building the preconditioner, usually the same as `A`
3012: Options Database Keys:
3013: + -snes_lag_preconditioner lag - how often to rebuild preconditioner
3014: . -snes_lag_jacobian lag - how often to rebuild Jacobian
3015: . -snes_test_jacobian [threshold] - compare the user provided Jacobian with one compute via finite differences to check for errors.
3016: If a threshold is given, display only those entries whose difference is greater than the threshold.
3017: . -snes_test_jacobian_view viewer_specification - 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.
3018: See `PetscOptionsCreateViewer()` for the format of `viewer_specification`
3019: . -snes_compare_explicit - compare the computed Jacobian to the finite difference Jacobian and output the differences
3020: . -snes_compare_explicit_draw - compare the computed Jacobian to the finite difference Jacobian and draw the result
3021: . -snes_compare_explicit_draw_contour - compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
3022: . -snes_compare_operator - make the comparison options above use the operator instead of the matrix used to construct the preconditioner
3023: . -snes_compare_coloring - compute the finite difference Jacobian using coloring and display norms of difference
3024: . -snes_compare_coloring_display - compute the finite difference Jacobian using coloring and display verbose differences
3025: . -snes_compare_coloring_threshold - display only those matrix entries that differ by more than a given threshold
3026: . -snes_compare_coloring_threshold_atol - absolute tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
3027: . -snes_compare_coloring_threshold_rtol - relative tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
3028: . -snes_compare_coloring_draw - compute the finite difference Jacobian using coloring and draw differences
3029: - -snes_compare_coloring_draw_contour - compute the finite difference Jacobian using coloring and show contours of matrices and differences
3031: Level: developer
3033: Note:
3034: Most users should not need to explicitly call this routine, as it
3035: is used internally within the nonlinear solvers.
3037: Developer Note:
3038: This has duplicative ways of checking the accuracy of the user provided Jacobian (see the options above). This is for historical reasons.
3040: .seealso: [](ch_snes), `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
3041: `SNESSetJacobianDomainError()`, `SNESCheckJacobianDomainError()`, `SNESSetCheckJacobianDomainError()`
3042: @*/
3043: PetscErrorCode SNESComputeJacobian(SNES snes, Vec X, Mat A, Mat B)
3044: {
3045: PetscBool flag;
3046: DM dm;
3047: DMSNES sdm;
3048: KSP ksp;
3050: PetscFunctionBegin;
3053: PetscCheckSameComm(snes, 1, X, 2);
3054: PetscCall(VecValidValues_Internal(X, 2, PETSC_TRUE));
3055: PetscCall(SNESGetDM(snes, &dm));
3056: PetscCall(DMGetDMSNES(dm, &sdm));
3058: /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix-free */
3059: if (snes->lagjacobian == -2) {
3060: snes->lagjacobian = -1;
3062: PetscCall(PetscInfo(snes, "Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n"));
3063: } else if (snes->lagjacobian == -1) {
3064: PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is -1\n"));
3065: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
3066: if (flag) {
3067: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3068: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3069: }
3070: PetscFunctionReturn(PETSC_SUCCESS);
3071: } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
3072: PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagjacobian, snes->iter));
3073: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
3074: if (flag) {
3075: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3076: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3077: }
3078: PetscFunctionReturn(PETSC_SUCCESS);
3079: }
3080: if (snes->npc && snes->npcside == PC_LEFT) {
3081: /* SNESASPIN uses SNESNASM as the nonlinear preconditioner. When SNESNASM
3082: is done solving the sub-systems it calls the user-provided Jacobian function
3083: (corresponding to the unpreconditioned residual) retrieved through the DM.
3084: Consequently it would be redundant to call the Jacobian function here. In
3085: the future we may move the outer Jacobian function call out of SNESNASM
3086: in which case no special casing will be required here. */
3087: PetscCall(PetscObjectTypeCompare((PetscObject)snes, SNESASPIN, &flag));
3088: if (flag) {
3089: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
3090: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
3091: PetscFunctionReturn(PETSC_SUCCESS);
3092: }
3093: }
3095: PetscCall(PetscLogEventBegin(SNES_JacobianEval, snes, X, A, B));
3096: PetscCall(VecLockReadPush(X));
3097: {
3098: void *ctx;
3099: SNESJacobianFn *J;
3100: PetscCall(DMSNESGetJacobian(dm, &J, &ctx));
3101: PetscCallBack("SNES callback Jacobian", (*J)(snes, X, A, B, ctx));
3102: }
3103: PetscCall(VecLockReadPop(X));
3104: PetscCall(PetscLogEventEnd(SNES_JacobianEval, snes, X, A, B));
3106: /* attach latest linearization point to the matrix used to construct the preconditioner */
3107: PetscCall(PetscObjectCompose((PetscObject)B, "__SNES_latest_X", (PetscObject)X));
3109: /* the next line ensures that snes->ksp exists */
3110: PetscCall(SNESGetKSP(snes, &ksp));
3111: if (snes->lagpreconditioner == -2) {
3112: PetscCall(PetscInfo(snes, "Rebuilding preconditioner exactly once since lag is -2\n"));
3113: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3114: snes->lagpreconditioner = -1;
3115: } else if (snes->lagpreconditioner == -1) {
3116: PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is -1\n"));
3117: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3118: } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
3119: PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagpreconditioner, snes->iter));
3120: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3121: } else {
3122: PetscCall(PetscInfo(snes, "Rebuilding preconditioner\n"));
3123: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3124: }
3126: /* monkey business to allow testing Jacobians in multilevel solvers.
3127: This is needed because the SNESTestXXX interface does not accept vectors and matrices */
3128: {
3129: Vec xsave = snes->vec_sol;
3130: Mat jacobiansave = snes->jacobian;
3131: Mat jacobian_presave = snes->jacobian_pre;
3133: snes->vec_sol = X;
3134: snes->jacobian = A;
3135: snes->jacobian_pre = B;
3136: if (snes->testFunc) PetscCall(SNESTestFunction(snes));
3137: if (snes->testJac) PetscCall(SNESTestJacobian(snes, NULL, NULL));
3139: snes->vec_sol = xsave;
3140: snes->jacobian = jacobiansave;
3141: snes->jacobian_pre = jacobian_presave;
3142: }
3144: {
3145: PetscBool flag = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_operator = PETSC_FALSE;
3146: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit", NULL, NULL, &flag));
3147: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw", NULL, NULL, &flag_draw));
3148: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw_contour", NULL, NULL, &flag_contour));
3149: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_operator", NULL, NULL, &flag_operator));
3150: if (flag || flag_draw || flag_contour) {
3151: Mat Bexp_mine = NULL, Bexp, FDexp;
3152: PetscViewer vdraw, vstdout;
3153: PetscBool flg;
3154: if (flag_operator) {
3155: PetscCall(MatComputeOperator(A, MATAIJ, &Bexp_mine));
3156: Bexp = Bexp_mine;
3157: } else {
3158: /* See if the matrix used to construct the preconditioner can be viewed and added directly */
3159: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
3160: if (flg) Bexp = B;
3161: else {
3162: /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
3163: PetscCall(MatComputeOperator(B, MATAIJ, &Bexp_mine));
3164: Bexp = Bexp_mine;
3165: }
3166: }
3167: PetscCall(MatConvert(Bexp, MATSAME, MAT_INITIAL_MATRIX, &FDexp));
3168: PetscCall(SNESComputeJacobianDefault(snes, X, FDexp, FDexp, NULL));
3169: PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3170: if (flag_draw || flag_contour) {
3171: PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Explicit Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3172: if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3173: } else vdraw = NULL;
3174: PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit %s\n", flag_operator ? "Jacobian" : "preconditioning Jacobian"));
3175: if (flag) PetscCall(MatView(Bexp, vstdout));
3176: if (vdraw) PetscCall(MatView(Bexp, vdraw));
3177: PetscCall(PetscViewerASCIIPrintf(vstdout, "Finite difference Jacobian\n"));
3178: if (flag) PetscCall(MatView(FDexp, vstdout));
3179: if (vdraw) PetscCall(MatView(FDexp, vdraw));
3180: PetscCall(MatAYPX(FDexp, -1.0, Bexp, SAME_NONZERO_PATTERN));
3181: PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian\n"));
3182: if (flag) PetscCall(MatView(FDexp, vstdout));
3183: if (vdraw) { /* Always use contour for the difference */
3184: PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3185: PetscCall(MatView(FDexp, vdraw));
3186: PetscCall(PetscViewerPopFormat(vdraw));
3187: }
3188: if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
3189: PetscCall(PetscViewerDestroy(&vdraw));
3190: PetscCall(MatDestroy(&Bexp_mine));
3191: PetscCall(MatDestroy(&FDexp));
3192: }
3193: }
3194: {
3195: PetscBool flag = PETSC_FALSE, flag_display = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_threshold = PETSC_FALSE;
3196: PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON, threshold_rtol = 10 * PETSC_SQRT_MACHINE_EPSILON;
3197: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring", NULL, NULL, &flag));
3198: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_display", NULL, NULL, &flag_display));
3199: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw", NULL, NULL, &flag_draw));
3200: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw_contour", NULL, NULL, &flag_contour));
3201: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold", NULL, NULL, &flag_threshold));
3202: if (flag_threshold) {
3203: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_rtol", &threshold_rtol, NULL));
3204: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_atol", &threshold_atol, NULL));
3205: }
3206: if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
3207: Mat Bfd;
3208: PetscViewer vdraw, vstdout;
3209: MatColoring coloring;
3210: ISColoring iscoloring;
3211: MatFDColoring matfdcoloring;
3212: SNESFunctionFn *func;
3213: void *funcctx;
3214: PetscReal norm1, norm2, normmax;
3216: PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &Bfd));
3217: PetscCall(MatColoringCreate(Bfd, &coloring));
3218: PetscCall(MatColoringSetType(coloring, MATCOLORINGSL));
3219: PetscCall(MatColoringSetFromOptions(coloring));
3220: PetscCall(MatColoringApply(coloring, &iscoloring));
3221: PetscCall(MatColoringDestroy(&coloring));
3222: PetscCall(MatFDColoringCreate(Bfd, iscoloring, &matfdcoloring));
3223: PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3224: PetscCall(MatFDColoringSetUp(Bfd, iscoloring, matfdcoloring));
3225: PetscCall(ISColoringDestroy(&iscoloring));
3227: /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
3228: PetscCall(SNESGetFunction(snes, NULL, &func, &funcctx));
3229: PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)func, funcctx));
3230: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring, ((PetscObject)snes)->prefix));
3231: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring, "coloring_"));
3232: PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3233: PetscCall(MatFDColoringApply(Bfd, matfdcoloring, X, snes));
3234: PetscCall(MatFDColoringDestroy(&matfdcoloring));
3236: PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3237: if (flag_draw || flag_contour) {
3238: PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Colored Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3239: if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3240: } else vdraw = NULL;
3241: PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit preconditioning Jacobian\n"));
3242: if (flag_display) PetscCall(MatView(B, vstdout));
3243: if (vdraw) PetscCall(MatView(B, vdraw));
3244: PetscCall(PetscViewerASCIIPrintf(vstdout, "Colored Finite difference Jacobian\n"));
3245: if (flag_display) PetscCall(MatView(Bfd, vstdout));
3246: if (vdraw) PetscCall(MatView(Bfd, vdraw));
3247: PetscCall(MatAYPX(Bfd, -1.0, B, SAME_NONZERO_PATTERN));
3248: PetscCall(MatNorm(Bfd, NORM_1, &norm1));
3249: PetscCall(MatNorm(Bfd, NORM_FROBENIUS, &norm2));
3250: PetscCall(MatNorm(Bfd, NORM_MAX, &normmax));
3251: PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n", (double)norm1, (double)norm2, (double)normmax));
3252: if (flag_display) PetscCall(MatView(Bfd, vstdout));
3253: if (vdraw) { /* Always use contour for the difference */
3254: PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3255: PetscCall(MatView(Bfd, vdraw));
3256: PetscCall(PetscViewerPopFormat(vdraw));
3257: }
3258: if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
3260: if (flag_threshold) {
3261: PetscInt bs, rstart, rend, i;
3262: PetscCall(MatGetBlockSize(B, &bs));
3263: PetscCall(MatGetOwnershipRange(B, &rstart, &rend));
3264: for (i = rstart; i < rend; i++) {
3265: const PetscScalar *ba, *ca;
3266: const PetscInt *bj, *cj;
3267: PetscInt bn, cn, j, maxentrycol = -1, maxdiffcol = -1, maxrdiffcol = -1;
3268: PetscReal maxentry = 0, maxdiff = 0, maxrdiff = 0;
3269: PetscCall(MatGetRow(B, i, &bn, &bj, &ba));
3270: PetscCall(MatGetRow(Bfd, i, &cn, &cj, &ca));
3271: PetscCheck(bn == cn, ((PetscObject)A)->comm, PETSC_ERR_PLIB, "Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
3272: for (j = 0; j < bn; j++) {
3273: PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3274: if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
3275: maxentrycol = bj[j];
3276: maxentry = PetscRealPart(ba[j]);
3277: }
3278: if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
3279: maxdiffcol = bj[j];
3280: maxdiff = PetscRealPart(ca[j]);
3281: }
3282: if (rdiff > maxrdiff) {
3283: maxrdiffcol = bj[j];
3284: maxrdiff = rdiff;
3285: }
3286: }
3287: if (maxrdiff > 1) {
3288: 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));
3289: for (j = 0; j < bn; j++) {
3290: PetscReal rdiff;
3291: rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3292: if (rdiff > 1) PetscCall(PetscViewerASCIIPrintf(vstdout, " (%" PetscInt_FMT ",%g:%g)", bj[j], (double)PetscRealPart(ba[j]), (double)PetscRealPart(ca[j])));
3293: }
3294: PetscCall(PetscViewerASCIIPrintf(vstdout, "\n"));
3295: }
3296: PetscCall(MatRestoreRow(B, i, &bn, &bj, &ba));
3297: PetscCall(MatRestoreRow(Bfd, i, &cn, &cj, &ca));
3298: }
3299: }
3300: PetscCall(PetscViewerDestroy(&vdraw));
3301: PetscCall(MatDestroy(&Bfd));
3302: }
3303: }
3304: PetscFunctionReturn(PETSC_SUCCESS);
3305: }
3307: /*@
3308: SNESSetJacobian - Sets the function to compute Jacobian as well as the
3309: location to store the matrix.
3311: Logically Collective
3313: Input Parameters:
3314: + snes - the `SNES` context
3315: . Amat - the matrix that defines the (approximate) Jacobian
3316: . Pmat - the matrix to be used in constructing the preconditioner, usually the same as `Amat`.
3317: . J - Jacobian evaluation routine (if `NULL` then `SNES` retains any previously set value), see `SNESJacobianFn` for details
3318: - ctx - [optional] user-defined context for private data for the
3319: Jacobian evaluation routine (may be `NULL`) (if `NULL` then `SNES` retains any previously set value)
3321: Level: beginner
3323: Notes:
3324: If the `Amat` matrix and `Pmat` matrix are different you must call `MatAssemblyBegin()`/`MatAssemblyEnd()` on
3325: each matrix.
3327: If you know the operator `Amat` has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
3328: space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
3330: If using `SNESComputeJacobianDefaultColor()` to assemble a Jacobian, the `ctx` argument
3331: must be a `MatFDColoring`.
3333: Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian. One common
3334: example is to use the "Picard linearization" which only differentiates through the highest order parts of each term using `SNESSetPicard()`
3336: .seealso: [](ch_snes), `SNES`, `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`,
3337: `SNESSetPicard()`, `SNESJacobianFn`, `SNESFunctionFn`
3338: @*/
3339: PetscErrorCode SNESSetJacobian(SNES snes, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
3340: {
3341: DM dm;
3343: PetscFunctionBegin;
3347: if (Amat) PetscCheckSameComm(snes, 1, Amat, 2);
3348: if (Pmat) PetscCheckSameComm(snes, 1, Pmat, 3);
3349: /* update DMSNES
3350: We support incremental information; so update the function context only if both Amat and Pmat are not specified
3351: (which allows to disable the callbacks when both J and ctx are NULL),
3352: or, if any of the mats is specified, when at least one of J and ctx is not NULL */
3353: PetscCall(SNESGetDM(snes, &dm));
3354: if ((!Amat && !Pmat) || J || ctx) PetscCall(DMSNESSetJacobian(dm, J, ctx));
3355: if (Amat) {
3356: PetscCall(PetscObjectReference((PetscObject)Amat));
3357: PetscCall(MatDestroy(&snes->jacobian));
3359: snes->jacobian = Amat;
3360: }
3361: if (Pmat) {
3362: PetscCall(PetscObjectReference((PetscObject)Pmat));
3363: PetscCall(MatDestroy(&snes->jacobian_pre));
3365: snes->jacobian_pre = Pmat;
3366: }
3367: PetscFunctionReturn(PETSC_SUCCESS);
3368: }
3370: /*@
3371: SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3372: provided context for evaluating the Jacobian.
3374: Not Collective, but `Mat` object will be parallel if `SNES` is
3376: Input Parameter:
3377: . snes - the nonlinear solver context
3379: Output Parameters:
3380: + Amat - location to stash (approximate) Jacobian matrix (or `NULL`)
3381: . Pmat - location to stash matrix used to compute the preconditioner (or `NULL`)
3382: . J - location to put Jacobian function (or `NULL`), for calling sequence see `SNESJacobianFn`
3383: - ctx - location to stash Jacobian ctx (or `NULL`)
3385: Level: advanced
3387: .seealso: [](ch_snes), `SNES`, `Mat`, `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFn`, `SNESGetFunction()`
3388: @*/
3389: PetscErrorCode SNESGetJacobian(SNES snes, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
3390: {
3391: DM dm;
3393: PetscFunctionBegin;
3395: if (Amat) *Amat = snes->jacobian;
3396: if (Pmat) *Pmat = snes->jacobian_pre;
3397: PetscCall(SNESGetDM(snes, &dm));
3398: PetscCall(DMSNESGetJacobian(dm, J, ctx));
3399: PetscFunctionReturn(PETSC_SUCCESS);
3400: }
3402: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3403: {
3404: DM dm;
3405: DMSNES sdm;
3407: PetscFunctionBegin;
3408: PetscCall(SNESGetDM(snes, &dm));
3409: PetscCall(DMGetDMSNES(dm, &sdm));
3410: if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3411: DM dm;
3412: PetscBool isdense, ismf;
3414: PetscCall(SNESGetDM(snes, &dm));
3415: PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &isdense, MATSEQDENSE, MATMPIDENSE, MATDENSE, NULL));
3416: PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &ismf, MATMFFD, MATSHELL, NULL));
3417: if (isdense) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefault, NULL));
3418: else if (!ismf) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefaultColor, NULL));
3419: }
3420: PetscFunctionReturn(PETSC_SUCCESS);
3421: }
3423: /*@
3424: SNESSetUp - Sets up the internal data structures for the later use
3425: of a nonlinear solver `SNESSolve()`.
3427: Collective
3429: Input Parameter:
3430: . snes - the `SNES` context
3432: Level: advanced
3434: Note:
3435: For basic use of the `SNES` solvers the user does not need to explicitly call
3436: `SNESSetUp()`, since these actions will automatically occur during
3437: the call to `SNESSolve()`. However, if one wishes to control this
3438: phase separately, `SNESSetUp()` should be called after `SNESCreate()`
3439: and optional routines of the form SNESSetXXX(), but before `SNESSolve()`.
3441: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`, `SNESDestroy()`, `SNESSetFromOptions()`
3442: @*/
3443: PetscErrorCode SNESSetUp(SNES snes)
3444: {
3445: DM dm;
3446: DMSNES sdm;
3447: SNESLineSearch linesearch, pclinesearch;
3448: void *lsprectx, *lspostctx;
3449: PetscBool mf_operator, mf;
3450: Vec f, fpc;
3451: void *funcctx;
3452: void *jacctx, *appctx;
3453: Mat j, jpre;
3454: PetscErrorCode (*precheck)(SNESLineSearch, Vec, Vec, PetscBool *, PetscCtx);
3455: PetscErrorCode (*postcheck)(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, PetscCtx);
3456: SNESFunctionFn *func;
3457: SNESJacobianFn *jac;
3459: PetscFunctionBegin;
3461: if (snes->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
3462: PetscCall(PetscLogEventBegin(SNES_SetUp, snes, 0, 0, 0));
3464: if (!((PetscObject)snes)->type_name) PetscCall(SNESSetType(snes, SNESNEWTONLS));
3466: PetscCall(SNESGetFunction(snes, &snes->vec_func, NULL, NULL));
3468: PetscCall(SNESGetDM(snes, &dm));
3469: PetscCall(DMGetDMSNES(dm, &sdm));
3470: PetscCall(SNESSetDefaultComputeJacobian(snes));
3472: if (!snes->vec_func) PetscCall(DMCreateGlobalVector(dm, &snes->vec_func));
3474: if (snes->usesksp && !snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
3476: if (snes->linesearch) {
3477: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
3478: PetscCall(SNESLineSearchSetFunction(snes->linesearch, SNESComputeFunction));
3479: }
3481: PetscCall(SNESGetUseMatrixFree(snes, &mf_operator, &mf));
3482: if (snes->npc && snes->npcside == PC_LEFT) {
3483: snes->mf = PETSC_TRUE;
3484: snes->mf_operator = PETSC_FALSE;
3485: }
3486: if (snes->ops->ctxcompute && !snes->ctx) PetscCallBack("SNES callback compute application context", (*snes->ops->ctxcompute)(snes, &snes->ctx));
3487: if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));
3489: if (snes->npc) {
3490: SNESNormSchedule npc_norm_schedule;
3492: /* copy the DM over and the functions if NPC DM is not present */
3493: if (!snes->npc->dm) {
3494: PetscCall(SNESGetDM(snes, &dm));
3495: PetscCall(SNESSetDM(snes->npc, dm));
3497: PetscCall(SNESGetFunction(snes, &f, &func, &funcctx));
3498: PetscCall(VecDuplicate(f, &fpc));
3499: PetscCall(SNESSetFunction(snes->npc, fpc, func, funcctx));
3500: PetscCall(SNESGetJacobian(snes, &j, &jpre, &jac, &jacctx));
3501: PetscCall(SNESSetJacobian(snes->npc, j, jpre, jac, jacctx));
3502: PetscCall(SNESSetUseMatrixFree(snes->npc, mf_operator, mf));
3503: PetscCall(VecDestroy(&fpc));
3505: /* copy the function pointers over */
3506: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)snes, (PetscObject)snes->npc));
3508: /* Propagate app context if not present */
3509: PetscCall(SNESGetApplicationContext(snes->npc, &appctx));
3510: if (!appctx && !snes->npc->ops->ctxcompute) {
3511: if (snes->ops->ctxcompute) {
3512: PetscCall(SNESSetComputeApplicationContext(snes->npc, snes->ops->ctxcompute, snes->ops->ctxdestroy));
3513: } else {
3514: PetscCall(SNESGetApplicationContext(snes, &appctx));
3515: PetscCall(SNESSetApplicationContext(snes->npc, appctx));
3516: }
3517: }
3518: }
3520: /* Set default norm schedule for NPC if not yet set */
3521: PetscCall(SNESGetNormSchedule(snes->npc, &npc_norm_schedule));
3522: if (npc_norm_schedule == SNES_NORM_DEFAULT) {
3523: if (snes->npcside == PC_RIGHT) PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_FINAL_ONLY));
3524: else if (snes->npcside == PC_LEFT) PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_NONE));
3525: }
3527: PetscCall(SNESSetFromOptions(snes->npc));
3529: /* copy the line search context over */
3530: if (snes->dm == snes->npc->dm && snes->linesearch && snes->npc->linesearch) {
3531: PetscCall(SNESGetLineSearch(snes, &linesearch));
3532: PetscCall(SNESGetLineSearch(snes->npc, &pclinesearch));
3533: PetscCall(SNESLineSearchGetPreCheck(linesearch, &precheck, &lsprectx));
3534: PetscCall(SNESLineSearchGetPostCheck(linesearch, &postcheck, &lspostctx));
3535: PetscCall(SNESLineSearchSetPreCheck(pclinesearch, precheck, lsprectx));
3536: PetscCall(SNESLineSearchSetPostCheck(pclinesearch, postcheck, lspostctx));
3537: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
3538: }
3539: }
3541: snes->jac_iter = 0;
3542: snes->pre_iter = 0;
3544: PetscTryTypeMethod(snes, setup);
3546: PetscCall(SNESSetDefaultComputeJacobian(snes));
3548: if (snes->npc && snes->npcside == PC_LEFT) {
3549: if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3550: if (snes->linesearch) {
3551: PetscCall(SNESGetLineSearch(snes, &linesearch));
3552: PetscCall(SNESLineSearchSetFunction(linesearch, SNESComputeFunctionDefaultNPC));
3553: }
3554: }
3555: }
3556: PetscCall(PetscLogEventEnd(SNES_SetUp, snes, 0, 0, 0));
3557: snes->setupcalled = PETSC_TRUE;
3558: PetscFunctionReturn(PETSC_SUCCESS);
3559: }
3561: /*@
3562: 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
3564: Collective
3566: Input Parameter:
3567: . snes - the nonlinear iterative solver context obtained from `SNESCreate()`
3569: Level: intermediate
3571: Notes:
3572: Any options set on the `SNES` object, including those set with `SNESSetFromOptions()` remain.
3574: Call this if you wish to reuse a `SNES` but with different size vectors
3576: Also calls the application context destroy routine set with `SNESSetComputeApplicationContext()`
3578: .seealso: [](ch_snes), `SNES`, `SNESDestroy()`, `SNESCreate()`, `SNESSetUp()`, `SNESSolve()`
3579: @*/
3580: PetscErrorCode SNESReset(SNES snes)
3581: {
3582: PetscFunctionBegin;
3584: if (snes->ops->ctxdestroy && snes->ctx) {
3585: PetscCallBack("SNES callback destroy application context", (*snes->ops->ctxdestroy)(&snes->ctx));
3586: snes->ctx = NULL;
3587: }
3588: if (snes->npc) PetscCall(SNESReset(snes->npc));
3590: PetscTryTypeMethod(snes, reset);
3591: if (snes->ksp) PetscCall(KSPReset(snes->ksp));
3593: if (snes->linesearch) PetscCall(SNESLineSearchReset(snes->linesearch));
3595: PetscCall(VecDestroy(&snes->vec_rhs));
3596: PetscCall(VecDestroy(&snes->vec_sol));
3597: PetscCall(VecDestroy(&snes->vec_sol_update));
3598: PetscCall(VecDestroy(&snes->vec_func));
3599: PetscCall(MatDestroy(&snes->jacobian));
3600: PetscCall(MatDestroy(&snes->jacobian_pre));
3601: PetscCall(MatDestroy(&snes->picard));
3602: PetscCall(VecDestroyVecs(snes->nwork, &snes->work));
3603: PetscCall(VecDestroyVecs(snes->nvwork, &snes->vwork));
3605: snes->alwayscomputesfinalresidual = PETSC_FALSE;
3607: snes->nwork = snes->nvwork = 0;
3608: snes->setupcalled = PETSC_FALSE;
3609: PetscFunctionReturn(PETSC_SUCCESS);
3610: }
3612: /*@
3613: SNESConvergedReasonViewCancel - Clears all the reason view functions for a `SNES` object provided with `SNESConvergedReasonViewSet()` also
3614: removes the default viewer.
3616: Collective
3618: Input Parameter:
3619: . snes - the nonlinear iterative solver context obtained from `SNESCreate()`
3621: Level: intermediate
3623: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESReset()`, `SNESConvergedReasonViewSet()`
3624: @*/
3625: PetscErrorCode SNESConvergedReasonViewCancel(SNES snes)
3626: {
3627: PetscFunctionBegin;
3629: for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
3630: if (snes->reasonviewdestroy[i]) PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3631: }
3632: snes->numberreasonviews = 0;
3633: PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
3634: PetscFunctionReturn(PETSC_SUCCESS);
3635: }
3637: /*@
3638: SNESDestroy - Destroys the nonlinear solver context that was created
3639: with `SNESCreate()`.
3641: Collective
3643: Input Parameter:
3644: . snes - the `SNES` context
3646: Level: beginner
3648: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`
3649: @*/
3650: PetscErrorCode SNESDestroy(SNES *snes)
3651: {
3652: DM dm;
3654: PetscFunctionBegin;
3655: if (!*snes) PetscFunctionReturn(PETSC_SUCCESS);
3657: if (--((PetscObject)*snes)->refct > 0) {
3658: *snes = NULL;
3659: PetscFunctionReturn(PETSC_SUCCESS);
3660: }
3662: PetscCall(SNESReset(*snes));
3663: PetscCall(SNESDestroy(&(*snes)->npc));
3665: /* if memory was published with SAWs then destroy it */
3666: PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
3667: PetscTryTypeMethod(*snes, destroy);
3669: dm = (*snes)->dm;
3670: while (dm) {
3671: PetscCall(DMCoarsenHookRemove(dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, *snes));
3672: PetscCall(DMGetCoarseDM(dm, &dm));
3673: }
3675: PetscCall(DMDestroy(&(*snes)->dm));
3676: PetscCall(KSPDestroy(&(*snes)->ksp));
3677: PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));
3679: PetscCall(PetscFree((*snes)->kspconvctx));
3680: if ((*snes)->ops->convergeddestroy) PetscCall((*(*snes)->ops->convergeddestroy)(&(*snes)->cnvP));
3681: if ((*snes)->conv_hist_alloc) PetscCall(PetscFree2((*snes)->conv_hist, (*snes)->conv_hist_its));
3682: PetscCall(SNESMonitorCancel(*snes));
3683: PetscCall(SNESConvergedReasonViewCancel(*snes));
3684: PetscCall(PetscHeaderDestroy(snes));
3685: PetscFunctionReturn(PETSC_SUCCESS);
3686: }
3688: /* ----------- Routines to set solver parameters ---------- */
3690: /*@
3691: SNESSetLagPreconditioner - Sets when the preconditioner is rebuilt in the nonlinear solve `SNESSolve()`.
3693: Logically Collective
3695: Input Parameters:
3696: + snes - the `SNES` context
3697: - lag - 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3698: the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3700: Options Database Keys:
3701: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3702: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3703: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3704: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3706: Level: intermediate
3708: Notes:
3709: The default is 1
3711: The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or `SNESSetLagPreconditionerPersists()` was called
3713: `SNESSetLagPreconditionerPersists()` allows using the same uniform lagging (for example every second linear solve) across multiple nonlinear solves.
3715: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`,
3716: `SNESSetLagJacobianPersists()`, `SNES`, `SNESSolve()`
3717: @*/
3718: PetscErrorCode SNESSetLagPreconditioner(SNES snes, PetscInt lag)
3719: {
3720: PetscFunctionBegin;
3723: PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3724: PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3725: snes->lagpreconditioner = lag;
3726: PetscFunctionReturn(PETSC_SUCCESS);
3727: }
3729: /*@
3730: SNESSetGridSequence - sets the number of steps of grid sequencing that `SNES` will do
3732: Logically Collective
3734: Input Parameters:
3735: + snes - the `SNES` context
3736: - steps - the number of refinements to do, defaults to 0
3738: Options Database Key:
3739: . -snes_grid_sequence steps - Use grid sequencing to generate initial guess
3741: Level: intermediate
3743: Notes:
3744: Once grid sequencing is turned on `SNESSolve()` will automatically perform the solve on each grid refinement.
3746: Use `SNESGetSolution()` to extract the fine grid solution after grid sequencing.
3748: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`,
3749: `SNESSetDM()`, `SNESSolve()`
3750: @*/
3751: PetscErrorCode SNESSetGridSequence(SNES snes, PetscInt steps)
3752: {
3753: PetscFunctionBegin;
3756: snes->gridsequence = steps;
3757: PetscFunctionReturn(PETSC_SUCCESS);
3758: }
3760: /*@
3761: SNESGetGridSequence - gets the number of steps of grid sequencing that `SNES` will do
3763: Logically Collective
3765: Input Parameter:
3766: . snes - the `SNES` context
3768: Output Parameter:
3769: . steps - the number of refinements to do, defaults to 0
3771: Level: intermediate
3773: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()`
3774: @*/
3775: PetscErrorCode SNESGetGridSequence(SNES snes, PetscInt *steps)
3776: {
3777: PetscFunctionBegin;
3779: *steps = snes->gridsequence;
3780: PetscFunctionReturn(PETSC_SUCCESS);
3781: }
3783: /*@
3784: SNESGetLagPreconditioner - Return how often 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. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3795: Level: intermediate
3797: Notes:
3798: The default is 1
3800: The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3802: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3803: @*/
3804: PetscErrorCode SNESGetLagPreconditioner(SNES snes, PetscInt *lag)
3805: {
3806: PetscFunctionBegin;
3808: *lag = snes->lagpreconditioner;
3809: PetscFunctionReturn(PETSC_SUCCESS);
3810: }
3812: /*@
3813: SNESSetLagJacobian - Set when the Jacobian is rebuilt in the nonlinear solve. See `SNESSetLagPreconditioner()` for determining how
3814: often the preconditioner is rebuilt.
3816: Logically Collective
3818: Input Parameters:
3819: + snes - the `SNES` context
3820: - lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3821: the Jacobian is built etc. -2 means rebuild at next chance but then never again
3823: Options Database Keys:
3824: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3825: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3826: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3827: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag.
3829: Level: intermediate
3831: Notes:
3832: The default is 1
3834: The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3836: 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
3837: at the next Newton step but never again (unless it is reset to another value)
3839: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3840: @*/
3841: PetscErrorCode SNESSetLagJacobian(SNES snes, PetscInt lag)
3842: {
3843: PetscFunctionBegin;
3845: PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3846: PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3848: snes->lagjacobian = lag;
3849: PetscFunctionReturn(PETSC_SUCCESS);
3850: }
3852: /*@
3853: SNESGetLagJacobian - Get how often the Jacobian is rebuilt. See `SNESGetLagPreconditioner()` to determine when the preconditioner is rebuilt
3855: Not Collective
3857: Input Parameter:
3858: . snes - the `SNES` context
3860: Output Parameter:
3861: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3862: the Jacobian is built etc.
3864: Level: intermediate
3866: Notes:
3867: The default is 1
3869: The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or `SNESSetLagJacobianPersists()` was called.
3871: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobian()`, `SNESSetLagPreconditioner()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3872: @*/
3873: PetscErrorCode SNESGetLagJacobian(SNES snes, PetscInt *lag)
3874: {
3875: PetscFunctionBegin;
3877: *lag = snes->lagjacobian;
3878: PetscFunctionReturn(PETSC_SUCCESS);
3879: }
3881: /*@
3882: SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple nonlinear solves
3884: Logically collective
3886: Input Parameters:
3887: + snes - the `SNES` context
3888: - flg - jacobian lagging persists if true
3890: Options Database Keys:
3891: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3892: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3893: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3894: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3896: Level: advanced
3898: Notes:
3899: Normally when `SNESSetLagJacobian()` is used, the Jacobian is always rebuilt at the beginning of each new nonlinear solve, this removes that behavior
3901: This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
3902: several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
3903: timesteps may present huge efficiency gains.
3905: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`
3906: @*/
3907: PetscErrorCode SNESSetLagJacobianPersists(SNES snes, PetscBool flg)
3908: {
3909: PetscFunctionBegin;
3912: snes->lagjac_persist = flg;
3913: PetscFunctionReturn(PETSC_SUCCESS);
3914: }
3916: /*@
3917: SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves
3919: Logically Collective
3921: Input Parameters:
3922: + snes - the `SNES` context
3923: - flg - preconditioner lagging persists if true
3925: Options Database Keys:
3926: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3927: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3928: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3929: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3931: Level: developer
3933: Notes:
3934: Normally when `SNESSetLagPreconditioner()` is used, the preconditioner is always rebuilt at the beginning of each new nonlinear solve, this removes that behavior
3936: This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
3937: by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
3938: several timesteps may present huge efficiency gains.
3940: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
3941: @*/
3942: PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes, PetscBool flg)
3943: {
3944: PetscFunctionBegin;
3947: snes->lagpre_persist = flg;
3948: PetscFunctionReturn(PETSC_SUCCESS);
3949: }
3951: /*@
3952: SNESSetForceIteration - force `SNESSolve()` to take at least one iteration regardless of the initial residual norm
3954: Logically Collective
3956: Input Parameters:
3957: + snes - the `SNES` context
3958: - force - `PETSC_TRUE` require at least one iteration
3960: Options Database Key:
3961: . -snes_force_iteration force - Sets forcing an iteration
3963: Level: intermediate
3965: Note:
3966: This is used sometimes with `TS` to prevent `TS` from detecting a false steady state solution
3968: .seealso: [](ch_snes), `SNES`, `TS`, `SNESSetDivergenceTolerance()`
3969: @*/
3970: PetscErrorCode SNESSetForceIteration(SNES snes, PetscBool force)
3971: {
3972: PetscFunctionBegin;
3974: snes->forceiteration = force;
3975: PetscFunctionReturn(PETSC_SUCCESS);
3976: }
3978: /*@
3979: SNESGetForceIteration - Check whether or not `SNESSolve()` take at least one iteration regardless of the initial residual norm
3981: Logically Collective
3983: Input Parameter:
3984: . snes - the `SNES` context
3986: Output Parameter:
3987: . force - `PETSC_TRUE` requires at least one iteration.
3989: Level: intermediate
3991: .seealso: [](ch_snes), `SNES`, `SNESSetForceIteration()`, `SNESSetDivergenceTolerance()`
3992: @*/
3993: PetscErrorCode SNESGetForceIteration(SNES snes, PetscBool *force)
3994: {
3995: PetscFunctionBegin;
3997: *force = snes->forceiteration;
3998: PetscFunctionReturn(PETSC_SUCCESS);
3999: }
4001: /*@
4002: SNESSetTolerances - Sets various parameters used in `SNES` convergence tests.
4004: Logically Collective
4006: Input Parameters:
4007: + snes - the `SNES` context
4008: . abstol - the absolute convergence tolerance, $ F(x^n) \le abstol $
4009: . rtol - the relative convergence tolerance, $ F(x^n) \le reltol * F(x^0) $
4010: . stol - convergence tolerance in terms of the norm of the change in the solution between steps, || delta x || < stol*|| x ||
4011: . maxit - the maximum number of iterations allowed in the solver, default 50.
4012: - maxf - the maximum number of function evaluations allowed in the solver (use `PETSC_UNLIMITED` indicates no limit), default 10,000
4014: Options Database Keys:
4015: + -snes_atol abstol - Sets `abstol`
4016: . -snes_rtol rtol - Sets `rtol`
4017: . -snes_stol stol - Sets `stol`
4018: . -snes_max_it maxit - Sets `maxit`
4019: - -snes_max_funcs maxf - Sets `maxf` (use `unlimited` to have no maximum)
4021: Level: intermediate
4023: Note:
4024: All parameters must be non-negative
4026: Use `PETSC_CURRENT` to retain the current value of any parameter and `PETSC_DETERMINE` to use the default value for the given `SNES`.
4027: The default value is the value in the object when its type is set.
4029: Use `PETSC_UNLIMITED` on `maxit` or `maxf` to indicate there is no bound on the number of iterations or number of function evaluations.
4031: Fortran Note:
4032: Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_UNLIMITED_INTEGER`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`
4034: .seealso: [](ch_snes), `SNESSolve()`, `SNES`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()`
4035: @*/
4036: PetscErrorCode SNESSetTolerances(SNES snes, PetscReal abstol, PetscReal rtol, PetscReal stol, PetscInt maxit, PetscInt maxf)
4037: {
4038: PetscFunctionBegin;
4046: if (abstol == (PetscReal)PETSC_DETERMINE) {
4047: snes->abstol = snes->default_abstol;
4048: } else if (abstol != (PetscReal)PETSC_CURRENT) {
4049: PetscCheck(abstol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)abstol);
4050: snes->abstol = abstol;
4051: }
4053: if (rtol == (PetscReal)PETSC_DETERMINE) {
4054: snes->rtol = snes->default_rtol;
4055: } else if (rtol != (PetscReal)PETSC_CURRENT) {
4056: 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);
4057: snes->rtol = rtol;
4058: }
4060: if (stol == (PetscReal)PETSC_DETERMINE) {
4061: snes->stol = snes->default_stol;
4062: } else if (stol != (PetscReal)PETSC_CURRENT) {
4063: PetscCheck(stol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Step tolerance %g must be non-negative", (double)stol);
4064: snes->stol = stol;
4065: }
4067: if (maxit == PETSC_DETERMINE) {
4068: snes->max_its = snes->default_max_its;
4069: } else if (maxit == PETSC_UNLIMITED) {
4070: snes->max_its = PETSC_INT_MAX;
4071: } else if (maxit != PETSC_CURRENT) {
4072: PetscCheck(maxit >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of iterations %" PetscInt_FMT " must be non-negative", maxit);
4073: snes->max_its = maxit;
4074: }
4076: if (maxf == PETSC_DETERMINE) {
4077: snes->max_funcs = snes->default_max_funcs;
4078: } else if (maxf == PETSC_UNLIMITED || maxf == -1) {
4079: snes->max_funcs = PETSC_UNLIMITED;
4080: } else if (maxf != PETSC_CURRENT) {
4081: PetscCheck(maxf >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of function evaluations %" PetscInt_FMT " must be nonnegative", maxf);
4082: snes->max_funcs = maxf;
4083: }
4084: PetscFunctionReturn(PETSC_SUCCESS);
4085: }
4087: /*@
4088: SNESSetDivergenceTolerance - Sets the divergence tolerance used for the `SNES` divergence test.
4090: Logically Collective
4092: Input Parameters:
4093: + snes - the `SNES` context
4094: - 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
4095: is stopped due to divergence.
4097: Options Database Key:
4098: . -snes_divergence_tolerance divtol - Sets `divtol`
4100: Level: intermediate
4102: Notes:
4103: Use `PETSC_DETERMINE` to use the default value from when the object's type was set.
4105: Fortran Note:
4106: Use ``PETSC_DETERMINE_REAL` or `PETSC_UNLIMITED_REAL`
4108: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetTolerances()`, `SNESGetDivergenceTolerance()`
4109: @*/
4110: PetscErrorCode SNESSetDivergenceTolerance(SNES snes, PetscReal divtol)
4111: {
4112: PetscFunctionBegin;
4116: if (divtol == (PetscReal)PETSC_DETERMINE) {
4117: snes->divtol = snes->default_divtol;
4118: } else if (divtol == (PetscReal)PETSC_UNLIMITED || divtol == -1) {
4119: snes->divtol = PETSC_UNLIMITED;
4120: } else if (divtol != (PetscReal)PETSC_CURRENT) {
4121: PetscCheck(divtol >= 1.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Divergence tolerance %g must be greater than 1.0", (double)divtol);
4122: snes->divtol = divtol;
4123: }
4124: PetscFunctionReturn(PETSC_SUCCESS);
4125: }
4127: /*@
4128: SNESGetTolerances - Gets various parameters used in `SNES` convergence tests.
4130: Not Collective
4132: Input Parameter:
4133: . snes - the `SNES` context
4135: Output Parameters:
4136: + atol - the absolute convergence tolerance
4137: . rtol - the relative convergence tolerance
4138: . stol - convergence tolerance in terms of the norm of the change in the solution between steps
4139: . maxit - the maximum number of iterations allowed
4140: - maxf - the maximum number of function evaluations allowed, `PETSC_UNLIMITED` indicates no bound
4142: Level: intermediate
4144: Notes:
4145: See `SNESSetTolerances()` for details on the parameters.
4147: The user can specify `NULL` for any parameter that is not needed.
4149: .seealso: [](ch_snes), `SNES`, `SNESSetTolerances()`
4150: @*/
4151: PetscErrorCode SNESGetTolerances(SNES snes, PetscReal *atol, PetscReal *rtol, PetscReal *stol, PetscInt *maxit, PetscInt *maxf)
4152: {
4153: PetscFunctionBegin;
4155: if (atol) *atol = snes->abstol;
4156: if (rtol) *rtol = snes->rtol;
4157: if (stol) *stol = snes->stol;
4158: if (maxit) *maxit = snes->max_its;
4159: if (maxf) *maxf = snes->max_funcs;
4160: PetscFunctionReturn(PETSC_SUCCESS);
4161: }
4163: /*@
4164: SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.
4166: Not Collective
4168: Input Parameters:
4169: + snes - the `SNES` context
4170: - divtol - divergence tolerance
4172: Level: intermediate
4174: .seealso: [](ch_snes), `SNES`, `SNESSetDivergenceTolerance()`
4175: @*/
4176: PetscErrorCode SNESGetDivergenceTolerance(SNES snes, PetscReal *divtol)
4177: {
4178: PetscFunctionBegin;
4180: if (divtol) *divtol = snes->divtol;
4181: PetscFunctionReturn(PETSC_SUCCESS);
4182: }
4184: PETSC_INTERN PetscErrorCode SNESMonitorRange_Private(SNES, PetscInt, PetscReal *);
4186: /*@
4187: SNESMonitorLGRange - Line-graph monitor that plots the residual norm together with residual-range statistics for a `SNESSolve()`
4189: Collective
4191: Input Parameters:
4192: + snes - the `SNES` context
4193: . n - the iteration number
4194: . rnorm - the 2-norm of the residual
4195: - monctx - a `PetscViewer` of type `PETSCVIEWERDRAW` set up with `PetscViewerMonitorLGSetUp()`
4197: Level: intermediate
4199: Note:
4200: 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.
4202: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`, `SNESMonitorDefault()`, `PetscViewerDrawGetDrawLG()`, `PetscDrawLG`
4203: @*/
4204: PetscErrorCode SNESMonitorLGRange(SNES snes, PetscInt n, PetscReal rnorm, PetscCtx monctx)
4205: {
4206: PetscDrawLG lg;
4207: PetscReal x, y, per;
4208: PetscViewer v = (PetscViewer)monctx;
4209: static PetscReal prev; /* should be in the context */
4210: PetscDraw draw;
4212: PetscFunctionBegin;
4214: PetscCall(PetscViewerDrawGetDrawLG(v, 0, &lg));
4215: if (!n) PetscCall(PetscDrawLGReset(lg));
4216: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4217: PetscCall(PetscDrawSetTitle(draw, "Residual norm"));
4218: x = (PetscReal)n;
4219: if (rnorm > 0.0) y = PetscLog10Real(rnorm);
4220: else y = -15.0;
4221: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4222: if (n < 20 || !(n % 5) || snes->reason) {
4223: PetscCall(PetscDrawLGDraw(lg));
4224: PetscCall(PetscDrawLGSave(lg));
4225: }
4227: PetscCall(PetscViewerDrawGetDrawLG(v, 1, &lg));
4228: if (!n) PetscCall(PetscDrawLGReset(lg));
4229: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4230: PetscCall(PetscDrawSetTitle(draw, "% elements > .2*max element"));
4231: PetscCall(SNESMonitorRange_Private(snes, n, &per));
4232: x = (PetscReal)n;
4233: y = 100.0 * per;
4234: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4235: if (n < 20 || !(n % 5) || snes->reason) {
4236: PetscCall(PetscDrawLGDraw(lg));
4237: PetscCall(PetscDrawLGSave(lg));
4238: }
4240: PetscCall(PetscViewerDrawGetDrawLG(v, 2, &lg));
4241: if (!n) {
4242: prev = rnorm;
4243: PetscCall(PetscDrawLGReset(lg));
4244: }
4245: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4246: PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm"));
4247: x = (PetscReal)n;
4248: y = (prev - rnorm) / prev;
4249: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4250: if (n < 20 || !(n % 5) || snes->reason) {
4251: PetscCall(PetscDrawLGDraw(lg));
4252: PetscCall(PetscDrawLGSave(lg));
4253: }
4255: PetscCall(PetscViewerDrawGetDrawLG(v, 3, &lg));
4256: if (!n) PetscCall(PetscDrawLGReset(lg));
4257: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4258: PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm*(% > .2 max)"));
4259: x = (PetscReal)n;
4260: y = (prev - rnorm) / (prev * per);
4261: if (n > 2) { /*skip initial crazy value */
4262: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4263: }
4264: if (n < 20 || !(n % 5) || snes->reason) {
4265: PetscCall(PetscDrawLGDraw(lg));
4266: PetscCall(PetscDrawLGSave(lg));
4267: }
4268: prev = rnorm;
4269: PetscFunctionReturn(PETSC_SUCCESS);
4270: }
4272: /*@
4273: SNESConverged - Run the convergence test and update the `SNESConvergedReason`.
4275: Collective
4277: Input Parameters:
4278: + snes - the `SNES` context
4279: . it - current iteration
4280: . xnorm - 2-norm of current iterate
4281: . snorm - 2-norm of current step
4282: - fnorm - 2-norm of function
4284: Level: developer
4286: Note:
4287: This routine is called by the `SNESSolve()` implementations.
4288: It does not typically need to be called by the user.
4290: .seealso: [](ch_snes), `SNES`, `SNESSolve`, `SNESSetConvergenceTest()`
4291: @*/
4292: PetscErrorCode SNESConverged(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm)
4293: {
4294: PetscFunctionBegin;
4295: if (!snes->reason) {
4296: if (snes->normschedule == SNES_NORM_ALWAYS) PetscUseTypeMethod(snes, converged, it, xnorm, snorm, fnorm, &snes->reason, snes->cnvP);
4297: if (it == snes->max_its && !snes->reason) {
4298: if (snes->normschedule == SNES_NORM_ALWAYS) {
4299: PetscCall(PetscInfo(snes, "Maximum number of iterations has been reached: %" PetscInt_FMT "\n", snes->max_its));
4300: snes->reason = SNES_DIVERGED_MAX_IT;
4301: } else snes->reason = SNES_CONVERGED_ITS;
4302: }
4303: }
4304: PetscFunctionReturn(PETSC_SUCCESS);
4305: }
4307: /*@
4308: SNESMonitor - runs any `SNES` monitor routines provided with `SNESMonitor()` or the options database
4310: Collective
4312: Input Parameters:
4313: + snes - nonlinear solver context obtained from `SNESCreate()`
4314: . iter - current iteration number
4315: - rnorm - current relative norm of the residual
4317: Level: developer
4319: Note:
4320: This routine is called by the `SNESSolve()` implementations.
4321: It does not typically need to be called by the user.
4323: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`
4324: @*/
4325: PetscErrorCode SNESMonitor(SNES snes, PetscInt iter, PetscReal rnorm)
4326: {
4327: PetscInt i, n = snes->numbermonitors;
4329: PetscFunctionBegin;
4330: PetscCall(VecLockReadPush(snes->vec_sol));
4331: for (i = 0; i < n; i++) PetscCall((*snes->monitor[i])(snes, iter, rnorm, snes->monitorcontext[i]));
4332: PetscCall(VecLockReadPop(snes->vec_sol));
4333: PetscFunctionReturn(PETSC_SUCCESS);
4334: }
4336: /* ------------ Routines to set performance monitoring options ----------- */
4338: /*MC
4339: SNESMonitorFunction - functional form passed to `SNESMonitorSet()` to monitor convergence of nonlinear solver
4341: Synopsis:
4342: #include <petscsnes.h>
4343: PetscErrorCode SNESMonitorFunction(SNES snes, PetscInt its, PetscReal norm, PetscCtx mctx)
4345: Collective
4347: Input Parameters:
4348: + snes - the `SNES` context
4349: . its - iteration number
4350: . norm - 2-norm function value (may be estimated)
4351: - mctx - [optional] monitoring context
4353: Level: advanced
4355: .seealso: [](ch_snes), `SNESMonitorSet()`, `PetscCtx`
4356: M*/
4358: /*@
4359: SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
4360: iteration of the `SNES` nonlinear solver to display the iteration's
4361: progress.
4363: Logically Collective
4365: Input Parameters:
4366: + snes - the `SNES` context
4367: . f - the monitor function, for the calling sequence see `SNESMonitorFunction`
4368: . mctx - [optional] user-defined context for private data for the monitor routine (use `NULL` if no context is desired)
4369: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
4371: Calling sequence of f:
4372: + snes - the `SNES` object
4373: . it - the current iteration
4374: . rnorm - norm of the residual
4375: - mctx - the optional monitor context
4377: Options Database Keys:
4378: + -snes_monitor - sets `SNESMonitorDefault()`
4379: . -snes_monitor draw::draw_lg - sets line graph monitor
4380: - -snes_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `SNESMonitorSet()`, but does not cancel those set via
4381: the options database.
4383: Level: intermediate
4385: Note:
4386: Several different monitoring routines may be set by calling
4387: `SNESMonitorSet()` multiple times; all will be called in the
4388: order in which they were set.
4390: Fortran Note:
4391: Only a single monitor function can be set for each `SNES` object
4393: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction`, `PetscCtxDestroyFn`
4394: @*/
4395: PetscErrorCode SNESMonitorSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscInt it, PetscReal rnorm, PetscCtx mctx), PetscCtx mctx, PetscCtxDestroyFn *monitordestroy)
4396: {
4397: PetscFunctionBegin;
4399: for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4400: PetscBool identical;
4402: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->monitor[i], snes->monitorcontext[i], snes->monitordestroy[i], &identical));
4403: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4404: }
4405: PetscCheck(snes->numbermonitors < MAXSNESMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
4406: snes->monitor[snes->numbermonitors] = f;
4407: snes->monitordestroy[snes->numbermonitors] = monitordestroy;
4408: snes->monitorcontext[snes->numbermonitors++] = mctx;
4409: PetscFunctionReturn(PETSC_SUCCESS);
4410: }
4412: /*@
4413: SNESMonitorCancel - Clears all the monitor functions for a `SNES` object.
4415: Logically Collective
4417: Input Parameter:
4418: . snes - the `SNES` context
4420: Options Database Key:
4421: . -snes_monitor_cancel - cancels all monitors that have been hardwired
4422: into a code by calls to `SNESMonitorSet()`, but does not cancel those
4423: set via the options database
4425: Level: intermediate
4427: Note:
4428: There is no way to clear one specific monitor from a `SNES` object.
4430: .seealso: [](ch_snes), `SNES`, `SNESMonitorDefault()`, `SNESMonitorSet()`
4431: @*/
4432: PetscErrorCode SNESMonitorCancel(SNES snes)
4433: {
4434: PetscFunctionBegin;
4436: for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4437: if (snes->monitordestroy[i]) PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4438: }
4439: snes->numbermonitors = 0;
4440: PetscFunctionReturn(PETSC_SUCCESS);
4441: }
4443: /*@
4444: SNESSetConvergenceTest - Sets the function that is to be used
4445: to test for convergence of the nonlinear iterative solution.
4447: Logically Collective
4449: Input Parameters:
4450: + snes - the `SNES` context
4451: . func - routine to test for convergence
4452: . ctx - [optional] context for private data for the convergence routine (may be `NULL`)
4453: - destroy - [optional] destructor for the context (may be `NULL`; `PETSC_NULL_FUNCTION` in Fortran)
4455: Calling sequence of func:
4456: + snes - the `SNES` context
4457: . it - the current iteration number
4458: . xnorm - the norm of the new solution
4459: . snorm - the norm of the step
4460: . fnorm - the norm of the function value
4461: . reason - output, the reason convergence or divergence as declared
4462: - ctx - the optional convergence test context
4464: Level: advanced
4466: .seealso: [](ch_snes), `SNES`, `SNESConvergedDefault()`, `SNESConvergedSkip()`
4467: @*/
4468: PetscErrorCode SNESSetConvergenceTest(SNES snes, PetscErrorCode (*func)(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm, SNESConvergedReason *reason, PetscCtx ctx), PetscCtx ctx, PetscCtxDestroyFn *destroy)
4469: {
4470: PetscFunctionBegin;
4472: if (!func) func = SNESConvergedSkip;
4473: if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(&snes->cnvP));
4474: snes->ops->converged = func;
4475: snes->ops->convergeddestroy = destroy;
4476: snes->cnvP = ctx;
4477: PetscFunctionReturn(PETSC_SUCCESS);
4478: }
4480: /*@
4481: SNESGetConvergedReason - Gets the reason the `SNES` iteration was stopped, which may be due to convergence, divergence, or stagnation
4483: Not Collective
4485: Input Parameter:
4486: . snes - the `SNES` context
4488: Output Parameter:
4489: . reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` for the individual convergence tests for complete lists
4491: Options Database Key:
4492: . -snes_converged_reason - prints the reason to standard out
4494: Level: intermediate
4496: Note:
4497: Should only be called after the call the `SNESSolve()` is complete, if it is called earlier it returns the value `SNES__CONVERGED_ITERATING`.
4499: .seealso: [](ch_snes), `SNESSolve()`, `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason`, `SNESGetConvergedReasonString()`
4500: @*/
4501: PetscErrorCode SNESGetConvergedReason(SNES snes, SNESConvergedReason *reason)
4502: {
4503: PetscFunctionBegin;
4505: PetscAssertPointer(reason, 2);
4506: *reason = snes->reason;
4507: PetscFunctionReturn(PETSC_SUCCESS);
4508: }
4510: /*@
4511: SNESGetConvergedReasonString - Return a human readable string for `SNESConvergedReason`
4513: Not Collective
4515: Input Parameter:
4516: . snes - the `SNES` context
4518: Output Parameter:
4519: . strreason - a human readable string that describes `SNES` converged reason
4521: Level: beginner
4523: .seealso: [](ch_snes), `SNES`, `SNESGetConvergedReason()`
4524: @*/
4525: PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char *strreason[])
4526: {
4527: PetscFunctionBegin;
4529: PetscAssertPointer(strreason, 2);
4530: *strreason = SNESConvergedReasons[snes->reason];
4531: PetscFunctionReturn(PETSC_SUCCESS);
4532: }
4534: /*@
4535: SNESSetConvergedReason - Sets the reason the `SNES` iteration was stopped.
4537: Not Collective
4539: Input Parameters:
4540: + snes - the `SNES` context
4541: - reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` or the
4542: manual pages for the individual convergence tests for complete lists
4544: Level: developer
4546: Developer Note:
4547: Called inside the various `SNESSolve()` implementations
4549: .seealso: [](ch_snes), `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason`
4550: @*/
4551: PetscErrorCode SNESSetConvergedReason(SNES snes, SNESConvergedReason reason)
4552: {
4553: PetscFunctionBegin;
4555: PetscCheck(!snes->errorifnotconverged || reason > 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_PLIB, "SNES code should have previously errored due to negative reason");
4556: snes->reason = reason;
4557: PetscFunctionReturn(PETSC_SUCCESS);
4558: }
4560: /*@
4561: SNESSetConvergenceHistory - Sets the arrays used to hold the convergence history.
4563: Logically Collective
4565: Input Parameters:
4566: + snes - iterative context obtained from `SNESCreate()`
4567: . a - array to hold history, this array will contain the function norms computed at each step
4568: . its - integer array holds the number of linear iterations for each solve.
4569: . na - size of `a` and `its`
4570: - reset - `PETSC_TRUE` indicates each new nonlinear solve resets the history counter to zero,
4571: else it continues storing new values for new nonlinear solves after the old ones
4573: Level: intermediate
4575: Notes:
4576: If 'a' and 'its' are `NULL` then space is allocated for the history. If 'na' is `PETSC_DECIDE` (or, deprecated, `PETSC_DEFAULT`) then a
4577: default array of length 1,000 is allocated.
4579: This routine is useful, e.g., when running a code for purposes
4580: of accurate performance monitoring, when no I/O should be done
4581: during the section of code that is being timed.
4583: If the arrays run out of space after a number of iterations then the later values are not saved in the history
4585: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetConvergenceHistory()`
4586: @*/
4587: PetscErrorCode SNESSetConvergenceHistory(SNES snes, PetscReal a[], PetscInt its[], PetscInt na, PetscBool reset)
4588: {
4589: PetscFunctionBegin;
4591: if (a) PetscAssertPointer(a, 2);
4592: if (its) PetscAssertPointer(its, 3);
4593: if (!a) {
4594: if (na == PETSC_DECIDE) na = 1000;
4595: PetscCall(PetscCalloc2(na, &a, na, &its));
4596: snes->conv_hist_alloc = PETSC_TRUE;
4597: }
4598: snes->conv_hist = a;
4599: snes->conv_hist_its = its;
4600: snes->conv_hist_max = (size_t)na;
4601: snes->conv_hist_len = 0;
4602: snes->conv_hist_reset = reset;
4603: PetscFunctionReturn(PETSC_SUCCESS);
4604: }
4606: #if PetscDefined(HAVE_MATLAB)
4607: #include <engine.h> /* MATLAB include file */
4608: #include <mex.h> /* MATLAB include file */
4610: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4611: {
4612: mxArray *mat;
4613: PetscReal *ar;
4615: mat = mxCreateDoubleMatrix(snes->conv_hist_len, 1, mxREAL);
4616: ar = (PetscReal *)mxGetData(mat);
4617: for (PetscInt i = 0; i < snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4618: return mat;
4619: }
4620: #endif
4622: /*@
4623: SNESGetConvergenceHistory - Gets the arrays used to hold the convergence history.
4625: Not Collective
4627: Input Parameter:
4628: . snes - iterative context obtained from `SNESCreate()`
4630: Output Parameters:
4631: + a - array to hold history, usually was set with `SNESSetConvergenceHistory()`
4632: . its - integer array holds the number of linear iterations (or
4633: negative if not converged) for each solve.
4634: - na - size of `a` and `its`
4636: Level: intermediate
4638: Note:
4639: This routine is useful, e.g., when running a code for purposes
4640: of accurate performance monitoring, when no I/O should be done
4641: during the section of code that is being timed.
4643: Fortran Notes:
4644: Return the arrays with ``SNESRestoreConvergenceHistory()`
4646: Use the arguments
4647: .vb
4648: PetscReal, pointer :: a(:)
4649: PetscInt, pointer :: its(:)
4650: .ve
4652: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetConvergenceHistory()`
4653: @*/
4654: PetscErrorCode SNESGetConvergenceHistory(SNES snes, PetscReal *a[], PetscInt *its[], PetscInt *na)
4655: {
4656: PetscFunctionBegin;
4658: if (a) *a = snes->conv_hist;
4659: if (its) *its = snes->conv_hist_its;
4660: if (na) *na = (PetscInt)snes->conv_hist_len;
4661: PetscFunctionReturn(PETSC_SUCCESS);
4662: }
4664: /*@
4665: SNESSetUpdate - Sets the general-purpose update function called
4666: at the beginning of every iteration of the nonlinear solve. Specifically
4667: it is called just before the Jacobian is "evaluated" and after the function
4668: evaluation.
4670: Logically Collective
4672: Input Parameters:
4673: + snes - The nonlinear solver context
4674: - func - The update function; for calling sequence see `SNESUpdateFn`
4676: Level: advanced
4678: Notes:
4679: 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
4680: to `SNESSetFunction()`, or `SNESSetPicard()`
4681: This is not used by most users, and it is intended to provide a general hook that is run
4682: right before the direction step is computed.
4684: Users are free to modify the current residual vector,
4685: the current linearization point, or any other vector associated to the specific solver used.
4686: If such modifications take place, it is the user responsibility to update all the relevant
4687: vectors. For example, if one is adjusting the model parameters at each Newton step their code may look like
4688: .vb
4689: PetscErrorCode update(SNES snes, PetscInt iteration)
4690: {
4691: PetscFunctionBeginUser;
4692: if (iteration > 0) {
4693: // update the model parameters here
4694: Vec x,f;
4695: PetscCall(SNESGetSolution(snes,&x));
4696: PetcCall(SNESGetFunction(snes,&f,NULL,NULL));
4697: PetscCall(SNESComputeFunction(snes,x,f));
4698: }
4699: PetscFunctionReturn(PETSC_SUCCESS);
4700: }
4701: .ve
4703: 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.
4705: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetJacobian()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`,
4706: `SNESMonitorSet()`
4707: @*/
4708: PetscErrorCode SNESSetUpdate(SNES snes, SNESUpdateFn *func)
4709: {
4710: PetscFunctionBegin;
4712: snes->ops->update = func;
4713: PetscFunctionReturn(PETSC_SUCCESS);
4714: }
4716: /*@
4717: SNESConvergedReasonView - Displays the reason a `SNES` solve converged or diverged to a viewer
4719: Collective
4721: Input Parameters:
4722: + snes - iterative context obtained from `SNESCreate()`
4723: - viewer - the viewer to display the reason
4725: Options Database Keys:
4726: + -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4727: - -snes_converged_reason ::failed - only print reason and number of iterations when diverged
4729: Level: beginner
4731: Note:
4732: To change the format of the output call `PetscViewerPushFormat`(viewer,format) before this call. Use `PETSC_VIEWER_DEFAULT` for the default,
4733: use `PETSC_VIEWER_FAILED` to only display a reason if it fails.
4735: .seealso: [](ch_snes), `SNESConvergedReason`, `PetscViewer`, `SNES`,
4736: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`,
4737: `SNESConvergedReasonViewFromOptions()`,
4738: `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
4739: @*/
4740: PetscErrorCode SNESConvergedReasonView(SNES snes, PetscViewer viewer)
4741: {
4742: PetscViewerFormat format;
4743: PetscBool isAscii;
4745: PetscFunctionBegin;
4746: if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4747: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
4748: if (isAscii) {
4749: PetscCall(PetscViewerGetFormat(viewer, &format));
4750: PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)snes)->tablevel + 1));
4751: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4752: DM dm;
4753: Vec u;
4754: PetscDS prob;
4755: PetscInt Nf;
4756: PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4757: void **exactCtx;
4758: PetscReal error;
4760: PetscCall(SNESGetDM(snes, &dm));
4761: PetscCall(SNESGetSolution(snes, &u));
4762: PetscCall(DMGetDS(dm, &prob));
4763: PetscCall(PetscDSGetNumFields(prob, &Nf));
4764: PetscCall(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx));
4765: for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]));
4766: PetscCall(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error));
4767: PetscCall(PetscFree2(exactSol, exactCtx));
4768: if (error < 1.0e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n"));
4769: else PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", (double)error));
4770: }
4771: if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4772: if (((PetscObject)snes)->prefix) {
4773: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve converged due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4774: } else {
4775: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve converged due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4776: }
4777: } else if (snes->reason <= 0) {
4778: if (((PetscObject)snes)->prefix) {
4779: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4780: } else {
4781: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve did not converge due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4782: }
4783: }
4784: PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)snes)->tablevel + 1));
4785: }
4786: PetscFunctionReturn(PETSC_SUCCESS);
4787: }
4789: /*@
4790: SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4791: end of the nonlinear solver to display the convergence reason of the nonlinear solver.
4793: Logically Collective
4795: Input Parameters:
4796: + snes - the `SNES` context
4797: . f - the `SNESConvergedReason` view function
4798: . vctx - [optional] user-defined context for private data for the `SNESConvergedReason` view function (use `NULL` if no context is desired)
4799: - reasonviewdestroy - [optional] routine that frees the context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
4801: Calling sequence of `f`:
4802: + snes - the `SNES` context
4803: - vctx - [optional] context for private data for the function
4805: Options Database Keys:
4806: + -snes_converged_reason - sets a default `SNESConvergedReasonView()`
4807: - -snes_converged_reason_view_cancel - cancels all converged reason viewers that have been hardwired into a code by
4808: calls to `SNESConvergedReasonViewSet()`, but does not cancel those set via the options database.
4810: Level: intermediate
4812: Note:
4813: Several different converged reason view routines may be set by calling
4814: `SNESConvergedReasonViewSet()` multiple times; all will be called in the
4815: order in which they were set.
4817: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESConvergedReason`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()`,
4818: `PetscCtxDestroyFn`
4819: @*/
4820: PetscErrorCode SNESConvergedReasonViewSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscCtx vctx), PetscCtx vctx, PetscCtxDestroyFn *reasonviewdestroy)
4821: {
4822: PetscFunctionBegin;
4824: for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
4825: PetscBool identical;
4827: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, vctx, reasonviewdestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->reasonview[i], snes->reasonviewcontext[i], snes->reasonviewdestroy[i], &identical));
4828: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4829: }
4830: PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many SNES reasonview set");
4831: snes->reasonview[snes->numberreasonviews] = f;
4832: snes->reasonviewdestroy[snes->numberreasonviews] = reasonviewdestroy;
4833: snes->reasonviewcontext[snes->numberreasonviews++] = vctx;
4834: PetscFunctionReturn(PETSC_SUCCESS);
4835: }
4837: /*@
4838: SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a `SNESConvergedReason` is to be viewed at the end of `SNESSolve()`
4839: All the user-provided viewer routines set with `SNESConvergedReasonViewSet()` will be called, if they exist.
4841: Collective
4843: Input Parameter:
4844: . snes - the `SNES` object
4846: Level: advanced
4848: Note:
4849: This function has a different API and behavior than `PetscObjectViewFromOptions()`
4851: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESConvergedReasonViewSet()`, `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`,
4852: `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`
4853: @*/
4854: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4855: {
4856: static PetscBool incall = PETSC_FALSE;
4858: PetscFunctionBegin;
4859: if (incall) PetscFunctionReturn(PETSC_SUCCESS);
4860: incall = PETSC_TRUE;
4862: /* All user-provided viewers are called first, if they exist. */
4863: for (PetscInt i = 0; i < snes->numberreasonviews; i++) PetscCall((*snes->reasonview[i])(snes, snes->reasonviewcontext[i]));
4865: /* Call PETSc default routine if users ask for it */
4866: if (snes->convergedreasonviewer) {
4867: PetscCall(PetscViewerPushFormat(snes->convergedreasonviewer, snes->convergedreasonformat));
4868: PetscCall(SNESConvergedReasonView(snes, snes->convergedreasonviewer));
4869: PetscCall(PetscViewerPopFormat(snes->convergedreasonviewer));
4870: }
4871: incall = PETSC_FALSE;
4872: PetscFunctionReturn(PETSC_SUCCESS);
4873: }
4875: /*@
4876: SNESSolve - Solves a nonlinear system $F(x) = b $ associated with a `SNES` object
4878: Collective
4880: Input Parameters:
4881: + snes - the `SNES` context
4882: . b - the constant part of the equation $F(x) = b$, or `NULL` to use zero.
4883: - x - the solution vector.
4885: Level: beginner
4887: Note:
4888: The user should initialize the vector, `x`, with the initial guess
4889: for the nonlinear solve prior to calling `SNESSolve()` .
4891: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`,
4892: `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`,
4893: `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()`
4894: @*/
4895: PetscErrorCode SNESSolve(SNES snes, Vec b, Vec x)
4896: {
4897: PetscBool flg;
4898: Vec xcreated = NULL;
4899: DM dm;
4901: PetscFunctionBegin;
4904: if (x) PetscCheckSameComm(snes, 1, x, 3);
4906: if (b) PetscCheckSameComm(snes, 1, b, 2);
4908: /* High level operations using the nonlinear solver */
4909: {
4910: PetscViewer viewer;
4911: PetscViewerFormat format;
4912: PetscInt num;
4913: PetscBool flg;
4914: static PetscBool incall = PETSC_FALSE;
4916: if (!incall) {
4917: /* Estimate the convergence rate of the discretization */
4918: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
4919: if (flg) {
4920: PetscConvEst conv;
4921: DM dm;
4922: PetscReal *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4923: PetscInt Nf;
4925: incall = PETSC_TRUE;
4926: PetscCall(SNESGetDM(snes, &dm));
4927: PetscCall(DMGetNumFields(dm, &Nf));
4928: PetscCall(PetscCalloc1(Nf, &alpha));
4929: PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)snes), &conv));
4930: PetscCall(PetscConvEstSetSolver(conv, (PetscObject)snes));
4931: PetscCall(PetscConvEstSetFromOptions(conv));
4932: PetscCall(PetscConvEstSetUp(conv));
4933: PetscCall(PetscConvEstGetConvRate(conv, alpha));
4934: PetscCall(PetscViewerPushFormat(viewer, format));
4935: PetscCall(PetscConvEstRateView(conv, alpha, viewer));
4936: PetscCall(PetscViewerPopFormat(viewer));
4937: PetscCall(PetscViewerDestroy(&viewer));
4938: PetscCall(PetscConvEstDestroy(&conv));
4939: PetscCall(PetscFree(alpha));
4940: incall = PETSC_FALSE;
4941: }
4942: /* Adaptively refine the initial grid */
4943: num = 1;
4944: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_initial", &num, &flg));
4945: if (flg) {
4946: DMAdaptor adaptor;
4948: incall = PETSC_TRUE;
4949: PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4950: PetscCall(DMAdaptorSetSolver(adaptor, snes));
4951: PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4952: PetscCall(DMAdaptorSetFromOptions(adaptor));
4953: PetscCall(DMAdaptorSetUp(adaptor));
4954: PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
4955: PetscCall(DMAdaptorDestroy(&adaptor));
4956: incall = PETSC_FALSE;
4957: }
4958: /* Use grid sequencing to adapt */
4959: num = 0;
4960: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_sequence", &num, NULL));
4961: if (num) {
4962: DMAdaptor adaptor;
4963: const char *prefix;
4965: incall = PETSC_TRUE;
4966: PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4967: PetscCall(SNESGetOptionsPrefix(snes, &prefix));
4968: PetscCall(DMAdaptorSetOptionsPrefix(adaptor, prefix));
4969: PetscCall(DMAdaptorSetSolver(adaptor, snes));
4970: PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4971: PetscCall(DMAdaptorSetFromOptions(adaptor));
4972: PetscCall(DMAdaptorSetUp(adaptor));
4973: PetscCall(PetscObjectViewFromOptions((PetscObject)adaptor, NULL, "-snes_adapt_view"));
4974: PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
4975: PetscCall(DMAdaptorDestroy(&adaptor));
4976: incall = PETSC_FALSE;
4977: }
4978: }
4979: }
4980: if (!x) x = snes->vec_sol;
4981: if (!x) {
4982: PetscCall(SNESGetDM(snes, &dm));
4983: PetscCall(DMCreateGlobalVector(dm, &xcreated));
4984: x = xcreated;
4985: }
4986: PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view_pre"));
4988: for (PetscInt grid = 0; grid < snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4989: for (PetscInt grid = 0; grid < snes->gridsequence + 1; grid++) {
4990: /* set solution vector */
4991: if (!grid) PetscCall(PetscObjectReference((PetscObject)x));
4992: PetscCall(VecDestroy(&snes->vec_sol));
4993: snes->vec_sol = x;
4994: PetscCall(SNESGetDM(snes, &dm));
4996: /* set affine vector if provided */
4997: PetscCall(PetscObjectReference((PetscObject)b));
4998: PetscCall(VecDestroy(&snes->vec_rhs));
4999: snes->vec_rhs = b;
5001: 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");
5002: PetscCheck(snes->vec_func != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be function vector");
5003: PetscCheck(snes->vec_rhs != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be right-hand side vector");
5004: if (!snes->vec_sol_update /* && snes->vec_sol */) PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_sol_update));
5005: PetscCall(DMShellSetGlobalVector(dm, snes->vec_sol));
5006: PetscCall(SNESSetUp(snes));
5008: if (!grid) {
5009: if (snes->ops->computeinitialguess) PetscCallBack("SNES callback compute initial guess", (*snes->ops->computeinitialguess)(snes, snes->vec_sol, snes->initialguessP));
5010: }
5012: if (snes->conv_hist_reset) snes->conv_hist_len = 0;
5013: PetscCall(SNESResetCounters(snes));
5014: snes->reason = SNES_CONVERGED_ITERATING;
5015: PetscCall(PetscLogEventBegin(SNES_Solve, snes, 0, 0, 0));
5016: PetscUseTypeMethod(snes, solve);
5017: PetscCall(PetscLogEventEnd(SNES_Solve, snes, 0, 0, 0));
5018: PetscCheck(snes->reason, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal error, solver %s returned without setting converged reason", ((PetscObject)snes)->type_name);
5019: snes->functiondomainerror = PETSC_FALSE; /* clear the flag if it has been set */
5020: snes->objectivedomainerror = PETSC_FALSE; /* clear the flag if it has been set */
5021: snes->jacobiandomainerror = PETSC_FALSE; /* clear the flag if it has been set */
5023: if (snes->lagjac_persist) snes->jac_iter += snes->iter;
5024: if (snes->lagpre_persist) snes->pre_iter += snes->iter;
5026: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_test_local_min", NULL, NULL, &flg));
5027: if (flg && !PetscPreLoadingOn) PetscCall(SNESTestLocalMin(snes));
5028: /* Call converged reason views. This may involve user-provided viewers as well */
5029: PetscCall(SNESConvergedReasonViewFromOptions(snes));
5031: if (snes->errorifnotconverged) {
5032: if (snes->reason < 0) PetscCall(SNESMonitorCancel(snes));
5033: PetscCheck(snes->reason >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_NOT_CONVERGED, "SNESSolve has not converged");
5034: }
5035: if (snes->reason < 0) break;
5036: if (grid < snes->gridsequence) {
5037: DM fine;
5038: Vec xnew;
5039: Mat interp;
5041: PetscCall(DMRefine(snes->dm, PetscObjectComm((PetscObject)snes), &fine));
5042: PetscCheck(fine, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_INCOMP, "DMRefine() did not perform any refinement, cannot continue grid sequencing");
5043: PetscCall(DMGetCoordinatesLocalSetUp(fine));
5044: PetscCall(DMCreateInterpolation(snes->dm, fine, &interp, NULL));
5045: PetscCall(DMCreateGlobalVector(fine, &xnew));
5046: PetscCall(MatInterpolate(interp, x, xnew));
5047: PetscCall(DMInterpolate(snes->dm, interp, fine));
5048: PetscCall(MatDestroy(&interp));
5049: x = xnew;
5051: PetscCall(SNESReset(snes));
5052: PetscCall(SNESSetDM(snes, fine));
5053: PetscCall(SNESResetFromOptions(snes));
5054: PetscCall(DMDestroy(&fine));
5055: PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
5056: }
5057: }
5058: PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view"));
5059: PetscCall(VecViewFromOptions(snes->vec_sol, (PetscObject)snes, "-snes_view_solution"));
5060: PetscCall(DMMonitor(snes->dm));
5061: PetscCall(SNESMonitorPauseFinal_Internal(snes));
5063: PetscCall(VecDestroy(&xcreated));
5064: PetscCall(PetscObjectSAWsBlock((PetscObject)snes));
5065: PetscFunctionReturn(PETSC_SUCCESS);
5066: }
5068: /* --------- Internal routines for SNES Package --------- */
5070: /*@
5071: SNESSetType - Sets the algorithm/method to be used to solve the nonlinear system with the given `SNES`
5073: Collective
5075: Input Parameters:
5076: + snes - the `SNES` context
5077: - type - a known method
5079: Options Database Key:
5080: . -snes_type type - Sets the method; see `SNESType`
5082: Level: intermediate
5084: Notes:
5085: See `SNESType` for available methods (for instance)
5086: + `SNESNEWTONLS` - Newton's method with line search
5087: (systems of nonlinear equations)
5088: - `SNESNEWTONTR` - Newton's method with trust region
5089: (systems of nonlinear equations)
5091: Normally, it is best to use the `SNESSetFromOptions()` command and then
5092: set the `SNES` solver type from the options database rather than by using
5093: this routine. Using the options database provides the user with
5094: maximum flexibility in evaluating the many nonlinear solvers.
5095: The `SNESSetType()` routine is provided for those situations where it
5096: is necessary to set the nonlinear solver independently of the command
5097: line or options database. This might be the case, for example, when
5098: the choice of solver changes during the execution of the program,
5099: and the user's application is taking responsibility for choosing the
5100: appropriate method.
5102: Developer Note:
5103: `SNESRegister()` adds a constructor for a new `SNESType` to `SNESList`, `SNESSetType()` locates
5104: the constructor in that list and calls it to create the specific object.
5106: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()`
5107: @*/
5108: PetscErrorCode SNESSetType(SNES snes, SNESType type)
5109: {
5110: PetscBool match;
5111: PetscErrorCode (*r)(SNES);
5113: PetscFunctionBegin;
5115: PetscAssertPointer(type, 2);
5117: PetscCall(PetscObjectTypeCompare((PetscObject)snes, type, &match));
5118: if (match) PetscFunctionReturn(PETSC_SUCCESS);
5120: PetscCall(PetscFunctionListFind(SNESList, type, &r));
5121: PetscCheck(r, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unable to find requested SNES type %s", type);
5122: /* Destroy the previous private SNES context */
5123: PetscTryTypeMethod(snes, destroy);
5124: /* Reinitialize type-specific function pointers in SNESOps structure */
5125: snes->ops->reset = NULL;
5126: snes->ops->setup = NULL;
5127: snes->ops->solve = NULL;
5128: snes->ops->view = NULL;
5129: snes->ops->setfromoptions = NULL;
5130: snes->ops->destroy = NULL;
5132: /* It may happen the user has customized the line search before calling SNESSetType */
5133: if (((PetscObject)snes)->type_name) PetscCall(SNESLineSearchDestroy(&snes->linesearch));
5135: /* Reinitialize default parameters */
5136: PetscCall(SNESParametersInitialize(snes));
5138: /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
5139: snes->setupcalled = PETSC_FALSE;
5140: PetscCall(PetscObjectChangeTypeName((PetscObject)snes, type));
5141: PetscCall((*r)(snes));
5142: PetscFunctionReturn(PETSC_SUCCESS);
5143: }
5145: /*@
5146: SNESGetType - Gets the `SNES` method type and name (as a string).
5148: Not Collective
5150: Input Parameter:
5151: . snes - nonlinear solver context
5153: Output Parameter:
5154: . type - `SNES` method (a character string)
5156: Level: intermediate
5158: Note:
5159: `type` should not be retained for later use as it will be an invalid pointer if the `SNESType` of `snes` is changed.
5161: .seealso: [](ch_snes), `SNESSetType()`, `SNESType`, `SNESSetFromOptions()`, `SNES`, `PetscObjectTypeCompare()`, `PetscObjectTypeCompareAny()`
5162: @*/
5163: PetscErrorCode SNESGetType(SNES snes, SNESType *type)
5164: {
5165: PetscFunctionBegin;
5167: PetscAssertPointer(type, 2);
5168: *type = ((PetscObject)snes)->type_name;
5169: PetscFunctionReturn(PETSC_SUCCESS);
5170: }
5172: /*@
5173: SNESSetSolution - Sets the solution vector for use by the `SNES` routines.
5175: Logically Collective
5177: Input Parameters:
5178: + snes - the `SNES` context obtained from `SNESCreate()`
5179: - u - the solution vector
5181: Level: beginner
5183: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetSolution()`, `Vec`
5184: @*/
5185: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
5186: {
5187: DM dm;
5189: PetscFunctionBegin;
5192: PetscCall(PetscObjectReference((PetscObject)u));
5193: PetscCall(VecDestroy(&snes->vec_sol));
5195: snes->vec_sol = u;
5197: PetscCall(SNESGetDM(snes, &dm));
5198: PetscCall(DMShellSetGlobalVector(dm, u));
5199: PetscFunctionReturn(PETSC_SUCCESS);
5200: }
5202: /*@
5203: SNESGetSolution - Returns the vector where the approximate solution is
5204: stored. This is the fine grid solution when using `SNESSetGridSequence()`.
5206: Not Collective, but `x` is parallel if `snes` is parallel
5208: Input Parameter:
5209: . snes - the `SNES` context
5211: Output Parameter:
5212: . x - the solution
5214: Level: intermediate
5216: .seealso: [](ch_snes), `SNESSetSolution()`, `SNESSolve()`, `SNES`, `SNESGetSolutionUpdate()`, `SNESGetFunction()`
5217: @*/
5218: PetscErrorCode SNESGetSolution(SNES snes, Vec *x)
5219: {
5220: PetscFunctionBegin;
5222: PetscAssertPointer(x, 2);
5223: *x = snes->vec_sol;
5224: PetscFunctionReturn(PETSC_SUCCESS);
5225: }
5227: /*@
5228: SNESGetSolutionUpdate - Returns the vector where the solution update is
5229: stored.
5231: Not Collective, but `x` is parallel if `snes` is parallel
5233: Input Parameter:
5234: . snes - the `SNES` context
5236: Output Parameter:
5237: . x - the solution update
5239: Level: advanced
5241: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`
5242: @*/
5243: PetscErrorCode SNESGetSolutionUpdate(SNES snes, Vec *x)
5244: {
5245: PetscFunctionBegin;
5247: PetscAssertPointer(x, 2);
5248: *x = snes->vec_sol_update;
5249: PetscFunctionReturn(PETSC_SUCCESS);
5250: }
5252: /*@
5253: SNESGetFunction - Returns the function that defines the nonlinear system set with `SNESSetFunction()`
5255: Not Collective, but `r` is parallel if `snes` is parallel. Collective if `r` is requested, but has not been created yet.
5257: Input Parameter:
5258: . snes - the `SNES` context
5260: Output Parameters:
5261: + r - the vector that is used to store residuals (or `NULL` if you don't want it)
5262: . f - the function (or `NULL` if you don't want it); for calling sequence see `SNESFunctionFn`
5263: - ctx - the function context (or `NULL` if you don't want it)
5265: Level: advanced
5267: Note:
5268: The vector `r` DOES NOT, in general, contain the current value of the `SNES` nonlinear function
5270: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunctionFn`
5271: @*/
5272: PetscErrorCode SNESGetFunction(SNES snes, Vec *r, SNESFunctionFn **f, PetscCtxRt ctx)
5273: {
5274: DM dm;
5276: PetscFunctionBegin;
5278: if (r) {
5279: if (!snes->vec_func) {
5280: if (snes->vec_rhs) {
5281: PetscCall(VecDuplicate(snes->vec_rhs, &snes->vec_func));
5282: } else if (snes->vec_sol) {
5283: PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_func));
5284: } else if (snes->dm) {
5285: PetscCall(DMCreateGlobalVector(snes->dm, &snes->vec_func));
5286: }
5287: }
5288: *r = snes->vec_func;
5289: }
5290: PetscCall(SNESGetDM(snes, &dm));
5291: PetscCall(DMSNESGetFunction(dm, f, ctx));
5292: PetscFunctionReturn(PETSC_SUCCESS);
5293: }
5295: /*@
5296: SNESGetNGS - Returns the function and context set with `SNESSetNGS()`
5298: Input Parameter:
5299: . snes - the `SNES` context
5301: Output Parameters:
5302: + f - the function (or `NULL`) see `SNESNGSFn` for calling sequence
5303: - ctx - the function context (or `NULL`)
5305: Level: advanced
5307: .seealso: [](ch_snes), `SNESSetNGS()`, `SNESGetFunction()`, `SNESNGSFn`
5308: @*/
5309: PetscErrorCode SNESGetNGS(SNES snes, SNESNGSFn **f, PetscCtxRt ctx)
5310: {
5311: DM dm;
5313: PetscFunctionBegin;
5315: PetscCall(SNESGetDM(snes, &dm));
5316: PetscCall(DMSNESGetNGS(dm, f, ctx));
5317: PetscFunctionReturn(PETSC_SUCCESS);
5318: }
5320: /*@
5321: SNESSetOptionsPrefix - Sets the prefix used for searching for all
5322: `SNES` options in the database.
5324: Logically Collective
5326: Input Parameters:
5327: + snes - the `SNES` context
5328: - prefix - the prefix to prepend to all option names
5330: Level: advanced
5332: Note:
5333: A hyphen (-) must NOT be given at the beginning of the prefix name.
5334: The first character of all runtime options is AUTOMATICALLY the hyphen.
5336: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESAppendOptionsPrefix()`
5337: @*/
5338: PetscErrorCode SNESSetOptionsPrefix(SNES snes, const char prefix[])
5339: {
5340: PetscFunctionBegin;
5342: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes, prefix));
5343: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5344: if (snes->linesearch) {
5345: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5346: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch, prefix));
5347: }
5348: PetscCall(KSPSetOptionsPrefix(snes->ksp, prefix));
5349: PetscFunctionReturn(PETSC_SUCCESS);
5350: }
5352: /*@
5353: SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5354: `SNES` options in the database.
5356: Logically Collective
5358: Input Parameters:
5359: + snes - the `SNES` context
5360: - prefix - the prefix to prepend to all option names
5362: Level: advanced
5364: Note:
5365: A hyphen (-) must NOT be given at the beginning of the prefix name.
5366: The first character of all runtime options is AUTOMATICALLY the hyphen.
5368: .seealso: [](ch_snes), `SNESGetOptionsPrefix()`, `SNESSetOptionsPrefix()`
5369: @*/
5370: PetscErrorCode SNESAppendOptionsPrefix(SNES snes, const char prefix[])
5371: {
5372: PetscFunctionBegin;
5374: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes, prefix));
5375: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5376: if (snes->linesearch) {
5377: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5378: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch, prefix));
5379: }
5380: PetscCall(KSPAppendOptionsPrefix(snes->ksp, prefix));
5381: PetscFunctionReturn(PETSC_SUCCESS);
5382: }
5384: /*@
5385: SNESGetOptionsPrefix - Gets the prefix used for searching for all
5386: `SNES` options in the database.
5388: Not Collective
5390: Input Parameter:
5391: . snes - the `SNES` context
5393: Output Parameter:
5394: . prefix - pointer to the prefix string used
5396: Level: advanced
5398: .seealso: [](ch_snes), `SNES`, `SNESSetOptionsPrefix()`, `SNESAppendOptionsPrefix()`
5399: @*/
5400: PetscErrorCode SNESGetOptionsPrefix(SNES snes, const char *prefix[])
5401: {
5402: PetscFunctionBegin;
5404: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes, prefix));
5405: PetscFunctionReturn(PETSC_SUCCESS);
5406: }
5408: /*@
5409: SNESRegister - Adds a method to the nonlinear solver package.
5411: Not Collective
5413: Input Parameters:
5414: + sname - name of a new user-defined solver
5415: - function - routine to create method context
5417: Level: advanced
5419: Note:
5420: `SNESRegister()` may be called multiple times to add several user-defined solvers.
5422: Example Usage:
5423: .vb
5424: SNESRegister("my_solver", MySolverCreate);
5425: .ve
5427: Then, your solver can be chosen with the procedural interface via
5428: .vb
5429: SNESSetType(snes, "my_solver")
5430: .ve
5431: or at runtime via the option
5432: .vb
5433: -snes_type my_solver
5434: .ve
5436: .seealso: [](ch_snes), `SNESRegisterAll()`, `SNESRegisterDestroy()`
5437: @*/
5438: PetscErrorCode SNESRegister(const char sname[], PetscErrorCode (*function)(SNES))
5439: {
5440: PetscFunctionBegin;
5441: PetscCall(SNESInitializePackage());
5442: PetscCall(PetscFunctionListAdd(&SNESList, sname, function));
5443: PetscFunctionReturn(PETSC_SUCCESS);
5444: }
5446: /*@
5447: 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
5449: Collective
5451: Input Parameter:
5452: . snes - the `SNES` context
5454: Level: developer
5456: Note:
5457: 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.
5459: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESComputeFunction()`
5460: @*/
5461: PetscErrorCode SNESTestLocalMin(SNES snes)
5462: {
5463: PetscInt N, i, j;
5464: Vec u, uh, fh;
5465: PetscScalar value;
5466: PetscReal norm;
5468: PetscFunctionBegin;
5469: PetscCall(SNESGetSolution(snes, &u));
5470: PetscCall(VecDuplicate(u, &uh));
5471: PetscCall(VecDuplicate(u, &fh));
5473: /* currently only works for sequential */
5474: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "Testing FormFunction() for local min\n"));
5475: PetscCall(VecGetSize(u, &N));
5476: for (i = 0; i < N; i++) {
5477: PetscCall(VecCopy(u, uh));
5478: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "i = %" PetscInt_FMT "\n", i));
5479: for (j = -10; j < 11; j++) {
5480: value = PetscSign(j) * PetscExpReal(PetscAbs(j) - 10.0);
5481: PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5482: PetscCall(SNESComputeFunction(snes, uh, fh));
5483: PetscCall(VecNorm(fh, NORM_2, &norm)); /* does not handle use of SNESSetFunctionDomainError() correctly */
5484: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), " j norm %" PetscInt_FMT " %18.16e\n", j, (double)norm));
5485: value = -value;
5486: PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5487: }
5488: }
5489: PetscCall(VecDestroy(&uh));
5490: PetscCall(VecDestroy(&fh));
5491: PetscFunctionReturn(PETSC_SUCCESS);
5492: }
5494: /*@
5495: SNESGetLineSearch - Returns the line search associated with the `SNES`.
5497: Not Collective
5499: Input Parameter:
5500: . snes - iterative context obtained from `SNESCreate()`
5502: Output Parameter:
5503: . linesearch - linesearch context
5505: Level: beginner
5507: Notes:
5508: It creates a default line search instance which can be configured as needed in case it has not been already set with `SNESSetLineSearch()`.
5510: You can also use the options database keys `-snes_linesearch_*` to configure the line search. See `SNESLineSearchSetFromOptions()` for the possible options.
5512: .seealso: [](ch_snes), `SNESLineSearch`, `SNESSetLineSearch()`, `SNESLineSearchCreate()`, `SNESLineSearchSetFromOptions()`
5513: @*/
5514: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5515: {
5516: const char *optionsprefix;
5518: PetscFunctionBegin;
5520: PetscAssertPointer(linesearch, 2);
5521: if (!snes->linesearch) {
5522: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5523: PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
5524: PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes));
5525: PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
5526: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->linesearch, (PetscObject)snes, 1));
5527: }
5528: *linesearch = snes->linesearch;
5529: PetscFunctionReturn(PETSC_SUCCESS);
5530: }
5532: /*@
5533: SNESKSPSetUseEW - Sets `SNES` to the use Eisenstat-Walker method for
5534: computing relative tolerance for linear solvers within an inexact
5535: Newton method.
5537: Logically Collective
5539: Input Parameters:
5540: + snes - `SNES` context
5541: - flag - `PETSC_TRUE` or `PETSC_FALSE`
5543: Options Database Keys:
5544: + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
5545: . -snes_ksp_ew_version ver - version of Eisenstat-Walker method
5546: . -snes_ksp_ew_rtol0 rtol0 - Sets rtol0
5547: . -snes_ksp_ew_rtolmax rtolmax - Sets rtolmax
5548: . -snes_ksp_ew_gamma gamma - Sets gamma
5549: . -snes_ksp_ew_alpha alpha - Sets alpha
5550: . -snes_ksp_ew_alpha2 alpha2 - Sets alpha2
5551: - -snes_ksp_ew_threshold threshold - Sets threshold
5553: Level: advanced
5555: Note:
5556: The default is to use a constant relative tolerance for
5557: the inner linear solvers. Alternatively, one can use the
5558: Eisenstat-Walker method {cite}`ew96`, where the relative convergence tolerance
5559: is reset at each Newton iteration according progress of the nonlinear
5560: solver.
5562: .seealso: [](ch_snes), `KSP`, `SNES`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5563: @*/
5564: PetscErrorCode SNESKSPSetUseEW(SNES snes, PetscBool flag)
5565: {
5566: PetscFunctionBegin;
5569: snes->ksp_ewconv = flag;
5570: PetscFunctionReturn(PETSC_SUCCESS);
5571: }
5573: /*@
5574: SNESKSPGetUseEW - Gets if `SNES` is using Eisenstat-Walker method
5575: for computing relative tolerance for linear solvers within an
5576: inexact Newton method.
5578: Not Collective
5580: Input Parameter:
5581: . snes - `SNES` context
5583: Output Parameter:
5584: . flag - `PETSC_TRUE` or `PETSC_FALSE`
5586: Level: advanced
5588: .seealso: [](ch_snes), `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5589: @*/
5590: PetscErrorCode SNESKSPGetUseEW(SNES snes, PetscBool *flag)
5591: {
5592: PetscFunctionBegin;
5594: PetscAssertPointer(flag, 2);
5595: *flag = snes->ksp_ewconv;
5596: PetscFunctionReturn(PETSC_SUCCESS);
5597: }
5599: /*@
5600: SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5601: convergence criteria for the linear solvers within an inexact
5602: Newton method.
5604: Logically Collective
5606: Input Parameters:
5607: + snes - `SNES` context
5608: . version - version 1, 2 (default is 2), 3 or 4
5609: . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5610: . rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5611: . gamma - multiplicative factor for version 2 rtol computation
5612: (0 <= gamma2 <= 1)
5613: . alpha - power for version 2 rtol computation (1 < alpha <= 2)
5614: . alpha2 - power for safeguard
5615: - threshold - threshold for imposing safeguard (0 < threshold < 1)
5617: Level: advanced
5619: Notes:
5620: Version 3 was contributed by Luis Chacon, June 2006.
5622: Use `PETSC_CURRENT` to retain the default for any of the parameters.
5624: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`
5625: @*/
5626: PetscErrorCode SNESKSPSetParametersEW(SNES snes, PetscInt version, PetscReal rtol_0, PetscReal rtol_max, PetscReal gamma, PetscReal alpha, PetscReal alpha2, PetscReal threshold)
5627: {
5628: SNESKSPEW *kctx;
5630: PetscFunctionBegin;
5632: kctx = (SNESKSPEW *)snes->kspconvctx;
5633: PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5642: if (version != PETSC_CURRENT) kctx->version = version;
5643: if (rtol_0 != (PetscReal)PETSC_CURRENT) kctx->rtol_0 = rtol_0;
5644: if (rtol_max != (PetscReal)PETSC_CURRENT) kctx->rtol_max = rtol_max;
5645: if (gamma != (PetscReal)PETSC_CURRENT) kctx->gamma = gamma;
5646: if (alpha != (PetscReal)PETSC_CURRENT) kctx->alpha = alpha;
5647: if (alpha2 != (PetscReal)PETSC_CURRENT) kctx->alpha2 = alpha2;
5648: if (threshold != (PetscReal)PETSC_CURRENT) kctx->threshold = threshold;
5650: 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);
5651: 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);
5652: 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);
5653: 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);
5654: 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);
5655: 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);
5656: PetscFunctionReturn(PETSC_SUCCESS);
5657: }
5659: /*@
5660: SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5661: convergence criteria for the linear solvers within an inexact
5662: Newton method.
5664: Not Collective
5666: Input Parameter:
5667: . snes - `SNES` context
5669: Output Parameters:
5670: + version - version 1, 2 (default is 2), 3 or 4
5671: . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5672: . rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5673: . gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5674: . alpha - power for version 2 rtol computation (1 < alpha <= 2)
5675: . alpha2 - power for safeguard
5676: - threshold - threshold for imposing safeguard (0 < threshold < 1)
5678: Level: advanced
5680: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()`
5681: @*/
5682: PetscErrorCode SNESKSPGetParametersEW(SNES snes, PetscInt *version, PetscReal *rtol_0, PetscReal *rtol_max, PetscReal *gamma, PetscReal *alpha, PetscReal *alpha2, PetscReal *threshold)
5683: {
5684: SNESKSPEW *kctx;
5686: PetscFunctionBegin;
5688: kctx = (SNESKSPEW *)snes->kspconvctx;
5689: PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5690: if (version) *version = kctx->version;
5691: if (rtol_0) *rtol_0 = kctx->rtol_0;
5692: if (rtol_max) *rtol_max = kctx->rtol_max;
5693: if (gamma) *gamma = kctx->gamma;
5694: if (alpha) *alpha = kctx->alpha;
5695: if (alpha2) *alpha2 = kctx->alpha2;
5696: if (threshold) *threshold = kctx->threshold;
5697: PetscFunctionReturn(PETSC_SUCCESS);
5698: }
5700: PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5701: {
5702: SNES snes = (SNES)ctx;
5703: SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5704: PetscReal rtol = PETSC_CURRENT, stol;
5706: PetscFunctionBegin;
5707: if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5708: if (!snes->iter) {
5709: rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5710: PetscCall(VecNorm(snes->vec_func, NORM_2, &kctx->norm_first));
5711: } else {
5712: PetscCheck(kctx->version >= 1 && kctx->version <= 4, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only versions 1-4 are supported: %" PetscInt_FMT, kctx->version);
5713: if (kctx->version == 1) {
5714: rtol = PetscAbsReal(snes->norm - kctx->lresid_last) / kctx->norm_last;
5715: stol = PetscPowReal(kctx->rtol_last, kctx->alpha2);
5716: if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5717: } else if (kctx->version == 2) {
5718: rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5719: stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5720: if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5721: } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5722: rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5723: /* safeguard: avoid sharp decrease of rtol */
5724: stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5725: stol = PetscMax(rtol, stol);
5726: rtol = PetscMin(kctx->rtol_0, stol);
5727: /* safeguard: avoid oversolving */
5728: stol = kctx->gamma * (kctx->norm_first * snes->rtol) / snes->norm;
5729: stol = PetscMax(rtol, stol);
5730: rtol = PetscMin(kctx->rtol_0, stol);
5731: } else /* if (kctx->version == 4) */ {
5732: /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */
5733: PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm);
5734: PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last);
5735: PetscReal rk = ared / pred;
5736: if (rk < kctx->v4_p1) rtol = 1. - 2. * kctx->v4_p1;
5737: else if (rk < kctx->v4_p2) rtol = kctx->rtol_last;
5738: else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last;
5739: else rtol = kctx->v4_m2 * kctx->rtol_last;
5741: 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;
5742: kctx->rtol_last_2 = kctx->rtol_last;
5743: kctx->rk_last_2 = kctx->rk_last;
5744: kctx->rk_last = rk;
5745: }
5746: }
5747: /* safeguard: avoid rtol greater than rtol_max */
5748: rtol = PetscMin(rtol, kctx->rtol_max);
5749: PetscCall(KSPSetTolerances(ksp, rtol, PETSC_CURRENT, PETSC_CURRENT, PETSC_CURRENT));
5750: PetscCall(PetscInfo(snes, "iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n", snes->iter, kctx->version, (double)rtol));
5751: PetscFunctionReturn(PETSC_SUCCESS);
5752: }
5754: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5755: {
5756: SNES snes = (SNES)ctx;
5757: SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5758: PCSide pcside;
5759: Vec lres;
5761: PetscFunctionBegin;
5762: if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5763: PetscCall(KSPGetTolerances(ksp, &kctx->rtol_last, NULL, NULL, NULL));
5764: kctx->norm_last = snes->norm;
5765: if (kctx->version == 1 || kctx->version == 4) {
5766: PC pc;
5767: PetscBool getRes;
5769: PetscCall(KSPGetPC(ksp, &pc));
5770: PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCNONE, &getRes));
5771: if (!getRes) {
5772: KSPNormType normtype;
5774: PetscCall(KSPGetNormType(ksp, &normtype));
5775: getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED);
5776: }
5777: PetscCall(KSPGetPCSide(ksp, &pcside));
5778: if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */
5779: PetscCall(KSPGetResidualNorm(ksp, &kctx->lresid_last));
5780: } else {
5781: /* KSP residual is preconditioned residual */
5782: /* compute true linear residual norm */
5783: Mat J;
5784: PetscCall(KSPGetOperators(ksp, &J, NULL));
5785: PetscCall(VecDuplicate(b, &lres));
5786: PetscCall(MatMult(J, x, lres));
5787: PetscCall(VecAYPX(lres, -1.0, b));
5788: PetscCall(VecNorm(lres, NORM_2, &kctx->lresid_last));
5789: PetscCall(VecDestroy(&lres));
5790: }
5791: }
5792: PetscFunctionReturn(PETSC_SUCCESS);
5793: }
5795: #include <petsc/private/kspimpl.h>
5796: /*@
5797: SNESGetKSP - Returns the `KSP` context for a `SNES` solver.
5799: Not Collective, but if `snes` is parallel, then `ksp` is parallel
5801: Input Parameter:
5802: . snes - the `SNES` context
5804: Output Parameter:
5805: . ksp - the `KSP` context
5807: Level: beginner
5809: Notes:
5810: The user can then directly manipulate the `KSP` context to set various
5811: options, etc. Likewise, the user can then extract and manipulate the
5812: `PC` contexts as well.
5814: 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.
5816: .seealso: [](ch_snes), `SNES`, `KSP`, `PC`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
5817: @*/
5818: PetscErrorCode SNESGetKSP(SNES snes, KSP *ksp)
5819: {
5820: PetscFunctionBegin;
5822: PetscAssertPointer(ksp, 2);
5824: if (!snes->ksp) {
5825: PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes), &snes->ksp));
5826: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp, (PetscObject)snes, 1));
5828: snes->ksp->presolve_ew = KSPPreSolve_SNESEW;
5829: snes->ksp->prectx_ew = snes;
5830: snes->ksp->postsolve_ew = KSPPostSolve_SNESEW;
5831: snes->ksp->postctx_ew = snes;
5833: PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
5834: PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp, ((PetscObject)snes)->options));
5835: }
5836: *ksp = snes->ksp;
5837: PetscFunctionReturn(PETSC_SUCCESS);
5838: }
5840: #include <petsc/private/dmimpl.h>
5841: /*@
5842: SNESSetDM - Sets the `DM` that may be used by some `SNES` nonlinear solvers or their underlying preconditioners
5844: Logically Collective
5846: Input Parameters:
5847: + snes - the nonlinear solver context
5848: - dm - the `DM`, cannot be `NULL`
5850: Level: intermediate
5852: Note:
5853: A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
5854: even when not using interfaces like `DMSNESSetFunction()`. Use `DMClone()` to get a distinct `DM` when solving different
5855: problems using the same function space.
5857: .seealso: [](ch_snes), `DM`, `SNES`, `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()`
5858: @*/
5859: PetscErrorCode SNESSetDM(SNES snes, DM dm)
5860: {
5861: KSP ksp;
5862: DMSNES sdm;
5863: DM odm;
5865: PetscFunctionBegin;
5868: PetscCall(PetscObjectReference((PetscObject)dm));
5869: odm = snes->dm;
5870: if (snes->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */
5871: if (snes->dm->dmsnes && !dm->dmsnes) {
5872: PetscCall(DMCopyDMSNES(snes->dm, dm));
5873: PetscCall(DMGetDMSNES(snes->dm, &sdm));
5874: if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5875: }
5876: PetscCall(DMCoarsenHookRemove(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
5877: PetscCall(DMDestroy(&snes->dm));
5878: }
5879: snes->dm = dm;
5880: snes->dmAuto = PETSC_FALSE;
5882: PetscCall(SNESGetKSP(snes, &ksp));
5883: PetscCall(KSPSetDM(ksp, dm));
5884: PetscCall(KSPSetDMActive(ksp, KSP_DMACTIVE_ALL, PETSC_FALSE));
5885: /* Propagate DM to NPC if npc does not have one yet or
5886: if it has the same DM SNES had before (like for gridsequencing) */
5887: if (snes->npc && (!snes->npc->dm || snes->npc->dm == odm)) PetscCall(SNESSetDM(snes->npc, snes->dm));
5888: PetscFunctionReturn(PETSC_SUCCESS);
5889: }
5891: /*@
5892: SNESGetDM - Gets the `DM` that may be used by some `SNES` nonlinear solvers/preconditioners
5894: Not Collective but `dm` obtained is parallel on `snes`
5896: Input Parameter:
5897: . snes - the `SNES` context
5899: Output Parameter:
5900: . dm - the `DM`
5902: Level: intermediate
5904: .seealso: [](ch_snes), `DM`, `SNES`, `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()`
5905: @*/
5906: PetscErrorCode SNESGetDM(SNES snes, DM *dm)
5907: {
5908: PetscFunctionBegin;
5910: if (!snes->dm) {
5911: PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes), &snes->dm));
5912: snes->dmAuto = PETSC_TRUE;
5913: }
5914: *dm = snes->dm;
5915: PetscFunctionReturn(PETSC_SUCCESS);
5916: }
5918: /*@
5919: SNESSetNPC - Sets the nonlinear preconditioner to be used.
5921: Collective
5923: Input Parameters:
5924: + snes - iterative context obtained from `SNESCreate()`
5925: - npc - the `SNES` nonlinear preconditioner object
5927: Level: developer
5929: Notes:
5930: This is rarely used, rather use `SNESGetNPC()` to retrieve the preconditioner and configure it using the API.
5932: Only some `SNESType` can use a nonlinear preconditioner
5934: .seealso: [](ch_snes), `SNES`, `SNESNGS`, `SNESFAS`, `SNESGetNPC()`, `SNESHasNPC()`
5935: @*/
5936: PetscErrorCode SNESSetNPC(SNES snes, SNES npc)
5937: {
5938: PetscFunctionBegin;
5941: PetscCheckSameComm(snes, 1, npc, 2);
5942: PetscCall(PetscObjectReference((PetscObject)npc));
5943: PetscCall(SNESDestroy(&snes->npc));
5944: snes->npc = npc;
5945: PetscFunctionReturn(PETSC_SUCCESS);
5946: }
5948: /*@
5949: SNESGetNPC - Gets a nonlinear preconditioning solver SNES` to be used to precondition the original nonlinear solver.
5951: Collective the first time it is called if the `SNES` has no NPC set.
5953: Input Parameter:
5954: . snes - iterative context obtained from `SNESCreate()`
5956: Output Parameter:
5957: . npc - the `SNES` preconditioner context
5959: Options Database Key:
5960: . -npc_snes_type type - set the type of the `SNES` to use as the nonlinear preconditioner
5962: Level: advanced
5964: Notes:
5965: If a `SNES` was previously set with `SNESSetNPC()` then that object is returned, otherwise a new `SNES` object is created that will
5966: be used as the nonlinear preconditioner for the current `SNES` if no nonlinear preconditioner is present.
5968: The (preconditioner) `SNES` returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5969: `SNES`. These may be overwritten if needed by calling `SNESSetDM()` on the nonlinear preconditioner followed by `SNESSetFunction()`
5970: and `SNESSetJacobian()`.
5972: The default preconditioner uses the options database prefixes `-npc_snes`, `-npc_ksp`, etc., to control the configuration.
5974: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()`
5975: @*/
5976: PetscErrorCode SNESGetNPC(SNES snes, SNES *npc)
5977: {
5978: const char *optionsprefix;
5980: PetscFunctionBegin;
5982: PetscAssertPointer(npc, 2);
5983: if (!snes->npc) {
5984: PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes), &snes->npc));
5985: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc, (PetscObject)snes, 1));
5986: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5987: PetscCall(SNESSetOptionsPrefix(snes->npc, optionsprefix));
5988: PetscCall(SNESAppendOptionsPrefix(snes->npc, "npc_"));
5989: PetscCall(SNESSetCountersReset(snes->npc, PETSC_FALSE));
5990: PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_DEFAULT));
5992: /* default to 1 iteration */
5993: PetscCall(SNESSetTolerances(snes->npc, 0.0, 0.0, 0.0, 1, snes->npc->max_funcs));
5994: }
5995: *npc = snes->npc;
5996: PetscFunctionReturn(PETSC_SUCCESS);
5997: }
5999: /*@
6000: SNESHasNPC - Returns whether a nonlinear preconditioner is associated with the given `SNES`
6002: Not Collective
6004: Input Parameter:
6005: . snes - iterative context obtained from `SNESCreate()`
6007: Output Parameter:
6008: . has_npc - whether the `SNES` has a nonlinear preconditioner or not
6010: Level: developer
6012: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESGetNPC()`
6013: @*/
6014: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
6015: {
6016: PetscFunctionBegin;
6018: PetscAssertPointer(has_npc, 2);
6019: *has_npc = snes->npc ? PETSC_TRUE : PETSC_FALSE;
6020: PetscFunctionReturn(PETSC_SUCCESS);
6021: }
6023: /*@
6024: SNESSetNPCSide - Sets the nonlinear preconditioning side used by the nonlinear preconditioner inside `SNES`.
6026: Logically Collective
6028: Input Parameter:
6029: . snes - iterative context obtained from `SNESCreate()`
6031: Output Parameter:
6032: . side - the preconditioning side, where side is one of
6033: .vb
6034: PC_LEFT - left preconditioning
6035: PC_RIGHT - right preconditioning (default for most nonlinear solvers)
6036: .ve
6038: Options Database Key:
6039: . -snes_npc_side (right|left) - nonlinear preconditioner side
6041: Level: intermediate
6043: Note:
6044: `SNESNRICHARDSON` and `SNESNCG` only support left preconditioning.
6046: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESNRICHARDSON`, `SNESNCG`, `SNESType`, `SNESGetNPCSide()`, `KSPSetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
6047: @*/
6048: PetscErrorCode SNESSetNPCSide(SNES snes, PCSide side)
6049: {
6050: PetscFunctionBegin;
6053: if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
6054: PetscCheck((side == PC_LEFT) || (side == PC_RIGHT), PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Only PC_LEFT and PC_RIGHT are supported");
6055: snes->npcside = side;
6056: PetscFunctionReturn(PETSC_SUCCESS);
6057: }
6059: /*@
6060: SNESGetNPCSide - Gets the preconditioning side used by the nonlinear preconditioner inside `SNES`.
6062: Not Collective
6064: Input Parameter:
6065: . snes - iterative context obtained from `SNESCreate()`
6067: Output Parameter:
6068: . side - the preconditioning side, where side is one of
6069: .vb
6070: `PC_LEFT` - left preconditioning
6071: `PC_RIGHT` - right preconditioning (default for most nonlinear solvers)
6072: .ve
6074: Level: intermediate
6076: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESSetNPCSide()`, `KSPGetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
6077: @*/
6078: PetscErrorCode SNESGetNPCSide(SNES snes, PCSide *side)
6079: {
6080: PetscFunctionBegin;
6082: PetscAssertPointer(side, 2);
6083: *side = snes->npcside;
6084: PetscFunctionReturn(PETSC_SUCCESS);
6085: }
6087: /*@
6088: SNESSetLineSearch - Sets the `SNESLineSearch` to be used for a given `SNES`
6090: Collective
6092: Input Parameters:
6093: + snes - iterative context obtained from `SNESCreate()`
6094: - linesearch - the linesearch object
6096: Level: developer
6098: Note:
6099: This is almost never used, rather one uses `SNESGetLineSearch()` to retrieve the line search and set options on it
6100: to configure it using the API).
6102: .seealso: [](ch_snes), `SNES`, `SNESLineSearch`, `SNESGetLineSearch()`
6103: @*/
6104: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
6105: {
6106: PetscFunctionBegin;
6109: PetscCheckSameComm(snes, 1, linesearch, 2);
6110: PetscCall(PetscObjectReference((PetscObject)linesearch));
6111: PetscCall(SNESLineSearchDestroy(&snes->linesearch));
6113: snes->linesearch = linesearch;
6114: PetscFunctionReturn(PETSC_SUCCESS);
6115: }