Actual source code: snes.c
1: #include <petsc/private/snesimpl.h>
2: #include <petsc/private/linesearchimpl.h>
3: #include <petscdmshell.h>
4: #include <petscdraw.h>
5: #include <petscds.h>
6: #include <petscdmadaptor.h>
7: #include <petscconvest.h>
9: PetscBool SNESRegisterAllCalled = PETSC_FALSE;
10: PetscFunctionList SNESList = NULL;
12: /* Logging support */
13: PetscClassId SNES_CLASSID, DMSNES_CLASSID;
14: PetscLogEvent SNES_Solve, SNES_SetUp, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NewtonALEval, SNES_NPCSolve, SNES_ObjectiveEval;
16: /*@
17: SNESSetErrorIfNotConverged - Causes `SNESSolve()` to generate an error immediately if the solver has not converged.
19: Logically Collective
21: Input Parameters:
22: + snes - iterative context obtained from `SNESCreate()`
23: - flg - `PETSC_TRUE` indicates you want the error generated
25: Options Database Key:
26: . -snes_error_if_not_converged (true|false) - cause an immediate error condition and stop the program if the solver does not converge
28: Level: intermediate
30: Note:
31: Normally PETSc continues if a solver fails to converge, you can call `SNESGetConvergedReason()` after a `SNESSolve()`
32: to determine if it has converged. Otherwise the solution may be inaccurate or wrong
34: .seealso: [](ch_snes), `SNES`, `SNESGetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()`
35: @*/
36: PetscErrorCode SNESSetErrorIfNotConverged(SNES snes, PetscBool flg)
37: {
38: PetscFunctionBegin;
41: snes->errorifnotconverged = flg;
42: PetscFunctionReturn(PETSC_SUCCESS);
43: }
45: /*@
46: SNESGetErrorIfNotConverged - Indicates if `SNESSolve()` will generate an error if the solver does not converge?
48: Not Collective
50: Input Parameter:
51: . snes - iterative context obtained from `SNESCreate()`
53: Output Parameter:
54: . flag - `PETSC_TRUE` if it will generate an error, else `PETSC_FALSE`
56: Level: intermediate
58: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()`
59: @*/
60: PetscErrorCode SNESGetErrorIfNotConverged(SNES snes, PetscBool *flag)
61: {
62: PetscFunctionBegin;
64: PetscAssertPointer(flag, 2);
65: *flag = snes->errorifnotconverged;
66: PetscFunctionReturn(PETSC_SUCCESS);
67: }
69: /*@
70: SNESSetAlwaysComputesFinalResidual - tells the `SNES` to always compute the residual (nonlinear function value) at the final solution
72: Logically Collective
74: Input Parameters:
75: + snes - the shell `SNES`
76: - flg - `PETSC_TRUE` to always compute the residual
78: Level: advanced
80: Note:
81: Some solvers (such as smoothers in a `SNESFAS`) do not need the residual computed at the final solution so skip computing it
82: to save time.
84: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSolve()`, `SNESGetAlwaysComputesFinalResidual()`
85: @*/
86: PetscErrorCode SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
87: {
88: PetscFunctionBegin;
90: snes->alwayscomputesfinalresidual = flg;
91: PetscFunctionReturn(PETSC_SUCCESS);
92: }
94: /*@
95: SNESGetAlwaysComputesFinalResidual - checks if the `SNES` always computes the residual at the final solution
97: Logically Collective
99: Input Parameter:
100: . snes - the `SNES` context
102: Output Parameter:
103: . flg - `PETSC_TRUE` if the residual is computed
105: Level: advanced
107: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSolve()`, `SNESSetAlwaysComputesFinalResidual()`
108: @*/
109: PetscErrorCode SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
110: {
111: PetscFunctionBegin;
113: *flg = snes->alwayscomputesfinalresidual;
114: PetscFunctionReturn(PETSC_SUCCESS);
115: }
117: /*@
118: SNESSetFunctionDomainError - tells `SNES` that the input vector, a proposed new solution, to your function you provided to `SNESSetFunction()` is not
119: in the function's domain. For example, a step with negative pressure.
121: Not Collective
123: Input Parameter:
124: . snes - the `SNES` context
126: Level: advanced
128: Notes:
129: This does not need to be called by all processes in the `SNES` MPI communicator.
131: A few solvers will try to cut the step size to avoid the domain error but for other solvers `SNESSolve()` stops iterating and
132: returns with a `SNESConvergedReason` of `SNES_DIVERGED_FUNCTION_DOMAIN`
134: You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
135: `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
137: You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).
139: You can call `SNESSetJacobianDomainError()` during a Jacobian computation to indicate the proposed solution is not in the domain.
141: Developer Note:
142: This value is used by `SNESCheckFunctionDomainError()` to determine if the `SNESConvergedReason` is set to `SNES_DIVERGED_FUNCTION_DOMAIN`
144: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`,
145: `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`,
146: `SNES_DIVERGED_FUNCTION_DOMAIN`, `SNESSetObjectiveDomainError()`, `SNES_DIVERGED_OBJECTIVE_DOMAIN`
147: @*/
148: PetscErrorCode SNESSetFunctionDomainError(SNES snes)
149: {
150: PetscFunctionBegin;
152: snes->functiondomainerror = PETSC_TRUE;
153: PetscFunctionReturn(PETSC_SUCCESS);
154: }
156: /*@
157: SNESSetObjectiveDomainError - tells `SNES` that the input vector, a proposed new solution, to your function you provided to `SNESSetObjective()` is not
158: in the function's domain. For example, a step with negative pressure.
160: Not Collective
162: Input Parameter:
163: . snes - the `SNES` context
165: Level: advanced
167: Notes:
168: This does not need to be called by all processes in the `SNES` MPI communicator.
170: A few solvers will try to cut the step size to avoid the domain error but for other solvers `SNESSolve()` stops iterating and
171: returns with a `SNESConvergedReason` of `SNES_DIVERGED_OBJECTIVE_DOMAIN`
173: You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
174: `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
176: You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).
178: You can call `SNESSetJacobianDomainError()` during a Jacobian computation to indicate the proposed solution is not in the domain.
180: Developer Note:
181: This value is used by `SNESCheckObjectiveDomainError()` to determine if the `SNESConvergedReason` is set to `SNES_DIVERGED_OBJECTIVE_DOMAIN`
183: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`,
184: `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`,
185: `SNES_DIVERGED_OBJECTIVE_DOMAIN`, `SNESSetFunctionDomainError()`, `SNES_DIVERGED_FUNCTION_DOMAIN`
186: @*/
187: PetscErrorCode SNESSetObjectiveDomainError(SNES snes)
188: {
189: PetscFunctionBegin;
191: snes->objectivedomainerror = PETSC_TRUE;
192: PetscFunctionReturn(PETSC_SUCCESS);
193: }
195: /*@
196: SNESSetJacobianDomainError - tells `SNES` that the function you provided to `SNESSetJacobian()` at the proposed step. For example there is a negative element transformation.
198: Logically Collective
200: Input Parameter:
201: . snes - the `SNES` context
203: Level: advanced
205: Notes:
206: If this is called the `SNESSolve()` stops iterating and returns with a `SNESConvergedReason` of `SNES_DIVERGED_JACOBIAN_DOMAIN`
208: You should always call `SNESGetConvergedReason()` after each `SNESSolve()` and verify if the iteration converged (positive result) or diverged (negative result).
210: You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
211: `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
213: .seealso: [](ch_snes), `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESVISetVariableBounds()`,
214: `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESConvergedReason`, `SNESGetConvergedReason()`
215: @*/
216: PetscErrorCode SNESSetJacobianDomainError(SNES snes)
217: {
218: PetscFunctionBegin;
220: PetscCheck(!snes->errorifnotconverged, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "User code indicates computeJacobian does not make sense");
221: snes->jacobiandomainerror = PETSC_TRUE;
222: PetscFunctionReturn(PETSC_SUCCESS);
223: }
225: /*@
226: SNESSetCheckJacobianDomainError - tells `SNESSolve()` whether to check if the user called `SNESSetJacobianDomainError()` to indicate a Jacobian domain error after
227: each Jacobian evaluation.
229: Logically Collective
231: Input Parameters:
232: + snes - the `SNES` context
233: - flg - indicates if or not to check Jacobian domain error after each Jacobian evaluation
235: Level: advanced
237: Notes:
238: By default, it checks for the Jacobian domain error in the debug mode, and does not check it in the optimized mode.
240: Checks require one extra parallel synchronization for each Jacobian evaluation
242: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESGetCheckJacobianDomainError()`
243: @*/
244: PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg)
245: {
246: PetscFunctionBegin;
248: snes->checkjacdomainerror = flg;
249: PetscFunctionReturn(PETSC_SUCCESS);
250: }
252: /*@
253: SNESGetCheckJacobianDomainError - Get an indicator whether or not `SNES` is checking Jacobian domain errors after each Jacobian evaluation.
255: Logically Collective
257: Input Parameter:
258: . snes - the `SNES` context
260: Output Parameter:
261: . flg - `PETSC_FALSE` indicates that it is not checking Jacobian domain errors after each Jacobian evaluation
263: Level: advanced
265: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSetFunction()`, `SNESFunctionFn`, `SNESSetFunctionDomainError()`, `SNESSetCheckJacobianDomainError()`
266: @*/
267: PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
268: {
269: PetscFunctionBegin;
271: PetscAssertPointer(flg, 2);
272: *flg = snes->checkjacdomainerror;
273: PetscFunctionReturn(PETSC_SUCCESS);
274: }
276: /*@
277: SNESLoad - Loads a `SNES` that has been stored in `PETSCVIEWERBINARY` with `SNESView()`.
279: Collective
281: Input Parameters:
282: + snes - the newly loaded `SNES`, this needs to have been created with `SNESCreate()` or
283: some related function before a call to `SNESLoad()`.
284: - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
286: Level: intermediate
288: Note:
289: The `SNESType` is determined by the data in the file, any type set into the `SNES` before this call is ignored.
291: .seealso: [](ch_snes), `SNES`, `PetscViewer`, `SNESCreate()`, `SNESType`, `PetscViewerBinaryOpen()`, `SNESView()`, `MatLoad()`, `VecLoad()`
292: @*/
293: PetscErrorCode SNESLoad(SNES snes, PetscViewer viewer)
294: {
295: PetscBool isbinary;
296: PetscInt classid;
297: char type[256];
298: KSP ksp;
299: DM dm;
300: DMSNES dmsnes;
302: PetscFunctionBegin;
305: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
306: PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
308: PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
309: PetscCheck(classid == SNES_FILE_CLASSID, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Not SNES next in file");
310: PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
311: PetscCall(SNESSetType(snes, type));
312: PetscTryTypeMethod(snes, load, viewer);
313: PetscCall(SNESGetDM(snes, &dm));
314: PetscCall(DMGetDMSNES(dm, &dmsnes));
315: PetscCall(DMSNESLoad(dmsnes, viewer));
316: PetscCall(SNESGetKSP(snes, &ksp));
317: PetscCall(KSPLoad(ksp, viewer));
318: PetscFunctionReturn(PETSC_SUCCESS);
319: }
321: #include <petscdraw.h>
322: #if defined(PETSC_HAVE_SAWS)
323: #include <petscviewersaws.h>
324: #endif
326: /*@
327: SNESViewFromOptions - View a `SNES` based on values in the options database
329: Collective
331: Input Parameters:
332: + A - the `SNES` context
333: . obj - Optional object that provides the options prefix for the checks
334: - name - command line option
336: Level: intermediate
338: .seealso: [](ch_snes), `SNES`, `SNESView`, `PetscObjectViewFromOptions()`, `SNESCreate()`
339: @*/
340: PetscErrorCode SNESViewFromOptions(SNES A, PetscObject obj, const char name[])
341: {
342: PetscFunctionBegin;
344: PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
345: PetscFunctionReturn(PETSC_SUCCESS);
346: }
348: PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES, Vec, Mat, Mat, void *);
350: /*@
351: SNESView - Prints or visualizes the `SNES` data structure.
353: Collective
355: Input Parameters:
356: + snes - the `SNES` context
357: - viewer - the `PetscViewer`
359: Options Database Key:
360: . -snes_view - Calls `SNESView()` at end of `SNESSolve()`
362: Level: beginner
364: Notes:
365: The available visualization contexts include
366: + `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
367: - `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
368: output where only the first processor opens
369: the file. All other processors send their
370: data to the first processor to print.
372: The available formats include
373: + `PETSC_VIEWER_DEFAULT` - standard output (default)
374: - `PETSC_VIEWER_ASCII_INFO_DETAIL` - more verbose output for `SNESNASM`
376: The user can open an alternative visualization context with
377: `PetscViewerASCIIOpen()` - output to a specified file.
379: In the debugger you can do "call `SNESView`(snes,0)" to display the `SNES` solver. (The same holds for any PETSc object viewer).
381: .seealso: [](ch_snes), `SNES`, `SNESLoad()`, `SNESCreate()`, `PetscViewerASCIIOpen()`
382: @*/
383: PetscErrorCode SNESView(SNES snes, PetscViewer viewer)
384: {
385: SNESKSPEW *kctx;
386: KSP ksp;
387: SNESLineSearch linesearch;
388: PetscBool isascii, isstring, isbinary, isdraw;
389: DMSNES dmsnes;
390: #if defined(PETSC_HAVE_SAWS)
391: PetscBool issaws;
392: #endif
394: PetscFunctionBegin;
396: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &viewer));
398: PetscCheckSameComm(snes, 1, viewer, 2);
400: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
401: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
402: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
403: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
404: #if defined(PETSC_HAVE_SAWS)
405: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
406: #endif
407: if (isascii) {
408: SNESNormSchedule normschedule;
409: DM dm;
410: SNESJacobianFn *cJ;
411: void *ctx;
412: const char *pre = "";
414: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)snes, viewer));
415: if (!snes->setupcalled) PetscCall(PetscViewerASCIIPrintf(viewer, " SNES has not been set up so information may be incomplete\n"));
416: if (snes->ops->view) {
417: PetscCall(PetscViewerASCIIPushTab(viewer));
418: PetscUseTypeMethod(snes, view, viewer);
419: PetscCall(PetscViewerASCIIPopTab(viewer));
420: }
421: if (snes->max_funcs == PETSC_UNLIMITED) {
422: PetscCall(PetscViewerASCIIPrintf(viewer, " maximum iterations=%" PetscInt_FMT ", maximum function evaluations=unlimited\n", snes->max_its));
423: } else {
424: PetscCall(PetscViewerASCIIPrintf(viewer, " maximum iterations=%" PetscInt_FMT ", maximum function evaluations=%" PetscInt_FMT "\n", snes->max_its, snes->max_funcs));
425: }
426: PetscCall(PetscViewerASCIIPrintf(viewer, " tolerances: relative=%g, absolute=%g, solution=%g\n", (double)snes->rtol, (double)snes->abstol, (double)snes->stol));
427: if (snes->usesksp) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of linear solver iterations=%" PetscInt_FMT "\n", snes->linear_its));
428: PetscCall(PetscViewerASCIIPrintf(viewer, " total number of function evaluations=%" PetscInt_FMT "\n", snes->nfuncs));
429: PetscCall(SNESGetNormSchedule(snes, &normschedule));
430: if (normschedule > 0) PetscCall(PetscViewerASCIIPrintf(viewer, " norm schedule %s\n", SNESNormSchedules[normschedule]));
431: if (snes->gridsequence) PetscCall(PetscViewerASCIIPrintf(viewer, " total number of grid sequence refinements=%" PetscInt_FMT "\n", snes->gridsequence));
432: if (snes->ksp_ewconv) {
433: kctx = (SNESKSPEW *)snes->kspconvctx;
434: if (kctx) {
435: PetscCall(PetscViewerASCIIPrintf(viewer, " Eisenstat-Walker computation of KSP relative tolerance (version %" PetscInt_FMT ")\n", kctx->version));
436: PetscCall(PetscViewerASCIIPrintf(viewer, " rtol_0=%g, rtol_max=%g, threshold=%g\n", (double)kctx->rtol_0, (double)kctx->rtol_max, (double)kctx->threshold));
437: PetscCall(PetscViewerASCIIPrintf(viewer, " gamma=%g, alpha=%g, alpha2=%g\n", (double)kctx->gamma, (double)kctx->alpha, (double)kctx->alpha2));
438: }
439: }
440: if (snes->lagpreconditioner == -1) {
441: PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioned is never rebuilt\n"));
442: } else if (snes->lagpreconditioner > 1) {
443: PetscCall(PetscViewerASCIIPrintf(viewer, " Preconditioned is rebuilt every %" PetscInt_FMT " new Jacobians\n", snes->lagpreconditioner));
444: }
445: if (snes->lagjacobian == -1) {
446: PetscCall(PetscViewerASCIIPrintf(viewer, " Jacobian is never rebuilt\n"));
447: } else if (snes->lagjacobian > 1) {
448: PetscCall(PetscViewerASCIIPrintf(viewer, " Jacobian is rebuilt every %" PetscInt_FMT " SNES iterations\n", snes->lagjacobian));
449: }
450: PetscCall(SNESGetDM(snes, &dm));
451: PetscCall(DMSNESGetJacobian(dm, &cJ, &ctx));
452: if (snes->mf_operator) {
453: PetscCall(PetscViewerASCIIPrintf(viewer, " Jacobian is applied matrix-free with differencing\n"));
454: pre = "Preconditioning ";
455: }
456: if (cJ == SNESComputeJacobianDefault) {
457: PetscCall(PetscViewerASCIIPrintf(viewer, " %sJacobian is built using finite differences one column at a time\n", pre));
458: } else if (cJ == SNESComputeJacobianDefaultColor) {
459: PetscCall(PetscViewerASCIIPrintf(viewer, " %sJacobian is built using finite differences with coloring\n", pre));
460: /* it slightly breaks data encapsulation for access the DMDA information directly */
461: } else if (cJ == SNESComputeJacobian_DMDA) {
462: MatFDColoring fdcoloring;
463: PetscCall(PetscObjectQuery((PetscObject)dm, "DMDASNES_FDCOLORING", (PetscObject *)&fdcoloring));
464: if (fdcoloring) {
465: PetscCall(PetscViewerASCIIPrintf(viewer, " %sJacobian is built using colored finite differences on a DMDA\n", pre));
466: } else {
467: PetscCall(PetscViewerASCIIPrintf(viewer, " %sJacobian is built using a DMDA local Jacobian\n", pre));
468: }
469: } else if (snes->mf && !snes->mf_operator) {
470: PetscCall(PetscViewerASCIIPrintf(viewer, " Jacobian is applied matrix-free with differencing, no explicit Jacobian\n"));
471: }
472: } else if (isstring) {
473: const char *type;
474: PetscCall(SNESGetType(snes, &type));
475: PetscCall(PetscViewerStringSPrintf(viewer, " SNESType: %-7.7s", type));
476: PetscTryTypeMethod(snes, view, viewer);
477: } else if (isbinary) {
478: PetscInt classid = SNES_FILE_CLASSID;
479: MPI_Comm comm;
480: PetscMPIInt rank;
481: char type[256];
483: PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
484: PetscCallMPI(MPI_Comm_rank(comm, &rank));
485: if (rank == 0) {
486: PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
487: PetscCall(PetscStrncpy(type, ((PetscObject)snes)->type_name, sizeof(type)));
488: PetscCall(PetscViewerBinaryWrite(viewer, type, sizeof(type), PETSC_CHAR));
489: }
490: PetscTryTypeMethod(snes, view, viewer);
491: } else if (isdraw) {
492: PetscDraw draw;
493: char str[36];
494: PetscReal x, y, bottom, h;
496: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
497: PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
498: PetscCall(PetscStrncpy(str, "SNES: ", sizeof(str)));
499: PetscCall(PetscStrlcat(str, ((PetscObject)snes)->type_name, sizeof(str)));
500: PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLUE, PETSC_DRAW_BLACK, str, NULL, &h));
501: bottom = y - h;
502: PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
503: PetscTryTypeMethod(snes, view, viewer);
504: #if defined(PETSC_HAVE_SAWS)
505: } else if (issaws) {
506: PetscMPIInt rank;
507: const char *name;
509: PetscCall(PetscObjectGetName((PetscObject)snes, &name));
510: PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
511: if (!((PetscObject)snes)->amsmem && rank == 0) {
512: char dir[1024];
514: PetscCall(PetscObjectViewSAWs((PetscObject)snes, viewer));
515: PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/its", name));
516: PetscCallSAWs(SAWs_Register, (dir, &snes->iter, 1, SAWs_READ, SAWs_INT));
517: if (!snes->conv_hist) PetscCall(SNESSetConvergenceHistory(snes, NULL, NULL, PETSC_DECIDE, PETSC_TRUE));
518: PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/conv_hist", name));
519: PetscCallSAWs(SAWs_Register, (dir, snes->conv_hist, 10, SAWs_READ, SAWs_DOUBLE));
520: }
521: #endif
522: }
523: if (snes->linesearch) {
524: PetscCall(SNESGetLineSearch(snes, &linesearch));
525: PetscCall(PetscViewerASCIIPushTab(viewer));
526: PetscCall(SNESLineSearchView(linesearch, viewer));
527: PetscCall(PetscViewerASCIIPopTab(viewer));
528: }
529: if (snes->npc && snes->usesnpc) {
530: PetscCall(PetscViewerASCIIPushTab(viewer));
531: PetscCall(SNESView(snes->npc, viewer));
532: PetscCall(PetscViewerASCIIPopTab(viewer));
533: }
534: PetscCall(PetscViewerASCIIPushTab(viewer));
535: PetscCall(DMGetDMSNES(snes->dm, &dmsnes));
536: PetscCall(DMSNESView(dmsnes, viewer));
537: PetscCall(PetscViewerASCIIPopTab(viewer));
538: if (snes->usesksp) {
539: PetscCall(SNESGetKSP(snes, &ksp));
540: PetscCall(PetscViewerASCIIPushTab(viewer));
541: PetscCall(KSPView(ksp, viewer));
542: PetscCall(PetscViewerASCIIPopTab(viewer));
543: }
544: if (isdraw) {
545: PetscDraw draw;
546: PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
547: PetscCall(PetscDrawPopCurrentPoint(draw));
548: }
549: PetscFunctionReturn(PETSC_SUCCESS);
550: }
552: /*
553: We retain a list of functions that also take SNES command
554: line options. These are called at the end SNESSetFromOptions()
555: */
556: #define MAXSETFROMOPTIONS 5
557: static PetscInt numberofsetfromoptions;
558: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);
560: /*@C
561: SNESAddOptionsChecker - Adds an additional function to check for `SNES` options.
563: Not Collective
565: Input Parameter:
566: . snescheck - function that checks for options
568: Calling sequence of `snescheck`:
569: . snes - the `SNES` object for which it is checking options
571: Level: developer
573: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`
574: @*/
575: PetscErrorCode SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES snes))
576: {
577: PetscFunctionBegin;
578: PetscCheck(numberofsetfromoptions < MAXSETFROMOPTIONS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %d allowed", MAXSETFROMOPTIONS);
579: othersetfromoptions[numberofsetfromoptions++] = snescheck;
580: PetscFunctionReturn(PETSC_SUCCESS);
581: }
583: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
584: {
585: Mat J;
586: MatNullSpace nullsp;
588: PetscFunctionBegin;
591: if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
592: Mat A = snes->jacobian, B = snes->jacobian_pre;
593: PetscCall(MatCreateVecs(A ? A : B, NULL, &snes->vec_func));
594: }
596: PetscCheck(version == 1 || version == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");
597: if (version == 1) {
598: PetscCall(MatCreateSNESMF(snes, &J));
599: PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
600: PetscCall(MatSetFromOptions(J));
601: /* TODO: the version 2 code should be merged into the MatCreateSNESMF() and MatCreateMFFD() infrastructure and then removed */
602: } else /* if (version == 2) */ {
603: PetscCheck(snes->vec_func, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "SNESSetFunction() must be called first");
604: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
605: PetscCall(MatCreateSNESMFMore(snes, snes->vec_func, &J));
606: #else
607: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
608: #endif
609: }
611: /* attach any user provided null space that was on Amat to the newly created matrix-free matrix */
612: if (snes->jacobian) {
613: PetscCall(MatGetNullSpace(snes->jacobian, &nullsp));
614: if (nullsp) PetscCall(MatSetNullSpace(J, nullsp));
615: }
617: PetscCall(PetscInfo(snes, "Setting default matrix-free operator routines (version %" PetscInt_FMT ")\n", version));
618: if (hasOperator) {
619: /* This version replaces the user provided Jacobian matrix with a
620: matrix-free version but still employs the user-provided matrix used for computing the preconditioner. */
621: PetscCall(SNESSetJacobian(snes, J, NULL, NULL, NULL));
622: } else {
623: /* This version replaces both the user-provided Jacobian and the user-
624: provided preconditioner Jacobian with the default matrix-free version. */
625: if (snes->npcside == PC_LEFT && snes->npc) {
626: if (!snes->jacobian) PetscCall(SNESSetJacobian(snes, J, NULL, NULL, NULL));
627: } else {
628: KSP ksp;
629: PC pc;
630: PetscBool match;
632: PetscCall(SNESSetJacobian(snes, J, J, MatMFFDComputeJacobian, NULL));
633: /* Force no preconditioner */
634: PetscCall(SNESGetKSP(snes, &ksp));
635: PetscCall(KSPGetPC(ksp, &pc));
636: PetscCall(PetscObjectTypeCompareAny((PetscObject)pc, &match, PCSHELL, PCH2OPUS, ""));
637: if (!match) {
638: PetscCall(PetscInfo(snes, "Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n"));
639: PetscCall(PCSetType(pc, PCNONE));
640: }
641: }
642: }
643: PetscCall(MatDestroy(&J));
644: PetscFunctionReturn(PETSC_SUCCESS);
645: }
647: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine, Mat Restrict, Vec Rscale, Mat Inject, DM dmcoarse, PetscCtx ctx)
648: {
649: SNES snes = (SNES)ctx;
650: Vec Xfine, Xfine_named = NULL, Xcoarse;
652: PetscFunctionBegin;
653: if (PetscLogPrintInfo) {
654: PetscInt finelevel, coarselevel, fineclevel, coarseclevel;
655: PetscCall(DMGetRefineLevel(dmfine, &finelevel));
656: PetscCall(DMGetCoarsenLevel(dmfine, &fineclevel));
657: PetscCall(DMGetRefineLevel(dmcoarse, &coarselevel));
658: PetscCall(DMGetCoarsenLevel(dmcoarse, &coarseclevel));
659: PetscCall(PetscInfo(dmfine, "Restricting SNES solution vector from level %" PetscInt_FMT "-%" PetscInt_FMT " to level %" PetscInt_FMT "-%" PetscInt_FMT "\n", finelevel, fineclevel, coarselevel, coarseclevel));
660: }
661: if (dmfine == snes->dm) Xfine = snes->vec_sol;
662: else {
663: PetscCall(DMGetNamedGlobalVector(dmfine, "SNESVecSol", &Xfine_named));
664: Xfine = Xfine_named;
665: }
666: PetscCall(DMGetNamedGlobalVector(dmcoarse, "SNESVecSol", &Xcoarse));
667: if (Inject) {
668: PetscCall(MatRestrict(Inject, Xfine, Xcoarse));
669: } else {
670: PetscCall(MatRestrict(Restrict, Xfine, Xcoarse));
671: PetscCall(VecPointwiseMult(Xcoarse, Xcoarse, Rscale));
672: }
673: PetscCall(DMRestoreNamedGlobalVector(dmcoarse, "SNESVecSol", &Xcoarse));
674: if (Xfine_named) PetscCall(DMRestoreNamedGlobalVector(dmfine, "SNESVecSol", &Xfine_named));
675: PetscFunctionReturn(PETSC_SUCCESS);
676: }
678: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm, DM dmc, PetscCtx ctx)
679: {
680: PetscFunctionBegin;
681: PetscCall(DMCoarsenHookAdd(dmc, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, ctx));
682: PetscFunctionReturn(PETSC_SUCCESS);
683: }
685: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
686: * safely call SNESGetDM() in their residual evaluation routine. */
687: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp, Mat A, Mat B, PetscCtx ctx)
688: {
689: SNES snes = (SNES)ctx;
690: DMSNES sdm;
691: Vec X, Xnamed = NULL;
692: DM dmsave;
693: void *ctxsave;
694: SNESJacobianFn *jac = NULL;
696: PetscFunctionBegin;
697: dmsave = snes->dm;
698: PetscCall(KSPGetDM(ksp, &snes->dm));
699: if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
700: else {
701: PetscBool has;
703: /* We are on a coarser level, this vec was initialized using a DM restrict hook */
704: PetscCall(DMHasNamedGlobalVector(snes->dm, "SNESVecSol", &has));
705: PetscCheck(has, PetscObjectComm((PetscObject)snes->dm), PETSC_ERR_PLIB, "Missing SNESVecSol");
706: PetscCall(DMGetNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
707: X = Xnamed;
708: PetscCall(SNESGetJacobian(snes, NULL, NULL, &jac, &ctxsave));
709: /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
710: if (jac == SNESComputeJacobianDefaultColor) PetscCall(SNESSetJacobian(snes, NULL, NULL, SNESComputeJacobianDefaultColor, NULL));
711: }
713: /* Compute the operators */
714: PetscCall(DMGetDMSNES(snes->dm, &sdm));
715: if (Xnamed && sdm->ops->computefunction) {
716: /* The SNES contract with the user is that ComputeFunction is always called before ComputeJacobian.
717: We make sure of this here. Disable affine shift since it is for the finest level */
718: Vec F, saverhs = snes->vec_rhs;
720: snes->vec_rhs = NULL;
721: PetscCall(DMGetGlobalVector(snes->dm, &F));
722: PetscCall(SNESComputeFunction(snes, X, F));
723: PetscCall(DMRestoreGlobalVector(snes->dm, &F));
724: snes->vec_rhs = saverhs;
725: snes->nfuncs--; /* Do not log coarser level evaluations */
726: }
727: /* Make sure KSP DM has the Jacobian computation routine */
728: if (!sdm->ops->computejacobian) PetscCall(DMCopyDMSNES(dmsave, snes->dm));
729: PetscCall(SNESComputeJacobian(snes, X, A, B)); /* cannot handle previous SNESSetJacobianDomainError() calls */
731: /* Put the previous context back */
732: if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) PetscCall(SNESSetJacobian(snes, NULL, NULL, jac, ctxsave));
734: if (Xnamed) PetscCall(DMRestoreNamedGlobalVector(snes->dm, "SNESVecSol", &Xnamed));
735: snes->dm = dmsave;
736: PetscFunctionReturn(PETSC_SUCCESS);
737: }
739: /*@
740: SNESSetUpMatrices - ensures that matrices are available for `SNES` Newton-like methods, this is called by `SNESSetUp_XXX()`
742: Collective
744: Input Parameter:
745: . snes - `SNES` object to configure
747: Level: developer
749: Note:
750: If the matrices do not yet exist it attempts to create them based on options previously set for the `SNES` such as `-snes_mf`
752: Developer Note:
753: The functionality of this routine overlaps in a confusing way with the functionality of `SNESSetUpMatrixFree_Private()` which is called by
754: `SNESSetUp()` but sometimes `SNESSetUpMatrices()` is called without `SNESSetUp()` being called. A refactorization to simplify the
755: logic that handles the matrix-free case is desirable.
757: .seealso: [](ch_snes), `SNES`, `SNESSetUp()`
758: @*/
759: PetscErrorCode SNESSetUpMatrices(SNES snes)
760: {
761: DM dm;
762: DMSNES sdm;
764: PetscFunctionBegin;
765: PetscCall(SNESGetDM(snes, &dm));
766: PetscCall(DMGetDMSNES(dm, &sdm));
767: if (!snes->jacobian && snes->mf && !snes->mf_operator && !snes->jacobian_pre) {
768: Mat J;
769: void *functx;
770: PetscCall(MatCreateSNESMF(snes, &J));
771: PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
772: PetscCall(MatSetFromOptions(J));
773: PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
774: PetscCall(SNESSetJacobian(snes, J, J, NULL, NULL));
775: PetscCall(MatDestroy(&J));
776: } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
777: Mat J, B;
778: PetscCall(MatCreateSNESMF(snes, &J));
779: PetscCall(MatMFFDSetOptionsPrefix(J, ((PetscObject)snes)->prefix));
780: PetscCall(MatSetFromOptions(J));
781: PetscCall(DMCreateMatrix(snes->dm, &B));
782: /* sdm->computejacobian was already set to reach here */
783: PetscCall(SNESSetJacobian(snes, J, B, NULL, NULL));
784: PetscCall(MatDestroy(&J));
785: PetscCall(MatDestroy(&B));
786: } else if (!snes->jacobian_pre) {
787: PetscDS prob;
788: Mat J, B;
789: PetscBool hasPrec = PETSC_FALSE;
791: J = snes->jacobian;
792: PetscCall(DMGetDS(dm, &prob));
793: if (prob) PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
794: if (J) PetscCall(PetscObjectReference((PetscObject)J));
795: else if (hasPrec) PetscCall(DMCreateMatrix(snes->dm, &J));
796: PetscCall(DMCreateMatrix(snes->dm, &B));
797: PetscCall(SNESSetJacobian(snes, J ? J : B, B, NULL, NULL));
798: PetscCall(MatDestroy(&J));
799: PetscCall(MatDestroy(&B));
800: }
801: {
802: KSP ksp;
803: PetscCall(SNESGetKSP(snes, &ksp));
804: PetscCall(KSPSetComputeOperators(ksp, KSPComputeOperators_SNES, snes));
805: PetscCall(DMCoarsenHookAdd(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
806: }
807: PetscFunctionReturn(PETSC_SUCCESS);
808: }
810: PETSC_SINGLE_LIBRARY_INTERN PetscErrorCode PetscMonitorPauseFinal_Internal(PetscInt, PetscCtx);
812: static PetscErrorCode SNESMonitorPauseFinal_Internal(SNES snes)
813: {
814: PetscFunctionBegin;
815: if (!snes->pauseFinal) PetscFunctionReturn(PETSC_SUCCESS);
816: PetscCall(PetscMonitorPauseFinal_Internal(snes->numbermonitors, snes->monitorcontext));
817: PetscFunctionReturn(PETSC_SUCCESS);
818: }
820: /*@C
821: SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
823: Collective
825: Input Parameters:
826: + snes - `SNES` object you wish to monitor
827: . name - the monitor type one is seeking
828: . help - message indicating what monitoring is done
829: . manual - manual page for the monitor
830: . monitor - the monitor function, this must use a `PetscViewerFormat` as its context
831: - monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the `SNES` or `PetscViewer` objects
833: Calling sequence of `monitor`:
834: + snes - the nonlinear solver context
835: . it - the current iteration
836: . r - the current function norm
837: - vf - a `PetscViewerAndFormat` struct that contains the `PetscViewer` and `PetscViewerFormat` to use
839: Calling sequence of `monitorsetup`:
840: + snes - the nonlinear solver context
841: - vf - a `PetscViewerAndFormat` struct that contains the `PetscViewer` and `PetscViewerFormat` to use
843: Options Database Key:
844: . -name - trigger the use of this monitor in `SNESSetFromOptions()`
846: Level: advanced
848: .seealso: [](ch_snes), `PetscOptionsCreateViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
849: `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`,
850: `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`,
851: `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
852: `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
853: `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
854: `PetscOptionsFList()`, `PetscOptionsEList()`
855: @*/
856: PetscErrorCode SNESMonitorSetFromOptions(SNES snes, const char name[], const char help[], const char manual[], PetscErrorCode (*monitor)(SNES snes, PetscInt it, PetscReal r, PetscViewerAndFormat *vf), PetscErrorCode (*monitorsetup)(SNES snes, PetscViewerAndFormat *vf))
857: {
858: PetscViewer viewer;
859: PetscViewerFormat format;
860: PetscBool flg;
862: PetscFunctionBegin;
863: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, name, &viewer, &format, &flg));
864: if (flg) {
865: PetscViewerAndFormat *vf;
866: PetscCall(PetscViewerAndFormatCreate(viewer, format, &vf));
867: PetscCall(PetscViewerDestroy(&viewer));
868: if (monitorsetup) PetscCall((*monitorsetup)(snes, vf));
869: PetscCall(SNESMonitorSet(snes, (PetscErrorCode (*)(SNES, PetscInt, PetscReal, PetscCtx))monitor, vf, (PetscCtxDestroyFn *)PetscViewerAndFormatDestroy));
870: }
871: PetscFunctionReturn(PETSC_SUCCESS);
872: }
874: PetscErrorCode SNESEWSetFromOptions_Private(SNESKSPEW *kctx, PetscBool print_api, MPI_Comm comm, const char *prefix)
875: {
876: const char *api = print_api ? "SNESKSPSetParametersEW" : NULL;
878: PetscFunctionBegin;
879: PetscOptionsBegin(comm, prefix, "Eisenstat and Walker type forcing options", "KSP");
880: PetscCall(PetscOptionsInt("-ksp_ew_version", "Version 1, 2 or 3", api, kctx->version, &kctx->version, NULL));
881: PetscCall(PetscOptionsReal("-ksp_ew_rtol0", "0 <= rtol0 < 1", api, kctx->rtol_0, &kctx->rtol_0, NULL));
882: kctx->rtol_max = PetscMax(kctx->rtol_0, kctx->rtol_max);
883: PetscCall(PetscOptionsReal("-ksp_ew_rtolmax", "0 <= rtolmax < 1", api, kctx->rtol_max, &kctx->rtol_max, NULL));
884: PetscCall(PetscOptionsReal("-ksp_ew_gamma", "0 <= gamma <= 1", api, kctx->gamma, &kctx->gamma, NULL));
885: PetscCall(PetscOptionsReal("-ksp_ew_alpha", "1 < alpha <= 2", api, kctx->alpha, &kctx->alpha, NULL));
886: PetscCall(PetscOptionsReal("-ksp_ew_alpha2", "alpha2", NULL, kctx->alpha2, &kctx->alpha2, NULL));
887: PetscCall(PetscOptionsReal("-ksp_ew_threshold", "0 < threshold < 1", api, kctx->threshold, &kctx->threshold, NULL));
888: PetscCall(PetscOptionsReal("-ksp_ew_v4_p1", "p1", NULL, kctx->v4_p1, &kctx->v4_p1, NULL));
889: PetscCall(PetscOptionsReal("-ksp_ew_v4_p2", "p2", NULL, kctx->v4_p2, &kctx->v4_p2, NULL));
890: PetscCall(PetscOptionsReal("-ksp_ew_v4_p3", "p3", NULL, kctx->v4_p3, &kctx->v4_p3, NULL));
891: PetscCall(PetscOptionsReal("-ksp_ew_v4_m1", "Scaling when rk-1 in [p2,p3)", NULL, kctx->v4_m1, &kctx->v4_m1, NULL));
892: PetscCall(PetscOptionsReal("-ksp_ew_v4_m2", "Scaling when rk-1 in [p3,+infty)", NULL, kctx->v4_m2, &kctx->v4_m2, NULL));
893: PetscCall(PetscOptionsReal("-ksp_ew_v4_m3", "Threshold for successive rtol (0.1 in Eq.7)", NULL, kctx->v4_m3, &kctx->v4_m3, NULL));
894: PetscCall(PetscOptionsReal("-ksp_ew_v4_m4", "Adaptation scaling (0.5 in Eq.7)", NULL, kctx->v4_m4, &kctx->v4_m4, NULL));
895: PetscOptionsEnd();
896: PetscFunctionReturn(PETSC_SUCCESS);
897: }
899: /*@
900: SNESSetFromOptions - Sets various `SNES` and `KSP` parameters from user options.
902: Collective
904: Input Parameter:
905: . snes - the `SNES` context
907: Options Database Keys:
908: + -snes_type type - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, `SNESType` for complete list
909: . -snes_rtol rtol - relative decrease in tolerance norm from initial
910: . -snes_atol abstol - absolute tolerance of residual norm
911: . -snes_stol stol - convergence tolerance in terms of the norm of the change in the solution between steps
912: . -snes_divergence_tolerance divtol - if the residual goes above divtol*rnorm0, exit with divergence
913: . -snes_max_it max_it - maximum number of iterations
914: . -snes_max_funcs max_funcs - maximum number of function evaluations
915: . -snes_force_iteration force - force `SNESSolve()` to take at least one iteration
916: . -snes_max_fail max_fail - maximum number of line search failures allowed before stopping, default is none
917: . -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
918: . -snes_lag_preconditioner lag - how often preconditioner is rebuilt (use -1 to never rebuild)
919: . -snes_lag_preconditioner_persists (true|false) - retains the -snes_lag_preconditioner information across multiple SNESSolve()
920: . -snes_lag_jacobian lag - how often Jacobian is rebuilt (use -1 to never rebuild)
921: . -snes_lag_jacobian_persists (true|false) - retains the -snes_lag_jacobian information across multiple SNESSolve()
922: . -snes_convergence_test (default|skip|correct_pressure) - convergence test in nonlinear solver. default `SNESConvergedDefault()`. skip `SNESConvergedSkip()` means continue
923: iterating until max_it or some other criterion is reached, saving expense of convergence test. correct_pressure
924: `SNESConvergedCorrectPressure()` has special handling of a pressure null space.
925: . -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
926: . -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
927: . -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
928: . -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
929: . -snes_monitor_lg_residualnorm - plots residual norm at each iteration
930: . -snes_monitor_lg_range - plots residual norm at each iteration
931: . -snes_monitor_pause_final - Pauses all monitor drawing after the solver ends
932: . -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
933: . -snes_fd_color - use finite differences with coloring to compute Jacobian
934: . -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each `KSP` iteration
935: . -snes_converged_reason - print the reason for convergence/divergence after each solve
936: . -npc_snes_type type - the `SNES` type to use as a nonlinear preconditioner
937: . -snes_test_jacobian [threshold] - compare the user provided Jacobian with one computed via finite differences to check for errors.
938: If a threshold is given, display only those entries whose difference is greater than the threshold.
939: - -snes_test_jacobian_view - display the user provided Jacobian, the finite difference Jacobian and the difference between them
940: to help users detect the location of errors in the user provided Jacobian.
942: Options Database Keys for Eisenstat-Walker method:
943: + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
944: . -snes_ksp_ew_version ver - version of Eisenstat-Walker method
945: . -snes_ksp_ew_rtol0 rtol0 - Sets rtol0
946: . -snes_ksp_ew_rtolmax rtolmax - Sets rtolmax
947: . -snes_ksp_ew_gamma gamma - Sets gamma
948: . -snes_ksp_ew_alpha alpha - Sets alpha
949: . -snes_ksp_ew_alpha2 alpha2 - Sets alpha2
950: - -snes_ksp_ew_threshold threshold - Sets threshold
952: Level: beginner
954: Notes:
955: To see all options, run your program with the -help option or consult the users manual
957: `SNES` supports three approaches for computing (approximate) Jacobians: user provided via `SNESSetJacobian()`, matrix-free using `MatCreateSNESMF()`,
958: and computing explicitly with
959: finite differences and coloring using `MatFDColoring`. It is also possible to use automatic differentiation and the `MatFDColoring` object.
961: .seealso: [](ch_snes), `SNESType`, `SNESSetOptionsPrefix()`, `SNESResetFromOptions()`, `SNES`, `SNESCreate()`, `MatCreateSNESMF()`, `MatFDColoring`
962: @*/
963: PetscErrorCode SNESSetFromOptions(SNES snes)
964: {
965: PetscBool flg, pcset, persist, set;
966: PetscInt i, indx, lag, grids, max_its, max_funcs;
967: const char *deft = SNESNEWTONLS;
968: const char *convtests[] = {"default", "skip", "correct_pressure"};
969: SNESKSPEW *kctx = NULL;
970: char type[256], monfilename[PETSC_MAX_PATH_LEN], ewprefix[256];
971: PCSide pcside;
972: const char *optionsprefix;
973: PetscReal rtol, abstol, stol;
975: PetscFunctionBegin;
977: PetscCall(SNESRegisterAll());
978: PetscObjectOptionsBegin((PetscObject)snes);
979: if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
980: PetscCall(PetscOptionsFList("-snes_type", "Nonlinear solver method", "SNESSetType", SNESList, deft, type, 256, &flg));
981: if (flg) PetscCall(SNESSetType(snes, type));
982: else if (!((PetscObject)snes)->type_name) PetscCall(SNESSetType(snes, deft));
984: abstol = snes->abstol;
985: rtol = snes->rtol;
986: stol = snes->stol;
987: max_its = snes->max_its;
988: max_funcs = snes->max_funcs;
989: PetscCall(PetscOptionsReal("-snes_rtol", "Stop if decrease in function norm less than", "SNESSetTolerances", snes->rtol, &rtol, NULL));
990: PetscCall(PetscOptionsReal("-snes_atol", "Stop if function norm less than", "SNESSetTolerances", snes->abstol, &abstol, NULL));
991: PetscCall(PetscOptionsReal("-snes_stol", "Stop if step length less than", "SNESSetTolerances", snes->stol, &stol, NULL));
992: PetscCall(PetscOptionsInt("-snes_max_it", "Maximum iterations", "SNESSetTolerances", snes->max_its, &max_its, NULL));
993: PetscCall(PetscOptionsInt("-snes_max_funcs", "Maximum function evaluations", "SNESSetTolerances", snes->max_funcs, &max_funcs, NULL));
994: PetscCall(SNESSetTolerances(snes, abstol, rtol, stol, max_its, max_funcs));
996: PetscCall(PetscOptionsReal("-snes_divergence_tolerance", "Stop if residual norm increases by this factor", "SNESSetDivergenceTolerance", snes->divtol, &snes->divtol, &flg));
997: if (flg) PetscCall(SNESSetDivergenceTolerance(snes, snes->divtol));
999: PetscCall(PetscOptionsInt("-snes_max_fail", "Maximum nonlinear step failures", "SNESSetMaxNonlinearStepFailures", snes->maxFailures, &snes->maxFailures, &flg));
1000: if (flg) PetscCall(SNESSetMaxNonlinearStepFailures(snes, snes->maxFailures));
1002: PetscCall(PetscOptionsInt("-snes_max_linear_solve_fail", "Maximum failures in linear solves allowed", "SNESSetMaxLinearSolveFailures", snes->maxLinearSolveFailures, &snes->maxLinearSolveFailures, &flg));
1003: if (flg) PetscCall(SNESSetMaxLinearSolveFailures(snes, snes->maxLinearSolveFailures));
1005: PetscCall(PetscOptionsBool("-snes_error_if_not_converged", "Generate error if solver does not converge", "SNESSetErrorIfNotConverged", snes->errorifnotconverged, &snes->errorifnotconverged, NULL));
1006: PetscCall(PetscOptionsBool("-snes_force_iteration", "Force SNESSolve() to take at least one iteration", "SNESSetForceIteration", snes->forceiteration, &snes->forceiteration, NULL));
1007: PetscCall(PetscOptionsBool("-snes_check_jacobian_domain_error", "Check Jacobian domain error after Jacobian evaluation", "SNESCheckJacobianDomainError", snes->checkjacdomainerror, &snes->checkjacdomainerror, NULL));
1009: PetscCall(PetscOptionsInt("-snes_lag_preconditioner", "How often to rebuild preconditioner", "SNESSetLagPreconditioner", snes->lagpreconditioner, &lag, &flg));
1010: if (flg) {
1011: 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");
1012: PetscCall(SNESSetLagPreconditioner(snes, lag));
1013: }
1014: PetscCall(PetscOptionsBool("-snes_lag_preconditioner_persists", "Preconditioner lagging through multiple SNES solves", "SNESSetLagPreconditionerPersists", snes->lagjac_persist, &persist, &flg));
1015: if (flg) PetscCall(SNESSetLagPreconditionerPersists(snes, persist));
1016: PetscCall(PetscOptionsInt("-snes_lag_jacobian", "How often to rebuild Jacobian", "SNESSetLagJacobian", snes->lagjacobian, &lag, &flg));
1017: if (flg) {
1018: 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");
1019: PetscCall(SNESSetLagJacobian(snes, lag));
1020: }
1021: PetscCall(PetscOptionsBool("-snes_lag_jacobian_persists", "Jacobian lagging through multiple SNES solves", "SNESSetLagJacobianPersists", snes->lagjac_persist, &persist, &flg));
1022: if (flg) PetscCall(SNESSetLagJacobianPersists(snes, persist));
1024: PetscCall(PetscOptionsInt("-snes_grid_sequence", "Use grid sequencing to generate initial guess", "SNESSetGridSequence", snes->gridsequence, &grids, &flg));
1025: if (flg) PetscCall(SNESSetGridSequence(snes, grids));
1027: PetscCall(PetscOptionsEList("-snes_convergence_test", "Convergence test", "SNESSetConvergenceTest", convtests, PETSC_STATIC_ARRAY_LENGTH(convtests), "default", &indx, &flg));
1028: if (flg) {
1029: switch (indx) {
1030: case 0:
1031: PetscCall(SNESSetConvergenceTest(snes, SNESConvergedDefault, NULL, NULL));
1032: break;
1033: case 1:
1034: PetscCall(SNESSetConvergenceTest(snes, SNESConvergedSkip, NULL, NULL));
1035: break;
1036: case 2:
1037: PetscCall(SNESSetConvergenceTest(snes, SNESConvergedCorrectPressure, NULL, NULL));
1038: break;
1039: }
1040: }
1042: PetscCall(PetscOptionsEList("-snes_norm_schedule", "SNES Norm schedule", "SNESSetNormSchedule", SNESNormSchedules, 5, "function", &indx, &flg));
1043: if (flg) PetscCall(SNESSetNormSchedule(snes, (SNESNormSchedule)indx));
1045: PetscCall(PetscOptionsEList("-snes_function_type", "SNES Norm schedule", "SNESSetFunctionType", SNESFunctionTypes, 2, "unpreconditioned", &indx, &flg));
1046: if (flg) PetscCall(SNESSetFunctionType(snes, (SNESFunctionType)indx));
1048: kctx = (SNESKSPEW *)snes->kspconvctx;
1050: PetscCall(PetscOptionsBool("-snes_ksp_ew", "Use Eisentat-Walker linear system convergence test", "SNESKSPSetUseEW", snes->ksp_ewconv, &snes->ksp_ewconv, NULL));
1052: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1053: PetscCall(PetscSNPrintf(ewprefix, sizeof(ewprefix), "%s%s", optionsprefix ? optionsprefix : "", "snes_"));
1054: PetscCall(SNESEWSetFromOptions_Private(kctx, PETSC_TRUE, PetscObjectComm((PetscObject)snes), ewprefix));
1056: flg = PETSC_FALSE;
1057: PetscCall(PetscOptionsBool("-snes_monitor_cancel", "Remove all monitors", "SNESMonitorCancel", flg, &flg, &set));
1058: if (set && flg) PetscCall(SNESMonitorCancel(snes));
1060: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor", "Monitor norm of function", "SNESMonitorDefault", SNESMonitorDefault, SNESMonitorDefaultSetUp));
1061: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_short", "Monitor norm of function with fewer digits", "SNESMonitorDefaultShort", SNESMonitorDefaultShort, NULL));
1062: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_range", "Monitor range of elements of function", "SNESMonitorRange", SNESMonitorRange, NULL));
1064: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_ratio", "Monitor ratios of the norm of function for consecutive steps", "SNESMonitorRatio", SNESMonitorRatio, SNESMonitorRatioSetUp));
1065: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_field", "Monitor norm of function (split into fields)", "SNESMonitorDefaultField", SNESMonitorDefaultField, NULL));
1066: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_solution", "View solution at each iteration", "SNESMonitorSolution", SNESMonitorSolution, NULL));
1067: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_solution_update", "View correction at each iteration", "SNESMonitorSolutionUpdate", SNESMonitorSolutionUpdate, NULL));
1068: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_residual", "View residual at each iteration", "SNESMonitorResidual", SNESMonitorResidual, NULL));
1069: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_jacupdate_spectrum", "Print the change in the spectrum of the Jacobian", "SNESMonitorJacUpdateSpectrum", SNESMonitorJacUpdateSpectrum, NULL));
1070: PetscCall(SNESMonitorSetFromOptions(snes, "-snes_monitor_fields", "Monitor norm of function per field", "SNESMonitorSet", SNESMonitorFields, NULL));
1071: PetscCall(PetscOptionsBool("-snes_monitor_pause_final", "Pauses all draw monitors at the final iterate", "SNESMonitorPauseFinal_Internal", PETSC_FALSE, &snes->pauseFinal, NULL));
1073: PetscCall(PetscOptionsString("-snes_monitor_python", "Use Python function", "SNESMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1074: if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)snes, monfilename));
1076: flg = PETSC_FALSE;
1077: PetscCall(PetscOptionsBool("-snes_monitor_lg_range", "Plot function range at each iteration", "SNESMonitorLGRange", flg, &flg, NULL));
1078: if (flg) {
1079: PetscViewer ctx;
1081: PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, &ctx));
1082: PetscCall(SNESMonitorSet(snes, SNESMonitorLGRange, ctx, (PetscCtxDestroyFn *)PetscViewerDestroy));
1083: }
1085: PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
1086: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_converged_reason", &snes->convergedreasonviewer, &snes->convergedreasonformat, NULL));
1087: flg = PETSC_FALSE;
1088: PetscCall(PetscOptionsBool("-snes_converged_reason_view_cancel", "Remove all converged reason viewers", "SNESConvergedReasonViewCancel", flg, &flg, &set));
1089: if (set && flg) PetscCall(SNESConvergedReasonViewCancel(snes));
1091: flg = PETSC_FALSE;
1092: PetscCall(PetscOptionsBool("-snes_fd", "Use finite differences (slow) to compute Jacobian", "SNESComputeJacobianDefault", flg, &flg, NULL));
1093: if (flg) {
1094: void *functx;
1095: DM dm;
1096: PetscCall(SNESGetDM(snes, &dm));
1097: PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1098: PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
1099: PetscCall(SNESSetJacobian(snes, snes->jacobian, snes->jacobian_pre, SNESComputeJacobianDefault, functx));
1100: PetscCall(PetscInfo(snes, "Setting default finite difference Jacobian matrix\n"));
1101: }
1103: flg = PETSC_FALSE;
1104: PetscCall(PetscOptionsBool("-snes_fd_function", "Use finite differences (slow) to compute function from user objective", "SNESObjectiveComputeFunctionDefaultFD", flg, &flg, NULL));
1105: if (flg) PetscCall(SNESSetFunction(snes, NULL, SNESObjectiveComputeFunctionDefaultFD, NULL));
1107: flg = PETSC_FALSE;
1108: PetscCall(PetscOptionsBool("-snes_fd_color", "Use finite differences with coloring to compute Jacobian", "SNESComputeJacobianDefaultColor", flg, &flg, NULL));
1109: if (flg) {
1110: DM dm;
1111: PetscCall(SNESGetDM(snes, &dm));
1112: PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1113: PetscCall(SNESSetJacobian(snes, snes->jacobian, snes->jacobian_pre, SNESComputeJacobianDefaultColor, NULL));
1114: PetscCall(PetscInfo(snes, "Setting default finite difference coloring Jacobian matrix\n"));
1115: }
1117: flg = PETSC_FALSE;
1118: 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));
1119: if (flg && snes->mf_operator) {
1120: snes->mf_operator = PETSC_TRUE;
1121: snes->mf = PETSC_TRUE;
1122: }
1123: flg = PETSC_FALSE;
1124: PetscCall(PetscOptionsBool("-snes_mf", "Use a Matrix-Free Jacobian with no matrix for computing the preconditioner", "SNESSetUseMatrixFree", PETSC_FALSE, &snes->mf, &flg));
1125: if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1126: PetscCall(PetscOptionsInt("-snes_mf_version", "Matrix-Free routines version 1 or 2", "None", snes->mf_version, &snes->mf_version, NULL));
1128: PetscCall(PetscOptionsName("-snes_test_function", "Compare hand-coded and finite difference functions", "None", &snes->testFunc));
1129: PetscCall(PetscOptionsName("-snes_test_jacobian", "Compare hand-coded and finite difference Jacobians", "None", &snes->testJac));
1131: flg = PETSC_FALSE;
1132: PetscCall(SNESGetNPCSide(snes, &pcside));
1133: PetscCall(PetscOptionsEnum("-snes_npc_side", "SNES nonlinear preconditioner side", "SNESSetNPCSide", PCSides, (PetscEnum)pcside, (PetscEnum *)&pcside, &flg));
1134: if (flg) PetscCall(SNESSetNPCSide(snes, pcside));
1136: #if defined(PETSC_HAVE_SAWS)
1137: /*
1138: Publish convergence information using SAWs
1139: */
1140: flg = PETSC_FALSE;
1141: PetscCall(PetscOptionsBool("-snes_monitor_saws", "Publish SNES progress using SAWs", "SNESMonitorSet", flg, &flg, NULL));
1142: if (flg) {
1143: PetscCtx ctx;
1144: PetscCall(SNESMonitorSAWsCreate(snes, &ctx));
1145: PetscCall(SNESMonitorSet(snes, SNESMonitorSAWs, ctx, SNESMonitorSAWsDestroy));
1146: }
1147: #endif
1148: #if defined(PETSC_HAVE_SAWS)
1149: {
1150: PetscBool set;
1151: flg = PETSC_FALSE;
1152: PetscCall(PetscOptionsBool("-snes_saws_block", "Block for SAWs at end of SNESSolve", "PetscObjectSAWsBlock", ((PetscObject)snes)->amspublishblock, &flg, &set));
1153: if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)snes, flg));
1154: }
1155: #endif
1157: for (i = 0; i < numberofsetfromoptions; i++) PetscCall((*othersetfromoptions[i])(snes));
1159: PetscTryTypeMethod(snes, setfromoptions, PetscOptionsObject);
1161: /* process any options handlers added with PetscObjectAddOptionsHandler() */
1162: PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)snes, PetscOptionsObject));
1163: PetscOptionsEnd();
1165: if (snes->linesearch) {
1166: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
1167: PetscCall(SNESLineSearchSetFromOptions(snes->linesearch));
1168: }
1170: if (snes->usesksp) {
1171: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
1172: PetscCall(KSPSetOperators(snes->ksp, snes->jacobian, snes->jacobian_pre));
1173: PetscCall(KSPSetFromOptions(snes->ksp));
1174: }
1176: /* if user has set the SNES NPC type via options database, create it. */
1177: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1178: PetscCall(PetscOptionsHasName(((PetscObject)snes)->options, optionsprefix, "-npc_snes_type", &pcset));
1179: if (pcset && (!snes->npc)) PetscCall(SNESGetNPC(snes, &snes->npc));
1180: if (snes->npc) PetscCall(SNESSetFromOptions(snes->npc));
1181: snes->setfromoptionscalled++;
1182: PetscFunctionReturn(PETSC_SUCCESS);
1183: }
1185: /*@
1186: SNESResetFromOptions - Sets various `SNES` and `KSP` parameters from user options ONLY if the `SNESSetFromOptions()` was previously called
1188: Collective
1190: Input Parameter:
1191: . snes - the `SNES` context
1193: Level: advanced
1195: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESSetOptionsPrefix()`
1196: @*/
1197: PetscErrorCode SNESResetFromOptions(SNES snes)
1198: {
1199: PetscFunctionBegin;
1200: if (snes->setfromoptionscalled) PetscCall(SNESSetFromOptions(snes));
1201: PetscFunctionReturn(PETSC_SUCCESS);
1202: }
1204: /*@C
1205: SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1206: the nonlinear solvers.
1208: Logically Collective; No Fortran Support
1210: Input Parameters:
1211: + snes - the `SNES` context
1212: . compute - function to compute the context
1213: - destroy - function to destroy the context, see `PetscCtxDestroyFn` for the calling sequence
1215: Calling sequence of `compute`:
1216: + snes - the `SNES` context
1217: - ctx - context to be computed
1219: Level: intermediate
1221: Note:
1222: This routine is useful if you are performing grid sequencing or using `SNESFAS` and need the appropriate context generated for each level.
1224: Use `SNESSetApplicationContext()` to see the context immediately
1226: .seealso: [](ch_snes), `SNESGetApplicationContext()`, `SNESSetApplicationContext()`, `PetscCtxDestroyFn`
1227: @*/
1228: PetscErrorCode SNESSetComputeApplicationContext(SNES snes, PetscErrorCode (*compute)(SNES snes, PetscCtxRt ctx), PetscCtxDestroyFn *destroy)
1229: {
1230: PetscFunctionBegin;
1232: snes->ops->ctxcompute = compute;
1233: snes->ops->ctxdestroy = destroy;
1234: PetscFunctionReturn(PETSC_SUCCESS);
1235: }
1237: /*@
1238: SNESSetApplicationContext - Sets the optional user-defined context for the nonlinear solvers.
1240: Logically Collective
1242: Input Parameters:
1243: + snes - the `SNES` context
1244: - ctx - the user context
1246: Level: intermediate
1248: Notes:
1249: Users can provide a context when constructing the `SNES` options and then access it inside their function, Jacobian computation, or other evaluation function
1250: with `SNESGetApplicationContext()`
1252: To provide a function that computes the context for you use `SNESSetComputeApplicationContext()`
1254: Fortran Note:
1255: This only works when `ctx` is a Fortran derived type (it cannot be a `PetscObject`), we recommend writing a Fortran interface definition for this
1256: function that tells the Fortran compiler the derived data type that is passed in as the `ctx` argument. See `SNESGetApplicationContext()` for
1257: an example.
1259: .seealso: [](ch_snes), `SNES`, `SNESSetComputeApplicationContext()`, `SNESGetApplicationContext()`
1260: @*/
1261: PetscErrorCode SNESSetApplicationContext(SNES snes, PetscCtx ctx)
1262: {
1263: KSP ksp;
1265: PetscFunctionBegin;
1267: PetscCall(SNESGetKSP(snes, &ksp));
1268: PetscCall(KSPSetApplicationContext(ksp, ctx));
1269: snes->ctx = ctx;
1270: PetscFunctionReturn(PETSC_SUCCESS);
1271: }
1273: /*@
1274: SNESGetApplicationContext - Gets the user-defined context for the
1275: nonlinear solvers set with `SNESGetApplicationContext()` or `SNESSetComputeApplicationContext()`
1277: Not Collective
1279: Input Parameter:
1280: . snes - `SNES` context
1282: Output Parameter:
1283: . ctx - the application context
1285: Level: intermediate
1287: Fortran Notes:
1288: This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
1289: .vb
1290: type(tUsertype), pointer :: ctx
1291: .ve
1293: .seealso: [](ch_snes), `SNESSetApplicationContext()`, `SNESSetComputeApplicationContext()`
1294: @*/
1295: PetscErrorCode SNESGetApplicationContext(SNES snes, PetscCtxRt ctx)
1296: {
1297: PetscFunctionBegin;
1299: *(void **)ctx = snes->ctx;
1300: PetscFunctionReturn(PETSC_SUCCESS);
1301: }
1303: /*@
1304: SNESSetUseMatrixFree - indicates that `SNES` should use matrix-free finite difference matrix-vector products to apply the Jacobian.
1306: Logically Collective
1308: Input Parameters:
1309: + snes - `SNES` context
1310: . mf_operator - use matrix-free only for the Amat used by `SNESSetJacobian()`, this means the user provided Pmat will continue to be used
1311: - 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
1312: this option no matrix-element based preconditioners can be used in the linear solve since the matrix won't be explicitly available
1314: Options Database Keys:
1315: + -snes_mf_operator - use matrix-free only for the mat operator
1316: . -snes_mf - use matrix-free for both the mat and pmat operator
1317: . -snes_fd_color - compute the Jacobian via coloring and finite differences.
1318: - -snes_fd - compute the Jacobian via finite differences (slow)
1320: Level: intermediate
1322: Note:
1323: `SNES` supports three approaches for computing (approximate) Jacobians: user provided via `SNESSetJacobian()`, matrix-free using `MatCreateSNESMF()`,
1324: and computing explicitly with
1325: finite differences and coloring using `MatFDColoring`. It is also possible to use automatic differentiation and the `MatFDColoring` object.
1327: .seealso: [](ch_snes), `SNES`, `SNESGetUseMatrixFree()`, `MatCreateSNESMF()`, `SNESComputeJacobianDefaultColor()`, `MatFDColoring`
1328: @*/
1329: PetscErrorCode SNESSetUseMatrixFree(SNES snes, PetscBool mf_operator, PetscBool mf)
1330: {
1331: PetscFunctionBegin;
1335: snes->mf = mf_operator ? PETSC_TRUE : mf;
1336: snes->mf_operator = mf_operator;
1337: PetscFunctionReturn(PETSC_SUCCESS);
1338: }
1340: /*@
1341: SNESGetUseMatrixFree - indicates if the `SNES` uses matrix-free finite difference matrix vector products to apply the Jacobian.
1343: Not Collective, but the resulting flags will be the same on all MPI processes
1345: Input Parameter:
1346: . snes - `SNES` context
1348: Output Parameters:
1349: + mf_operator - use matrix-free only for the Amat used by `SNESSetJacobian()`, this means the user provided Pmat will continue to be used
1350: - mf - use matrix-free for both the Amat and Pmat used by `SNESSetJacobian()`, both the Amat and Pmat set in `SNESSetJacobian()` will be ignored
1352: Level: intermediate
1354: .seealso: [](ch_snes), `SNES`, `SNESSetUseMatrixFree()`, `MatCreateSNESMF()`
1355: @*/
1356: PetscErrorCode SNESGetUseMatrixFree(SNES snes, PetscBool *mf_operator, PetscBool *mf)
1357: {
1358: PetscFunctionBegin;
1360: if (mf) *mf = snes->mf;
1361: if (mf_operator) *mf_operator = snes->mf_operator;
1362: PetscFunctionReturn(PETSC_SUCCESS);
1363: }
1365: /*@
1366: SNESGetIterationNumber - Gets the number of nonlinear iterations completed in the current or most recent `SNESSolve()`
1368: Not Collective
1370: Input Parameter:
1371: . snes - `SNES` context
1373: Output Parameter:
1374: . iter - iteration number
1376: Level: intermediate
1378: Notes:
1379: For example, during the computation of iteration 2 this would return 1.
1381: This is useful for using lagged Jacobians (where one does not recompute the
1382: Jacobian at each `SNES` iteration). For example, the code
1383: .vb
1384: ierr = SNESGetIterationNumber(snes,&it);
1385: if (!(it % 2)) {
1386: [compute Jacobian here]
1387: }
1388: .ve
1389: can be used in your function that computes the Jacobian to cause the Jacobian to be
1390: recomputed every second `SNES` iteration. See also `SNESSetLagJacobian()`
1392: After the `SNES` solve is complete this will return the number of nonlinear iterations used.
1394: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetLagJacobian()`, `SNESGetLinearSolveIterations()`, `SNESSetMonitor()`
1395: @*/
1396: PetscErrorCode SNESGetIterationNumber(SNES snes, PetscInt *iter)
1397: {
1398: PetscFunctionBegin;
1400: PetscAssertPointer(iter, 2);
1401: *iter = snes->iter;
1402: PetscFunctionReturn(PETSC_SUCCESS);
1403: }
1405: /*@
1406: SNESSetIterationNumber - Sets the current iteration number.
1408: Not Collective
1410: Input Parameters:
1411: + snes - `SNES` context
1412: - iter - iteration number
1414: Level: developer
1416: Note:
1417: This should only be called inside a `SNES` nonlinear solver.
1419: .seealso: [](ch_snes), `SNESGetLinearSolveIterations()`
1420: @*/
1421: PetscErrorCode SNESSetIterationNumber(SNES snes, PetscInt iter)
1422: {
1423: PetscFunctionBegin;
1425: PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
1426: snes->iter = iter;
1427: PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
1428: PetscFunctionReturn(PETSC_SUCCESS);
1429: }
1431: /*@
1432: SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1433: taken by the nonlinear solver in the current or most recent `SNESSolve()` .
1435: Not Collective
1437: Input Parameter:
1438: . snes - `SNES` context
1440: Output Parameter:
1441: . nfails - number of unsuccessful steps attempted
1443: Level: intermediate
1445: Notes:
1446: A failed step is a step that was generated and taken but did not satisfy the requested step criteria. For example,
1447: the `SNESLineSearchApply()` could not generate a sufficient decrease in the function norm (in fact it may have produced an increase).
1449: Taken steps that produce a infinity or NaN in the function evaluation or generate a `SNESSetFunctionDomainError()`
1450: will always immediately terminate the `SNESSolve()` regardless of the value of `maxFails`.
1452: `SNESSetMaxNonlinearStepFailures()` determines how many unsuccessful steps are allowed before the `SNESSolve()` terminates
1454: This counter is reset to zero for each successive call to `SNESSolve()`.
1456: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1457: `SNESSetMaxNonlinearStepFailures()`, `SNESGetMaxNonlinearStepFailures()`
1458: @*/
1459: PetscErrorCode SNESGetNonlinearStepFailures(SNES snes, PetscInt *nfails)
1460: {
1461: PetscFunctionBegin;
1463: PetscAssertPointer(nfails, 2);
1464: *nfails = snes->numFailures;
1465: PetscFunctionReturn(PETSC_SUCCESS);
1466: }
1468: /*@
1469: SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1470: attempted by the nonlinear solver before it gives up and returns unconverged or generates an error
1472: Not Collective
1474: Input Parameters:
1475: + snes - `SNES` context
1476: - maxFails - maximum of unsuccessful steps allowed, use `PETSC_UNLIMITED` to have no limit on the number of failures
1478: Options Database Key:
1479: . -snes_max_fail n - maximum number of unsuccessful steps allowed
1481: Level: intermediate
1483: Note:
1484: A failed step is a step that was generated and taken but did not satisfy the requested criteria. For example,
1485: the `SNESLineSearchApply()` could not generate a sufficient decrease in the function norm (in fact it may have produced an increase).
1487: Taken steps that produce a infinity or NaN in the function evaluation or generate a `SNESSetFunctionDomainError()`
1488: will always immediately terminate the `SNESSolve()` regardless of the value of `maxFails`.
1490: Developer Note:
1491: The options database key is wrong for this function name
1493: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`,
1494: `SNESGetLinearSolveFailures()`, `SNESGetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`, `SNESCheckLineSearchFailure()`
1495: @*/
1496: PetscErrorCode SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1497: {
1498: PetscFunctionBegin;
1501: if (maxFails == PETSC_UNLIMITED) {
1502: snes->maxFailures = PETSC_INT_MAX;
1503: } else {
1504: PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1505: snes->maxFailures = maxFails;
1506: }
1507: PetscFunctionReturn(PETSC_SUCCESS);
1508: }
1510: /*@
1511: SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1512: attempted by the nonlinear solver before it gives up and returns unconverged or generates an error
1514: Not Collective
1516: Input Parameter:
1517: . snes - `SNES` context
1519: Output Parameter:
1520: . maxFails - maximum of unsuccessful steps
1522: Level: intermediate
1524: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1525: `SNESSetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
1526: @*/
1527: PetscErrorCode SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1528: {
1529: PetscFunctionBegin;
1531: PetscAssertPointer(maxFails, 2);
1532: *maxFails = snes->maxFailures;
1533: PetscFunctionReturn(PETSC_SUCCESS);
1534: }
1536: /*@
1537: SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1538: done by the `SNES` object in the current or most recent `SNESSolve()`
1540: Not Collective
1542: Input Parameter:
1543: . snes - `SNES` context
1545: Output Parameter:
1546: . nfuncs - number of evaluations
1548: Level: intermediate
1550: Note:
1551: Reset every time `SNESSolve()` is called unless `SNESSetCountersReset()` is used.
1553: .seealso: [](ch_snes), `SNES`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, `SNESSetCountersReset()`
1554: @*/
1555: PetscErrorCode SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1556: {
1557: PetscFunctionBegin;
1559: PetscAssertPointer(nfuncs, 2);
1560: *nfuncs = snes->nfuncs;
1561: PetscFunctionReturn(PETSC_SUCCESS);
1562: }
1564: /*@
1565: SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1566: linear solvers in the current or most recent `SNESSolve()`
1568: Not Collective
1570: Input Parameter:
1571: . snes - `SNES` context
1573: Output Parameter:
1574: . nfails - number of failed solves
1576: Options Database Key:
1577: . -snes_max_linear_solve_fail num - The number of failures before the solve is terminated
1579: Level: intermediate
1581: Note:
1582: This counter is reset to zero for each successive call to `SNESSolve()`.
1584: .seealso: [](ch_snes), `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1585: @*/
1586: PetscErrorCode SNESGetLinearSolveFailures(SNES snes, PetscInt *nfails)
1587: {
1588: PetscFunctionBegin;
1590: PetscAssertPointer(nfails, 2);
1591: *nfails = snes->numLinearSolveFailures;
1592: PetscFunctionReturn(PETSC_SUCCESS);
1593: }
1595: /*@
1596: SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1597: allowed before `SNES` returns with a diverged reason of `SNES_DIVERGED_LINEAR_SOLVE`
1599: Logically Collective
1601: Input Parameters:
1602: + snes - `SNES` context
1603: - maxFails - maximum allowed linear solve failures, use `PETSC_UNLIMITED` to have no limit on the number of failures
1605: Options Database Key:
1606: . -snes_max_linear_solve_fail num - The number of failures before the solve is terminated
1608: Level: intermediate
1610: Note:
1611: By default this is 0; that is `SNES` returns on the first failed linear solve
1613: Developer Note:
1614: The options database key is wrong for this function name
1616: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`
1617: @*/
1618: PetscErrorCode SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1619: {
1620: PetscFunctionBegin;
1624: if (maxFails == PETSC_UNLIMITED) {
1625: snes->maxLinearSolveFailures = PETSC_INT_MAX;
1626: } else {
1627: PetscCheck(maxFails >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
1628: snes->maxLinearSolveFailures = maxFails;
1629: }
1630: PetscFunctionReturn(PETSC_SUCCESS);
1631: }
1633: /*@
1634: SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1635: are allowed before `SNES` returns as unsuccessful
1637: Not Collective
1639: Input Parameter:
1640: . snes - `SNES` context
1642: Output Parameter:
1643: . maxFails - maximum of unsuccessful solves allowed
1645: Level: intermediate
1647: Note:
1648: By default this is 1; that is `SNES` returns on the first failed linear solve
1650: .seealso: [](ch_snes), `SNESSetErrorIfNotConverged()`, `SNESGetLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1651: @*/
1652: PetscErrorCode SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1653: {
1654: PetscFunctionBegin;
1656: PetscAssertPointer(maxFails, 2);
1657: *maxFails = snes->maxLinearSolveFailures;
1658: PetscFunctionReturn(PETSC_SUCCESS);
1659: }
1661: /*@
1662: SNESGetLinearSolveIterations - Gets the total number of linear iterations
1663: used by the nonlinear solver in the most recent `SNESSolve()`
1665: Not Collective
1667: Input Parameter:
1668: . snes - `SNES` context
1670: Output Parameter:
1671: . lits - number of linear iterations
1673: Level: intermediate
1675: Notes:
1676: This counter is reset to zero for each successive call to `SNESSolve()` unless `SNESSetCountersReset()` is used.
1678: 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
1679: then call `KSPGetIterationNumber()` after the failed solve.
1681: .seealso: [](ch_snes), `SNES`, `SNESGetIterationNumber()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESSetCountersReset()`
1682: @*/
1683: PetscErrorCode SNESGetLinearSolveIterations(SNES snes, PetscInt *lits)
1684: {
1685: PetscFunctionBegin;
1687: PetscAssertPointer(lits, 2);
1688: *lits = snes->linear_its;
1689: PetscFunctionReturn(PETSC_SUCCESS);
1690: }
1692: /*@
1693: SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1694: are reset every time `SNESSolve()` is called.
1696: Logically Collective
1698: Input Parameters:
1699: + snes - `SNES` context
1700: - reset - whether to reset the counters or not, defaults to `PETSC_TRUE`
1702: Level: developer
1704: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1705: @*/
1706: PetscErrorCode SNESSetCountersReset(SNES snes, PetscBool reset)
1707: {
1708: PetscFunctionBegin;
1711: snes->counters_reset = reset;
1712: PetscFunctionReturn(PETSC_SUCCESS);
1713: }
1715: /*@
1716: SNESResetCounters - Reset counters for linear iterations and function evaluations.
1718: Logically Collective
1720: Input Parameters:
1721: . snes - `SNES` context
1723: Level: developer
1725: Note:
1726: It honors the flag set with `SNESSetCountersReset()`
1728: .seealso: [](ch_snes), `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1729: @*/
1730: PetscErrorCode SNESResetCounters(SNES snes)
1731: {
1732: PetscFunctionBegin;
1734: if (snes->counters_reset) {
1735: snes->nfuncs = 0;
1736: snes->linear_its = 0;
1737: snes->numFailures = 0;
1738: }
1739: PetscFunctionReturn(PETSC_SUCCESS);
1740: }
1742: /*@
1743: SNESSetKSP - Sets a `KSP` context for the `SNES` object to use
1745: Not Collective, but the `SNES` and `KSP` objects must live on the same `MPI_Comm`
1747: Input Parameters:
1748: + snes - the `SNES` context
1749: - ksp - the `KSP` context
1751: Level: developer
1753: Notes:
1754: The `SNES` object already has its `KSP` object, you can obtain with `SNESGetKSP()`
1755: so this routine is rarely needed.
1757: The `KSP` object that is already in the `SNES` object has its reference count
1758: decreased by one when this is called.
1760: .seealso: [](ch_snes), `SNES`, `KSP`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`
1761: @*/
1762: PetscErrorCode SNESSetKSP(SNES snes, KSP ksp)
1763: {
1764: PetscFunctionBegin;
1767: PetscCheckSameComm(snes, 1, ksp, 2);
1768: PetscCall(PetscObjectReference((PetscObject)ksp));
1769: if (snes->ksp) PetscCall(PetscObjectDereference((PetscObject)snes->ksp));
1770: snes->ksp = ksp;
1771: PetscFunctionReturn(PETSC_SUCCESS);
1772: }
1774: /*@
1775: SNESParametersInitialize - Sets all the parameters in `snes` to their default value (when `SNESCreate()` was called) if they
1776: currently contain default values
1778: Collective
1780: Input Parameter:
1781: . snes - the `SNES` object
1783: Level: developer
1785: Developer Note:
1786: This is called by all the `SNESCreate_XXX()` routines.
1788: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
1789: `PetscObjectParameterSetDefault()`
1790: @*/
1791: PetscErrorCode SNESParametersInitialize(SNES snes)
1792: {
1793: PetscObjectParameterSetDefault(snes, max_its, 50);
1794: PetscObjectParameterSetDefault(snes, max_funcs, 10000);
1795: PetscObjectParameterSetDefault(snes, rtol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1796: PetscObjectParameterSetDefault(snes, abstol, PetscDefined(USE_REAL_SINGLE) ? 1.e-25 : 1.e-50);
1797: PetscObjectParameterSetDefault(snes, stol, PetscDefined(USE_REAL_SINGLE) ? 1.e-5 : 1.e-8);
1798: PetscObjectParameterSetDefault(snes, divtol, 1.e4);
1799: return PETSC_SUCCESS;
1800: }
1802: /*@
1803: SNESCreate - Creates a nonlinear solver context used to manage a set of nonlinear solves
1805: Collective
1807: Input Parameter:
1808: . comm - MPI communicator
1810: Output Parameter:
1811: . outsnes - the new `SNES` context
1813: Options Database Keys:
1814: + -snes_mf - Activates default matrix-free Jacobian-vector products, and no matrix to construct a preconditioner
1815: . -snes_mf_operator - Activates default matrix-free Jacobian-vector products, and a user-provided matrix as set by `SNESSetJacobian()`
1816: . -snes_fd_coloring - uses a relative fast computation of the Jacobian using finite differences and a graph coloring
1817: - -snes_fd - Uses (slow!) finite differences to compute Jacobian
1819: Level: beginner
1821: Developer Notes:
1822: `SNES` always creates a `KSP` object even though many `SNES` methods do not use it. This is
1823: unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1824: particular method does use `KSP` and regulates if the information about the `KSP` is printed
1825: in `SNESView()`.
1827: `TSSetFromOptions()` does call `SNESSetFromOptions()` which can lead to users being confused
1828: by help messages about meaningless `SNES` options.
1830: `SNES` always creates the `snes->kspconvctx` even though it is used by only one type. This should be fixed.
1832: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESDestroy()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
1833: @*/
1834: PetscErrorCode SNESCreate(MPI_Comm comm, SNES *outsnes)
1835: {
1836: SNES snes;
1837: SNESKSPEW *kctx;
1839: PetscFunctionBegin;
1840: PetscAssertPointer(outsnes, 2);
1841: PetscCall(SNESInitializePackage());
1843: PetscCall(PetscHeaderCreate(snes, SNES_CLASSID, "SNES", "Nonlinear solver", "SNES", comm, SNESDestroy, SNESView));
1844: snes->ops->converged = SNESConvergedDefault;
1845: snes->usesksp = PETSC_TRUE;
1846: snes->norm = 0.0;
1847: snes->xnorm = 0.0;
1848: snes->ynorm = 0.0;
1849: snes->normschedule = SNES_NORM_ALWAYS;
1850: snes->functype = SNES_FUNCTION_DEFAULT;
1851: snes->ttol = 0.0;
1853: snes->rnorm0 = 0;
1854: snes->nfuncs = 0;
1855: snes->numFailures = 0;
1856: snes->maxFailures = 1;
1857: snes->linear_its = 0;
1858: snes->lagjacobian = 1;
1859: snes->jac_iter = 0;
1860: snes->lagjac_persist = PETSC_FALSE;
1861: snes->lagpreconditioner = 1;
1862: snes->pre_iter = 0;
1863: snes->lagpre_persist = PETSC_FALSE;
1864: snes->numbermonitors = 0;
1865: snes->numberreasonviews = 0;
1866: snes->data = NULL;
1867: snes->setupcalled = PETSC_FALSE;
1868: snes->ksp_ewconv = PETSC_FALSE;
1869: snes->nwork = 0;
1870: snes->work = NULL;
1871: snes->nvwork = 0;
1872: snes->vwork = NULL;
1873: snes->conv_hist_len = 0;
1874: snes->conv_hist_max = 0;
1875: snes->conv_hist = NULL;
1876: snes->conv_hist_its = NULL;
1877: snes->conv_hist_reset = PETSC_TRUE;
1878: snes->counters_reset = PETSC_TRUE;
1879: snes->vec_func_init_set = PETSC_FALSE;
1880: snes->reason = SNES_CONVERGED_ITERATING;
1881: snes->npcside = PC_RIGHT;
1882: snes->setfromoptionscalled = 0;
1884: snes->mf = PETSC_FALSE;
1885: snes->mf_operator = PETSC_FALSE;
1886: snes->mf_version = 1;
1888: snes->numLinearSolveFailures = 0;
1889: snes->maxLinearSolveFailures = 1;
1891: snes->vizerotolerance = 1.e-8;
1892: snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE;
1894: /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
1895: snes->alwayscomputesfinalresidual = PETSC_FALSE;
1897: /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
1898: PetscCall(PetscNew(&kctx));
1900: snes->kspconvctx = kctx;
1901: kctx->version = 2;
1902: kctx->rtol_0 = 0.3; /* Eisenstat and Walker suggest rtol_0=.5, but
1903: this was too large for some test cases */
1904: kctx->rtol_last = 0.0;
1905: kctx->rtol_max = 0.9;
1906: kctx->gamma = 1.0;
1907: kctx->alpha = 0.5 * (1.0 + PetscSqrtReal(5.0));
1908: kctx->alpha2 = kctx->alpha;
1909: kctx->threshold = 0.1;
1910: kctx->lresid_last = 0.0;
1911: kctx->norm_last = 0.0;
1913: kctx->rk_last = 0.0;
1914: kctx->rk_last_2 = 0.0;
1915: kctx->rtol_last_2 = 0.0;
1916: kctx->v4_p1 = 0.1;
1917: kctx->v4_p2 = 0.4;
1918: kctx->v4_p3 = 0.7;
1919: kctx->v4_m1 = 0.8;
1920: kctx->v4_m2 = 0.5;
1921: kctx->v4_m3 = 0.1;
1922: kctx->v4_m4 = 0.5;
1924: PetscCall(SNESParametersInitialize(snes));
1925: *outsnes = snes;
1926: PetscFunctionReturn(PETSC_SUCCESS);
1927: }
1929: /*@C
1930: SNESSetFunction - Sets the function evaluation routine and function
1931: vector for use by the `SNES` routines in solving systems of nonlinear
1932: equations.
1934: Logically Collective
1936: Input Parameters:
1937: + snes - the `SNES` context
1938: . r - vector to store function values, may be `NULL`
1939: . f - function evaluation routine; for calling sequence see `SNESFunctionFn`
1940: - ctx - [optional] user-defined context for private data for the
1941: function evaluation routine (may be `NULL`)
1943: Level: beginner
1945: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetPicard()`, `SNESFunctionFn`
1946: @*/
1947: PetscErrorCode SNESSetFunction(SNES snes, Vec r, SNESFunctionFn *f, PetscCtx ctx)
1948: {
1949: DM dm;
1951: PetscFunctionBegin;
1953: if (r) {
1955: PetscCheckSameComm(snes, 1, r, 2);
1956: PetscCall(PetscObjectReference((PetscObject)r));
1957: PetscCall(VecDestroy(&snes->vec_func));
1958: snes->vec_func = r;
1959: }
1960: PetscCall(SNESGetDM(snes, &dm));
1961: PetscCall(DMSNESSetFunction(dm, f, ctx));
1962: if (f == SNESPicardComputeFunction) PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
1963: PetscFunctionReturn(PETSC_SUCCESS);
1964: }
1966: /*@C
1967: SNESSetInitialFunction - Set an already computed function evaluation at the initial guess to be reused by `SNESSolve()`.
1969: Logically Collective
1971: Input Parameters:
1972: + snes - the `SNES` context
1973: - f - vector to store function value
1975: Level: developer
1977: Notes:
1978: This should not be modified during the solution procedure.
1980: This is used extensively in the `SNESFAS` hierarchy and in nonlinear preconditioning.
1982: .seealso: [](ch_snes), `SNES`, `SNESFAS`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetInitialFunctionNorm()`
1983: @*/
1984: PetscErrorCode SNESSetInitialFunction(SNES snes, Vec f)
1985: {
1986: Vec vec_func;
1988: PetscFunctionBegin;
1991: PetscCheckSameComm(snes, 1, f, 2);
1992: if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1993: snes->vec_func_init_set = PETSC_FALSE;
1994: PetscFunctionReturn(PETSC_SUCCESS);
1995: }
1996: PetscCall(SNESGetFunction(snes, &vec_func, NULL, NULL));
1997: PetscCall(VecCopy(f, vec_func));
1999: snes->vec_func_init_set = PETSC_TRUE;
2000: PetscFunctionReturn(PETSC_SUCCESS);
2001: }
2003: /*@
2004: SNESSetNormSchedule - Sets the `SNESNormSchedule` used in convergence and monitoring
2005: of the `SNES` method, when norms are computed in the solving process
2007: Logically Collective
2009: Input Parameters:
2010: + snes - the `SNES` context
2011: - normschedule - the frequency of norm computation
2013: Options Database Key:
2014: . -snes_norm_schedule (none|always|initialonly|finalonly|initialfinalonly) - set the schedule
2016: Level: advanced
2018: Notes:
2019: Only certain `SNES` methods support certain `SNESNormSchedules`. Most require evaluation
2020: of the nonlinear function and the taking of its norm at every iteration to
2021: even ensure convergence at all. However, methods such as custom Gauss-Seidel methods
2022: `SNESNGS` and the like do not require the norm of the function to be computed, and therefore
2023: may either be monitored for convergence or not. As these are often used as nonlinear
2024: preconditioners, monitoring the norm of their error is not a useful enterprise within
2025: their solution.
2027: .seealso: [](ch_snes), `SNESNormSchedule`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`
2028: @*/
2029: PetscErrorCode SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
2030: {
2031: PetscFunctionBegin;
2033: snes->normschedule = normschedule;
2034: PetscFunctionReturn(PETSC_SUCCESS);
2035: }
2037: /*@
2038: SNESGetNormSchedule - Gets the `SNESNormSchedule` used in convergence and monitoring
2039: of the `SNES` method.
2041: Logically Collective
2043: Input Parameters:
2044: + snes - the `SNES` context
2045: - normschedule - the type of the norm used
2047: Level: advanced
2049: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2050: @*/
2051: PetscErrorCode SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
2052: {
2053: PetscFunctionBegin;
2055: *normschedule = snes->normschedule;
2056: PetscFunctionReturn(PETSC_SUCCESS);
2057: }
2059: /*@
2060: SNESSetFunctionNorm - Sets the last computed residual norm.
2062: Logically Collective
2064: Input Parameters:
2065: + snes - the `SNES` context
2066: - norm - the value of the norm
2068: Level: developer
2070: .seealso: [](ch_snes), `SNES`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2071: @*/
2072: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
2073: {
2074: PetscFunctionBegin;
2076: snes->norm = norm;
2077: PetscFunctionReturn(PETSC_SUCCESS);
2078: }
2080: /*@
2081: SNESGetFunctionNorm - Gets the last computed norm of the residual
2083: Not Collective
2085: Input Parameter:
2086: . snes - the `SNES` context
2088: Output Parameter:
2089: . norm - the last computed residual norm
2091: Level: developer
2093: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2094: @*/
2095: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2096: {
2097: PetscFunctionBegin;
2099: PetscAssertPointer(norm, 2);
2100: *norm = snes->norm;
2101: PetscFunctionReturn(PETSC_SUCCESS);
2102: }
2104: /*@
2105: SNESGetUpdateNorm - Gets the last computed norm of the solution update
2107: Not Collective
2109: Input Parameter:
2110: . snes - the `SNES` context
2112: Output Parameter:
2113: . ynorm - the last computed update norm
2115: Level: developer
2117: Note:
2118: The new solution is the current solution plus the update, so this norm is an indication of the size of the update
2120: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`
2121: @*/
2122: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2123: {
2124: PetscFunctionBegin;
2126: PetscAssertPointer(ynorm, 2);
2127: *ynorm = snes->ynorm;
2128: PetscFunctionReturn(PETSC_SUCCESS);
2129: }
2131: /*@
2132: SNESGetSolutionNorm - Gets the last computed norm of the solution
2134: Not Collective
2136: Input Parameter:
2137: . snes - the `SNES` context
2139: Output Parameter:
2140: . xnorm - the last computed solution norm
2142: Level: developer
2144: .seealso: [](ch_snes), `SNES`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`, `SNESGetUpdateNorm()`
2145: @*/
2146: PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2147: {
2148: PetscFunctionBegin;
2150: PetscAssertPointer(xnorm, 2);
2151: *xnorm = snes->xnorm;
2152: PetscFunctionReturn(PETSC_SUCCESS);
2153: }
2155: /*@
2156: SNESSetFunctionType - Sets the `SNESFunctionType`
2157: of the `SNES` method.
2159: Logically Collective
2161: Input Parameters:
2162: + snes - the `SNES` context
2163: - type - the function type
2165: Level: developer
2167: Values of the function type\:
2168: + `SNES_FUNCTION_DEFAULT` - the default for the given `SNESType`
2169: . `SNES_FUNCTION_UNPRECONDITIONED` - an unpreconditioned function evaluation (this is the function provided with `SNESSetFunction()`
2170: - `SNES_FUNCTION_PRECONDITIONED` - a transformation of the function provided with `SNESSetFunction()`
2172: Note:
2173: Different `SNESType`s use this value in different ways
2175: .seealso: [](ch_snes), `SNES`, `SNESFunctionType`, `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2176: @*/
2177: PetscErrorCode SNESSetFunctionType(SNES snes, SNESFunctionType type)
2178: {
2179: PetscFunctionBegin;
2181: snes->functype = type;
2182: PetscFunctionReturn(PETSC_SUCCESS);
2183: }
2185: /*@
2186: SNESGetFunctionType - Gets the `SNESFunctionType` used in convergence and monitoring set with `SNESSetFunctionType()`
2187: of the SNES method.
2189: Logically Collective
2191: Input Parameters:
2192: + snes - the `SNES` context
2193: - type - the type of the function evaluation, see `SNESSetFunctionType()`
2195: Level: advanced
2197: .seealso: [](ch_snes), `SNESSetFunctionType()`, `SNESFunctionType`, `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2198: @*/
2199: PetscErrorCode SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2200: {
2201: PetscFunctionBegin;
2203: *type = snes->functype;
2204: PetscFunctionReturn(PETSC_SUCCESS);
2205: }
2207: /*@C
2208: SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2209: use with composed nonlinear solvers.
2211: Input Parameters:
2212: + snes - the `SNES` context, usually of the `SNESType` `SNESNGS`
2213: . f - function evaluation routine to apply Gauss-Seidel, see `SNESNGSFn` for calling sequence
2214: - ctx - [optional] user-defined context for private data for the smoother evaluation routine (may be `NULL`)
2216: Level: intermediate
2218: Note:
2219: The `SNESNGS` routines are used by the composed nonlinear solver to generate
2220: a problem appropriate update to the solution, particularly `SNESFAS`.
2222: .seealso: [](ch_snes), `SNESNGS`, `SNESGetNGS()`, `SNESNCG`, `SNESGetFunction()`, `SNESComputeNGS()`, `SNESNGSFn`
2223: @*/
2224: PetscErrorCode SNESSetNGS(SNES snes, SNESNGSFn *f, PetscCtx ctx)
2225: {
2226: DM dm;
2228: PetscFunctionBegin;
2230: PetscCall(SNESGetDM(snes, &dm));
2231: PetscCall(DMSNESSetNGS(dm, f, ctx));
2232: PetscFunctionReturn(PETSC_SUCCESS);
2233: }
2235: /*
2236: This is used for -snes_mf_operator; it uses a duplicate of snes->jacobian_pre because snes->jacobian_pre cannot be
2237: changed during the KSPSolve()
2238: */
2239: PetscErrorCode SNESPicardComputeMFFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2240: {
2241: DM dm;
2242: DMSNES sdm;
2244: PetscFunctionBegin;
2245: PetscCall(SNESGetDM(snes, &dm));
2246: PetscCall(DMGetDMSNES(dm, &sdm));
2247: /* A(x)*x - b(x) */
2248: if (sdm->ops->computepfunction) {
2249: PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2250: PetscCall(VecScale(f, -1.0));
2251: /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2252: if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre, MAT_DO_NOT_COPY_VALUES, &snes->picard));
2253: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2254: PetscCall(MatMultAdd(snes->picard, x, f, f));
2255: } else {
2256: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->picard, snes->picard, sdm->pctx));
2257: PetscCall(MatMult(snes->picard, x, f));
2258: }
2259: PetscFunctionReturn(PETSC_SUCCESS);
2260: }
2262: PetscErrorCode SNESPicardComputeFunction(SNES snes, Vec x, Vec f, PetscCtx ctx)
2263: {
2264: DM dm;
2265: DMSNES sdm;
2267: PetscFunctionBegin;
2268: PetscCall(SNESGetDM(snes, &dm));
2269: PetscCall(DMGetDMSNES(dm, &sdm));
2270: /* A(x)*x - b(x) */
2271: if (sdm->ops->computepfunction) {
2272: PetscCallBack("SNES Picard callback function", (*sdm->ops->computepfunction)(snes, x, f, sdm->pctx));
2273: PetscCall(VecScale(f, -1.0));
2274: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2275: PetscCall(MatMultAdd(snes->jacobian_pre, x, f, f));
2276: } else {
2277: PetscCallBack("SNES Picard callback Jacobian", (*sdm->ops->computepjacobian)(snes, x, snes->jacobian, snes->jacobian_pre, sdm->pctx));
2278: PetscCall(MatMult(snes->jacobian_pre, x, f));
2279: }
2280: PetscFunctionReturn(PETSC_SUCCESS);
2281: }
2283: PetscErrorCode SNESPicardComputeJacobian(SNES snes, Vec x1, Mat J, Mat B, PetscCtx ctx)
2284: {
2285: PetscFunctionBegin;
2286: /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2287: /* must assembly if matrix-free to get the last SNES solution */
2288: PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
2289: PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
2290: PetscFunctionReturn(PETSC_SUCCESS);
2291: }
2293: /*@C
2294: SNESSetPicard - Use `SNES` to solve the system $A(x) x = bp(x) + b $ via a Picard type iteration (Picard linearization)
2296: Logically Collective
2298: Input Parameters:
2299: + snes - the `SNES` context
2300: . r - vector to store function values, may be `NULL`
2301: . bp - function evaluation routine, may be `NULL`, for the calling sequence see `SNESFunctionFn`
2302: . Amat - matrix with which $A(x) x - bp(x) - b$ is to be computed
2303: . Pmat - matrix from which preconditioner is computed (usually the same as `Amat`)
2304: . J - function to compute matrix values, for the calling sequence see `SNESJacobianFn`
2305: - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
2307: Level: intermediate
2309: Notes:
2310: It is often better to provide the nonlinear function $F()$ and some approximation to its Jacobian directly and use
2311: 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.
2313: One can call `SNESSetPicard()` or `SNESSetFunction()` (and possibly `SNESSetJacobian()`) but cannot call both
2315: 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}$.
2316: When an exact solver is used this corresponds to the "classic" Picard $A(x^{n}) x^{n+1} = bp(x^{n}) + b$ iteration.
2318: Run with `-snes_mf_operator` to solve the system with Newton's method using $A(x^{n})$ to construct the preconditioner.
2320: We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
2321: the direct Picard iteration $A(x^n) x^{n+1} = bp(x^n) + b$
2323: 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
2324: 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
2325: different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument \:-).
2327: 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
2328: $A(x^{n})$ is used to build the preconditioner
2330: When used with `-snes_fd` this will compute the true Jacobian (very slowly one column at a time) and thus represent Newton's method.
2332: 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
2333: 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
2334: 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`.
2335: See the comment in src/snes/tutorials/ex15.c.
2337: .seealso: [](ch_snes), `SNES`, `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`,
2338: `SNESFunctionFn`, `SNESJacobianFn`
2339: @*/
2340: PetscErrorCode SNESSetPicard(SNES snes, Vec r, SNESFunctionFn *bp, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
2341: {
2342: DM dm;
2344: PetscFunctionBegin;
2346: PetscCall(SNESGetDM(snes, &dm));
2347: PetscCall(DMSNESSetPicard(dm, bp, J, ctx));
2348: PetscCall(DMSNESSetMFFunction(dm, SNESPicardComputeMFFunction, ctx));
2349: PetscCall(SNESSetFunction(snes, r, SNESPicardComputeFunction, ctx));
2350: PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESPicardComputeJacobian, ctx));
2351: PetscFunctionReturn(PETSC_SUCCESS);
2352: }
2354: /*@C
2355: SNESGetPicard - Returns the context for the Picard iteration
2357: Not Collective, but `Vec` is parallel if `SNES` is parallel. Collective if `Vec` is requested, but has not been created yet.
2359: Input Parameter:
2360: . snes - the `SNES` context
2362: Output Parameters:
2363: + r - the function (or `NULL`)
2364: . f - the function (or `NULL`); for calling sequence see `SNESFunctionFn`
2365: . Amat - the matrix used to defined the operation A(x) x - b(x) (or `NULL`)
2366: . Pmat - the matrix from which the preconditioner will be constructed (or `NULL`)
2367: . J - the function for matrix evaluation (or `NULL`); for calling sequence see `SNESJacobianFn`
2368: - ctx - the function context (or `NULL`)
2370: Level: advanced
2372: .seealso: [](ch_snes), `SNESSetFunction()`, `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunctionFn`, `SNESJacobianFn`
2373: @*/
2374: PetscErrorCode SNESGetPicard(SNES snes, Vec *r, SNESFunctionFn **f, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
2375: {
2376: DM dm;
2378: PetscFunctionBegin;
2380: PetscCall(SNESGetFunction(snes, r, NULL, NULL));
2381: PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
2382: PetscCall(SNESGetDM(snes, &dm));
2383: PetscCall(DMSNESGetPicard(dm, f, J, ctx));
2384: PetscFunctionReturn(PETSC_SUCCESS);
2385: }
2387: /*@C
2388: SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the nonlinear problem
2390: Logically Collective
2392: Input Parameters:
2393: + snes - the `SNES` context
2394: . func - function evaluation routine, see `SNESInitialGuessFn` for the calling sequence
2395: - ctx - [optional] user-defined context for private data for the
2396: function evaluation routine (may be `NULL`)
2398: Level: intermediate
2400: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESInitialGuessFn`
2401: @*/
2402: PetscErrorCode SNESSetComputeInitialGuess(SNES snes, SNESInitialGuessFn *func, PetscCtx ctx)
2403: {
2404: PetscFunctionBegin;
2406: if (func) snes->ops->computeinitialguess = func;
2407: if (ctx) snes->initialguessP = ctx;
2408: PetscFunctionReturn(PETSC_SUCCESS);
2409: }
2411: /*@C
2412: SNESGetRhs - Gets the vector for solving F(x) = `rhs`. If `rhs` is not set
2413: it assumes a zero right-hand side.
2415: Logically Collective
2417: Input Parameter:
2418: . snes - the `SNES` context
2420: Output Parameter:
2421: . rhs - the right-hand side vector or `NULL` if there is no right-hand side vector
2423: Level: intermediate
2425: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()`
2426: @*/
2427: PetscErrorCode SNESGetRhs(SNES snes, Vec *rhs)
2428: {
2429: PetscFunctionBegin;
2431: PetscAssertPointer(rhs, 2);
2432: *rhs = snes->vec_rhs;
2433: PetscFunctionReturn(PETSC_SUCCESS);
2434: }
2436: /*@
2437: SNESComputeFunction - Calls the function that has been set with `SNESSetFunction()`.
2439: Collective
2441: Input Parameters:
2442: + snes - the `SNES` context
2443: - x - input vector
2445: Output Parameter:
2446: . f - function vector, as set by `SNESSetFunction()`
2448: Level: developer
2450: Notes:
2451: `SNESComputeFunction()` is typically used within nonlinear solvers
2452: implementations, so users would not generally call this routine themselves.
2454: When solving for $F(x) = b$, this routine computes $f = F(x) - b$.
2456: This function usually appears in the pattern.
2457: .vb
2458: SNESComputeFunction(snes, x, f);
2459: VecNorm(f, &fnorm);
2460: SNESCheckFunctionDomainError(snes, fnorm); or SNESLineSearchCheckFunctionDomainError(ls, fnorm);
2461: .ve
2462: to collectively handle the use of `SNESSetFunctionDomainError()` in the provided callback function.
2464: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()`, `SNESSetFunctionDomainError()`
2465: @*/
2466: PetscErrorCode SNESComputeFunction(SNES snes, Vec x, Vec f)
2467: {
2468: DM dm;
2469: DMSNES sdm;
2471: PetscFunctionBegin;
2475: PetscCheckSameComm(snes, 1, x, 2);
2476: PetscCheckSameComm(snes, 1, f, 3);
2477: PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2479: PetscCall(SNESGetDM(snes, &dm));
2480: PetscCall(DMGetDMSNES(dm, &sdm));
2481: 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().");
2482: if (sdm->ops->computefunction) {
2483: if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, f, 0));
2484: PetscCall(VecLockReadPush(x));
2485: /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2486: snes->functiondomainerror = PETSC_FALSE;
2487: {
2488: void *ctx;
2489: SNESFunctionFn *computefunction;
2490: PetscCall(DMSNESGetFunction(dm, &computefunction, &ctx));
2491: PetscCallBack("SNES callback function", (*computefunction)(snes, x, f, ctx));
2492: }
2493: PetscCall(VecLockReadPop(x));
2494: if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, f, 0));
2495: } else /* if (snes->vec_rhs) */ {
2496: PetscCall(MatMult(snes->jacobian, x, f));
2497: }
2498: if (snes->vec_rhs) PetscCall(VecAXPY(f, -1.0, snes->vec_rhs));
2499: snes->nfuncs++;
2500: /*
2501: domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2502: propagate the value to all processes
2503: */
2504: PetscCall(VecFlag(f, snes->functiondomainerror));
2505: PetscFunctionReturn(PETSC_SUCCESS);
2506: }
2508: /*@
2509: SNESComputeMFFunction - Calls the function that has been set with `DMSNESSetMFFunction()`.
2511: Collective
2513: Input Parameters:
2514: + snes - the `SNES` context
2515: - x - input vector
2517: Output Parameter:
2518: . y - output vector
2520: Level: developer
2522: Notes:
2523: `SNESComputeMFFunction()` is used within the matrix-vector products called by the matrix created with `MatCreateSNESMF()`
2524: so users would not generally call this routine themselves.
2526: Since this function is intended for use with finite differencing it does not subtract the right-hand side vector provided with `SNESSolve()`
2527: while `SNESComputeFunction()` does. As such, this routine cannot be used with `MatMFFDSetBase()` with a provided F function value even if it applies the
2528: 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.
2530: .seealso: [](ch_snes), `SNES`, `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF()`, `DMSNESSetMFFunction()`
2531: @*/
2532: PetscErrorCode SNESComputeMFFunction(SNES snes, Vec x, Vec y)
2533: {
2534: DM dm;
2535: DMSNES sdm;
2537: PetscFunctionBegin;
2541: PetscCheckSameComm(snes, 1, x, 2);
2542: PetscCheckSameComm(snes, 1, y, 3);
2543: PetscCall(VecValidValues_Internal(x, 2, PETSC_TRUE));
2545: PetscCall(SNESGetDM(snes, &dm));
2546: PetscCall(DMGetDMSNES(dm, &sdm));
2547: PetscCall(PetscLogEventBegin(SNES_FunctionEval, snes, x, y, 0));
2548: PetscCall(VecLockReadPush(x));
2549: /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2550: snes->functiondomainerror = PETSC_FALSE;
2551: PetscCallBack("SNES callback function", (*sdm->ops->computemffunction)(snes, x, y, sdm->mffunctionctx));
2552: PetscCall(VecLockReadPop(x));
2553: PetscCall(PetscLogEventEnd(SNES_FunctionEval, snes, x, y, 0));
2554: snes->nfuncs++;
2555: /*
2556: domainerror might not be set on all processes; so we tag vector locally with infinity and the next inner product or norm will
2557: propagate the value to all processes
2558: */
2559: PetscCall(VecFlag(y, snes->functiondomainerror));
2560: PetscFunctionReturn(PETSC_SUCCESS);
2561: }
2563: /*@
2564: SNESComputeNGS - Calls the Gauss-Seidel function that has been set with `SNESSetNGS()`.
2566: Collective
2568: Input Parameters:
2569: + snes - the `SNES` context
2570: . x - input vector
2571: - b - rhs vector
2573: Output Parameter:
2574: . x - new solution vector
2576: Level: developer
2578: Note:
2579: `SNESComputeNGS()` is typically used within composed nonlinear solver
2580: implementations, so most users would not generally call this routine
2581: themselves.
2583: .seealso: [](ch_snes), `SNESNGSFn`, `SNESSetNGS()`, `SNESComputeFunction()`, `SNESNGS`
2584: @*/
2585: PetscErrorCode SNESComputeNGS(SNES snes, Vec b, Vec x)
2586: {
2587: DM dm;
2588: DMSNES sdm;
2590: PetscFunctionBegin;
2594: PetscCheckSameComm(snes, 1, x, 3);
2595: if (b) PetscCheckSameComm(snes, 1, b, 2);
2596: if (b) PetscCall(VecValidValues_Internal(b, 2, PETSC_TRUE));
2597: PetscCall(PetscLogEventBegin(SNES_NGSEval, snes, x, b, 0));
2598: PetscCall(SNESGetDM(snes, &dm));
2599: PetscCall(DMGetDMSNES(dm, &sdm));
2600: PetscCheck(sdm->ops->computegs, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2601: if (b) PetscCall(VecLockReadPush(b));
2602: PetscCallBack("SNES callback NGS", (*sdm->ops->computegs)(snes, x, b, sdm->gsctx));
2603: if (b) PetscCall(VecLockReadPop(b));
2604: PetscCall(PetscLogEventEnd(SNES_NGSEval, snes, x, b, 0));
2605: PetscFunctionReturn(PETSC_SUCCESS);
2606: }
2608: static PetscErrorCode SNESComputeFunction_FD(SNES snes, Vec Xin, Vec G)
2609: {
2610: Vec X;
2611: PetscScalar *g;
2612: PetscReal f, f2;
2613: PetscInt low, high, N, i;
2614: PetscBool flg;
2615: PetscReal h = .5 * PETSC_SQRT_MACHINE_EPSILON;
2617: PetscFunctionBegin;
2618: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_fd_delta", &h, &flg));
2619: PetscCall(VecDuplicate(Xin, &X));
2620: PetscCall(VecCopy(Xin, X));
2621: PetscCall(VecGetSize(X, &N));
2622: PetscCall(VecGetOwnershipRange(X, &low, &high));
2623: PetscCall(VecSetOption(X, VEC_IGNORE_OFF_PROC_ENTRIES, PETSC_TRUE));
2624: PetscCall(VecGetArray(G, &g));
2625: for (i = 0; i < N; i++) {
2626: PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2627: PetscCall(VecAssemblyBegin(X));
2628: PetscCall(VecAssemblyEnd(X));
2629: PetscCall(SNESComputeObjective(snes, X, &f));
2630: PetscCall(VecSetValue(X, i, 2.0 * h, ADD_VALUES));
2631: PetscCall(VecAssemblyBegin(X));
2632: PetscCall(VecAssemblyEnd(X));
2633: PetscCall(SNESComputeObjective(snes, X, &f2));
2634: PetscCall(VecSetValue(X, i, -h, ADD_VALUES));
2635: PetscCall(VecAssemblyBegin(X));
2636: PetscCall(VecAssemblyEnd(X));
2637: if (i >= low && i < high) g[i - low] = (f2 - f) / (2.0 * h);
2638: }
2639: PetscCall(VecRestoreArray(G, &g));
2640: PetscCall(VecDestroy(&X));
2641: PetscFunctionReturn(PETSC_SUCCESS);
2642: }
2644: /*@
2645: SNESTestFunction - Computes the difference between the computed and finite-difference functions
2647: Collective
2649: Input Parameter:
2650: . snes - the `SNES` context
2652: Options Database Keys:
2653: + -snes_test_function - compare the user provided function with one compute via finite differences to check for errors.
2654: - -snes_test_function_view - display the user provided function, the finite difference function and the difference
2656: Level: developer
2658: .seealso: [](ch_snes), `SNESTestJacobian()`, `SNESSetFunction()`, `SNESComputeFunction()`
2659: @*/
2660: PetscErrorCode SNESTestFunction(SNES snes)
2661: {
2662: Vec x, g1, g2, g3;
2663: PetscBool complete_print = PETSC_FALSE;
2664: PetscReal hcnorm, fdnorm, hcmax, fdmax, diffmax, diffnorm;
2665: PetscScalar dot;
2666: MPI_Comm comm;
2667: PetscViewer viewer, mviewer;
2668: PetscViewerFormat format;
2669: PetscInt tabs;
2670: static PetscBool directionsprinted = PETSC_FALSE;
2671: SNESObjectiveFn *objective;
2673: PetscFunctionBegin;
2674: PetscCall(SNESGetObjective(snes, &objective, NULL));
2675: if (!objective) PetscFunctionReturn(PETSC_SUCCESS);
2677: PetscObjectOptionsBegin((PetscObject)snes);
2678: PetscCall(PetscOptionsViewer("-snes_test_function_view", "View difference between hand-coded and finite difference function element entries", "None", &mviewer, &format, &complete_print));
2679: PetscOptionsEnd();
2681: PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2682: PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2683: PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2684: PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2685: PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Function -------------\n"));
2686: if (!complete_print && !directionsprinted) {
2687: PetscCall(PetscViewerASCIIPrintf(viewer, " Run with -snes_test_function_view and optionally -snes_test_function <threshold> to show difference\n"));
2688: PetscCall(PetscViewerASCIIPrintf(viewer, " of hand-coded and finite difference function entries greater than <threshold>.\n"));
2689: }
2690: if (!directionsprinted) {
2691: PetscCall(PetscViewerASCIIPrintf(viewer, " Testing hand-coded Function, if (for double precision runs) ||F - Ffd||/||F|| is\n"));
2692: PetscCall(PetscViewerASCIIPrintf(viewer, " O(1.e-8), the hand-coded Function is probably correct.\n"));
2693: directionsprinted = PETSC_TRUE;
2694: }
2695: if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));
2697: PetscCall(SNESGetSolution(snes, &x));
2698: PetscCall(VecDuplicate(x, &g1));
2699: PetscCall(VecDuplicate(x, &g2));
2700: PetscCall(VecDuplicate(x, &g3));
2701: PetscCall(SNESComputeFunction(snes, x, g1)); /* does not handle use of SNESSetFunctionDomainError() corrrectly */
2702: PetscCall(SNESComputeFunction_FD(snes, x, g2));
2704: PetscCall(VecNorm(g2, NORM_2, &fdnorm));
2705: PetscCall(VecNorm(g1, NORM_2, &hcnorm));
2706: PetscCall(VecNorm(g2, NORM_INFINITY, &fdmax));
2707: PetscCall(VecNorm(g1, NORM_INFINITY, &hcmax));
2708: PetscCall(VecDot(g1, g2, &dot));
2709: PetscCall(VecCopy(g1, g3));
2710: PetscCall(VecAXPY(g3, -1.0, g2));
2711: PetscCall(VecNorm(g3, NORM_2, &diffnorm));
2712: PetscCall(VecNorm(g3, NORM_INFINITY, &diffmax));
2713: PetscCall(PetscViewerASCIIPrintf(viewer, " ||Ffd|| %g, ||F|| = %g, angle cosine = (Ffd'F)/||Ffd||||F|| = %g\n", (double)fdnorm, (double)hcnorm, (double)(PetscRealPart(dot) / (fdnorm * hcnorm))));
2714: PetscCall(PetscViewerASCIIPrintf(viewer, " 2-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffnorm / PetscMax(hcnorm, fdnorm)), (double)diffnorm));
2715: PetscCall(PetscViewerASCIIPrintf(viewer, " max-norm ||F - Ffd||/||F|| = %g, ||F - Ffd|| = %g\n", (double)(diffmax / PetscMax(hcmax, fdmax)), (double)diffmax));
2717: if (complete_print) {
2718: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded function ----------\n"));
2719: PetscCall(VecView(g1, mviewer));
2720: PetscCall(PetscViewerASCIIPrintf(viewer, " Finite difference function ----------\n"));
2721: PetscCall(VecView(g2, mviewer));
2722: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded minus finite-difference function ----------\n"));
2723: PetscCall(VecView(g3, mviewer));
2724: }
2725: PetscCall(VecDestroy(&g1));
2726: PetscCall(VecDestroy(&g2));
2727: PetscCall(VecDestroy(&g3));
2729: if (complete_print) {
2730: PetscCall(PetscViewerPopFormat(mviewer));
2731: PetscCall(PetscViewerDestroy(&mviewer));
2732: }
2733: PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2734: PetscFunctionReturn(PETSC_SUCCESS);
2735: }
2737: /*@
2738: SNESTestJacobian - Computes the difference between the computed and finite-difference Jacobians
2740: Collective
2742: Input Parameter:
2743: . snes - the `SNES` context
2745: Output Parameters:
2746: + Jnorm - the Frobenius norm of the computed Jacobian, or `NULL`
2747: - diffNorm - the Frobenius norm of the difference of the computed and finite-difference Jacobians, or `NULL`
2749: Options Database Keys:
2750: + -snes_test_jacobian [threshold] - compare the user provided Jacobian with one compute via finite differences to check for errors. If a threshold is given, display only those entries whose difference is greater than the threshold.
2751: - -snes_test_jacobian_view - display the user provided Jacobian, the finite difference Jacobian and the difference
2753: Level: developer
2755: Note:
2756: Directions and norms are printed to stdout if `diffNorm` is `NULL`.
2758: .seealso: [](ch_snes), `SNESTestFunction()`, `SNESSetJacobian()`, `SNESComputeJacobian()`
2759: @*/
2760: PetscErrorCode SNESTestJacobian(SNES snes, PetscReal *Jnorm, PetscReal *diffNorm)
2761: {
2762: Mat A, B, C, D, jacobian;
2763: Vec x = snes->vec_sol, f;
2764: PetscReal nrm, gnorm;
2765: PetscReal threshold = 1.e-5;
2766: void *functx;
2767: PetscBool complete_print = PETSC_FALSE, threshold_print = PETSC_FALSE, flg, istranspose;
2768: PetscBool silent = diffNorm != PETSC_NULLPTR ? PETSC_TRUE : PETSC_FALSE;
2769: PetscViewer viewer, mviewer;
2770: MPI_Comm comm;
2771: PetscInt tabs;
2772: static PetscBool directionsprinted = PETSC_FALSE;
2773: PetscViewerFormat format;
2775: PetscFunctionBegin;
2776: PetscObjectOptionsBegin((PetscObject)snes);
2777: PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold, NULL));
2778: PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display", "-snes_test_jacobian_view", "3.13", NULL));
2779: PetscCall(PetscOptionsViewer("-snes_test_jacobian_view", "View difference between hand-coded and finite difference Jacobians element entries", "None", &mviewer, &format, &complete_print));
2780: PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold", "-snes_test_jacobian", "3.13", "-snes_test_jacobian accepts an optional threshold (since v3.10)"));
2781: 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));
2782: PetscOptionsEnd();
2784: PetscCall(PetscObjectGetComm((PetscObject)snes, &comm));
2785: PetscCall(PetscViewerASCIIGetStdout(comm, &viewer));
2786: PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2787: PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2788: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Jacobian -------------\n"));
2789: if (!complete_print && !silent && !directionsprinted) {
2790: PetscCall(PetscViewerASCIIPrintf(viewer, " Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
2791: PetscCall(PetscViewerASCIIPrintf(viewer, " of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
2792: }
2793: if (!directionsprinted && !silent) {
2794: PetscCall(PetscViewerASCIIPrintf(viewer, " Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
2795: PetscCall(PetscViewerASCIIPrintf(viewer, " O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
2796: directionsprinted = PETSC_TRUE;
2797: }
2798: if (complete_print) PetscCall(PetscViewerPushFormat(mviewer, format));
2800: PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian, MATMFFD, &flg));
2801: if (!flg) jacobian = snes->jacobian;
2802: else jacobian = snes->jacobian_pre;
2804: if (!x) PetscCall(MatCreateVecs(jacobian, &x, NULL));
2805: else PetscCall(PetscObjectReference((PetscObject)x));
2806: PetscCall(VecDuplicate(x, &f));
2808: /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2809: PetscCall(SNESComputeFunction(snes, x, f));
2810: PetscCall(VecDestroy(&f));
2811: PetscCall(PetscObjectTypeCompare((PetscObject)snes, SNESKSPTRANSPOSEONLY, &istranspose));
2812: while (jacobian) {
2813: Mat JT = NULL, Jsave = NULL;
2815: if (istranspose) {
2816: PetscCall(MatCreateTranspose(jacobian, &JT));
2817: Jsave = jacobian;
2818: jacobian = JT;
2819: }
2820: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
2821: if (flg) {
2822: A = jacobian;
2823: PetscCall(PetscObjectReference((PetscObject)A));
2824: } else {
2825: PetscCall(MatComputeOperator(jacobian, MATAIJ, &A));
2826: }
2828: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &B));
2829: PetscCall(MatSetOption(B, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
2831: PetscCall(SNESGetFunction(snes, NULL, NULL, &functx));
2832: PetscCall(SNESComputeJacobianDefault(snes, x, B, B, functx));
2834: PetscCall(MatDuplicate(B, MAT_COPY_VALUES, &D));
2835: PetscCall(MatAYPX(D, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2836: PetscCall(MatNorm(D, NORM_FROBENIUS, &nrm));
2837: PetscCall(MatNorm(A, NORM_FROBENIUS, &gnorm));
2838: PetscCall(MatDestroy(&D));
2839: if (!gnorm) gnorm = 1; /* just in case */
2840: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n", (double)(nrm / gnorm), (double)nrm));
2841: if (complete_print) {
2842: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded Jacobian ----------\n"));
2843: PetscCall(MatView(A, mviewer));
2844: PetscCall(PetscViewerASCIIPrintf(viewer, " Finite difference Jacobian ----------\n"));
2845: PetscCall(MatView(B, mviewer));
2846: }
2848: if (threshold_print || complete_print) {
2849: PetscInt Istart, Iend, *ccols, bncols, cncols, j, row;
2850: PetscScalar *cvals;
2851: const PetscInt *bcols;
2852: const PetscScalar *bvals;
2854: PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &C));
2855: PetscCall(MatSetOption(C, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_FALSE));
2857: PetscCall(MatAYPX(B, -1.0, A, DIFFERENT_NONZERO_PATTERN));
2858: PetscCall(MatGetOwnershipRange(B, &Istart, &Iend));
2860: for (row = Istart; row < Iend; row++) {
2861: PetscCall(MatGetRow(B, row, &bncols, &bcols, &bvals));
2862: PetscCall(PetscMalloc2(bncols, &ccols, bncols, &cvals));
2863: for (j = 0, cncols = 0; j < bncols; j++) {
2864: if (PetscAbsScalar(bvals[j]) > threshold) {
2865: ccols[cncols] = bcols[j];
2866: cvals[cncols] = bvals[j];
2867: cncols += 1;
2868: }
2869: }
2870: if (cncols) PetscCall(MatSetValues(C, 1, &row, cncols, ccols, cvals, INSERT_VALUES));
2871: PetscCall(MatRestoreRow(B, row, &bncols, &bcols, &bvals));
2872: PetscCall(PetscFree2(ccols, cvals));
2873: }
2874: PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
2875: PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
2876: PetscCall(PetscViewerASCIIPrintf(viewer, " Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n", (double)threshold));
2877: PetscCall(MatView(C, complete_print ? mviewer : viewer));
2878: PetscCall(MatDestroy(&C));
2879: }
2880: PetscCall(MatDestroy(&A));
2881: PetscCall(MatDestroy(&B));
2882: PetscCall(MatDestroy(&JT));
2883: if (Jsave) jacobian = Jsave;
2884: if (jacobian != snes->jacobian_pre) {
2885: jacobian = snes->jacobian_pre;
2886: if (!silent) PetscCall(PetscViewerASCIIPrintf(viewer, " ---------- Testing Jacobian for preconditioner -------------\n"));
2887: } else jacobian = NULL;
2888: }
2889: PetscCall(VecDestroy(&x));
2890: if (complete_print) PetscCall(PetscViewerPopFormat(mviewer));
2891: if (mviewer) PetscCall(PetscViewerDestroy(&mviewer));
2892: PetscCall(PetscViewerASCIISetTab(viewer, tabs));
2894: if (Jnorm) *Jnorm = gnorm;
2895: if (diffNorm) *diffNorm = nrm;
2896: PetscFunctionReturn(PETSC_SUCCESS);
2897: }
2899: /*@
2900: SNESComputeJacobian - Computes the Jacobian matrix that has been set with `SNESSetJacobian()`.
2902: Collective
2904: Input Parameters:
2905: + snes - the `SNES` context
2906: - X - input vector
2908: Output Parameters:
2909: + A - Jacobian matrix
2910: - B - optional matrix for building the preconditioner, usually the same as `A`
2912: Options Database Keys:
2913: + -snes_lag_preconditioner lag - how often to rebuild preconditioner
2914: . -snes_lag_jacobian lag - how often to rebuild Jacobian
2915: . -snes_test_jacobian [threshold] - compare the user provided Jacobian with one compute via finite differences to check for errors.
2916: If a threshold is given, display only those entries whose difference is greater than the threshold.
2917: . -snes_test_jacobian_view [viewer] - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian
2918: . -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2919: . -snes_compare_explicit_draw - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2920: . -snes_compare_explicit_contour - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2921: . -snes_compare_operator - Make the comparison options above use the operator instead of the matrix used to construct the preconditioner
2922: . -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2923: . -snes_compare_coloring_display - Compute the finite difference Jacobian using coloring and display verbose differences
2924: . -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2925: . -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
2926: . -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by `-snes_compare_coloring_threshold`
2927: . -snes_compare_coloring_draw - Compute the finite difference Jacobian using coloring and draw differences
2928: - -snes_compare_coloring_draw_contour - Compute the finite difference Jacobian using coloring and show contours of matrices and differences
2930: Level: developer
2932: Note:
2933: Most users should not need to explicitly call this routine, as it
2934: is used internally within the nonlinear solvers.
2936: Developer Note:
2937: This has duplicative ways of checking the accuracy of the user provided Jacobian (see the options above). This is for historical reasons, the routine `SNESTestJacobian()` use to used
2938: with the `SNESType` of test that has been removed.
2940: .seealso: [](ch_snes), `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`,
2941: `SNESSetJacobianDomainError()`, `SNESCheckJacobianDomainError()`, `SNESSetCheckJacobianDomainError()`
2942: @*/
2943: PetscErrorCode SNESComputeJacobian(SNES snes, Vec X, Mat A, Mat B)
2944: {
2945: PetscBool flag;
2946: DM dm;
2947: DMSNES sdm;
2948: KSP ksp;
2950: PetscFunctionBegin;
2953: PetscCheckSameComm(snes, 1, X, 2);
2954: PetscCall(VecValidValues_Internal(X, 2, PETSC_TRUE));
2955: PetscCall(SNESGetDM(snes, &dm));
2956: PetscCall(DMGetDMSNES(dm, &sdm));
2958: /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix-free */
2959: if (snes->lagjacobian == -2) {
2960: snes->lagjacobian = -1;
2962: PetscCall(PetscInfo(snes, "Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n"));
2963: } else if (snes->lagjacobian == -1) {
2964: PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is -1\n"));
2965: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
2966: if (flag) {
2967: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
2968: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
2969: }
2970: PetscFunctionReturn(PETSC_SUCCESS);
2971: } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2972: PetscCall(PetscInfo(snes, "Reusing Jacobian/preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagjacobian, snes->iter));
2973: PetscCall(PetscObjectTypeCompare((PetscObject)A, MATMFFD, &flag));
2974: if (flag) {
2975: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
2976: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
2977: }
2978: PetscFunctionReturn(PETSC_SUCCESS);
2979: }
2980: if (snes->npc && snes->npcside == PC_LEFT) {
2981: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
2982: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
2983: PetscFunctionReturn(PETSC_SUCCESS);
2984: }
2986: PetscCall(PetscLogEventBegin(SNES_JacobianEval, snes, X, A, B));
2987: PetscCall(VecLockReadPush(X));
2988: {
2989: void *ctx;
2990: SNESJacobianFn *J;
2991: PetscCall(DMSNESGetJacobian(dm, &J, &ctx));
2992: PetscCallBack("SNES callback Jacobian", (*J)(snes, X, A, B, ctx));
2993: }
2994: PetscCall(VecLockReadPop(X));
2995: PetscCall(PetscLogEventEnd(SNES_JacobianEval, snes, X, A, B));
2997: /* attach latest linearization point to the matrix used to construct the preconditioner */
2998: PetscCall(PetscObjectCompose((PetscObject)B, "__SNES_latest_X", (PetscObject)X));
3000: /* the next line ensures that snes->ksp exists */
3001: PetscCall(SNESGetKSP(snes, &ksp));
3002: if (snes->lagpreconditioner == -2) {
3003: PetscCall(PetscInfo(snes, "Rebuilding preconditioner exactly once since lag is -2\n"));
3004: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3005: snes->lagpreconditioner = -1;
3006: } else if (snes->lagpreconditioner == -1) {
3007: PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is -1\n"));
3008: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3009: } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
3010: PetscCall(PetscInfo(snes, "Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n", snes->lagpreconditioner, snes->iter));
3011: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_TRUE));
3012: } else {
3013: PetscCall(PetscInfo(snes, "Rebuilding preconditioner\n"));
3014: PetscCall(KSPSetReusePreconditioner(snes->ksp, PETSC_FALSE));
3015: }
3017: /* monkey business to allow testing Jacobians in multilevel solvers.
3018: This is needed because the SNESTestXXX interface does not accept vectors and matrices */
3019: {
3020: Vec xsave = snes->vec_sol;
3021: Mat jacobiansave = snes->jacobian;
3022: Mat jacobian_presave = snes->jacobian_pre;
3024: snes->vec_sol = X;
3025: snes->jacobian = A;
3026: snes->jacobian_pre = B;
3027: if (snes->testFunc) PetscCall(SNESTestFunction(snes));
3028: if (snes->testJac) PetscCall(SNESTestJacobian(snes, NULL, NULL));
3030: snes->vec_sol = xsave;
3031: snes->jacobian = jacobiansave;
3032: snes->jacobian_pre = jacobian_presave;
3033: }
3035: {
3036: PetscBool flag = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_operator = PETSC_FALSE;
3037: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit", NULL, NULL, &flag));
3038: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw", NULL, NULL, &flag_draw));
3039: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_explicit_draw_contour", NULL, NULL, &flag_contour));
3040: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_operator", NULL, NULL, &flag_operator));
3041: if (flag || flag_draw || flag_contour) {
3042: Mat Bexp_mine = NULL, Bexp, FDexp;
3043: PetscViewer vdraw, vstdout;
3044: PetscBool flg;
3045: if (flag_operator) {
3046: PetscCall(MatComputeOperator(A, MATAIJ, &Bexp_mine));
3047: Bexp = Bexp_mine;
3048: } else {
3049: /* See if the matrix used to construct the preconditioner can be viewed and added directly */
3050: PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B, &flg, MATSEQAIJ, MATMPIAIJ, MATSEQDENSE, MATMPIDENSE, MATSEQBAIJ, MATMPIBAIJ, MATSEQSBAIJ, MATMPISBAIJ, ""));
3051: if (flg) Bexp = B;
3052: else {
3053: /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
3054: PetscCall(MatComputeOperator(B, MATAIJ, &Bexp_mine));
3055: Bexp = Bexp_mine;
3056: }
3057: }
3058: PetscCall(MatConvert(Bexp, MATSAME, MAT_INITIAL_MATRIX, &FDexp));
3059: PetscCall(SNESComputeJacobianDefault(snes, X, FDexp, FDexp, NULL));
3060: PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3061: if (flag_draw || flag_contour) {
3062: PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Explicit Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3063: if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3064: } else vdraw = NULL;
3065: PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit %s\n", flag_operator ? "Jacobian" : "preconditioning Jacobian"));
3066: if (flag) PetscCall(MatView(Bexp, vstdout));
3067: if (vdraw) PetscCall(MatView(Bexp, vdraw));
3068: PetscCall(PetscViewerASCIIPrintf(vstdout, "Finite difference Jacobian\n"));
3069: if (flag) PetscCall(MatView(FDexp, vstdout));
3070: if (vdraw) PetscCall(MatView(FDexp, vdraw));
3071: PetscCall(MatAYPX(FDexp, -1.0, Bexp, SAME_NONZERO_PATTERN));
3072: PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian\n"));
3073: if (flag) PetscCall(MatView(FDexp, vstdout));
3074: if (vdraw) { /* Always use contour for the difference */
3075: PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3076: PetscCall(MatView(FDexp, vdraw));
3077: PetscCall(PetscViewerPopFormat(vdraw));
3078: }
3079: if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
3080: PetscCall(PetscViewerDestroy(&vdraw));
3081: PetscCall(MatDestroy(&Bexp_mine));
3082: PetscCall(MatDestroy(&FDexp));
3083: }
3084: }
3085: {
3086: PetscBool flag = PETSC_FALSE, flag_display = PETSC_FALSE, flag_draw = PETSC_FALSE, flag_contour = PETSC_FALSE, flag_threshold = PETSC_FALSE;
3087: PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON, threshold_rtol = 10 * PETSC_SQRT_MACHINE_EPSILON;
3088: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring", NULL, NULL, &flag));
3089: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_display", NULL, NULL, &flag_display));
3090: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw", NULL, NULL, &flag_draw));
3091: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_draw_contour", NULL, NULL, &flag_contour));
3092: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold", NULL, NULL, &flag_threshold));
3093: if (flag_threshold) {
3094: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_rtol", &threshold_rtol, NULL));
3095: PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_compare_coloring_threshold_atol", &threshold_atol, NULL));
3096: }
3097: if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
3098: Mat Bfd;
3099: PetscViewer vdraw, vstdout;
3100: MatColoring coloring;
3101: ISColoring iscoloring;
3102: MatFDColoring matfdcoloring;
3103: SNESFunctionFn *func;
3104: void *funcctx;
3105: PetscReal norm1, norm2, normmax;
3107: PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &Bfd));
3108: PetscCall(MatColoringCreate(Bfd, &coloring));
3109: PetscCall(MatColoringSetType(coloring, MATCOLORINGSL));
3110: PetscCall(MatColoringSetFromOptions(coloring));
3111: PetscCall(MatColoringApply(coloring, &iscoloring));
3112: PetscCall(MatColoringDestroy(&coloring));
3113: PetscCall(MatFDColoringCreate(Bfd, iscoloring, &matfdcoloring));
3114: PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3115: PetscCall(MatFDColoringSetUp(Bfd, iscoloring, matfdcoloring));
3116: PetscCall(ISColoringDestroy(&iscoloring));
3118: /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
3119: PetscCall(SNESGetFunction(snes, NULL, &func, &funcctx));
3120: PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)func, funcctx));
3121: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring, ((PetscObject)snes)->prefix));
3122: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring, "coloring_"));
3123: PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
3124: PetscCall(MatFDColoringApply(Bfd, matfdcoloring, X, snes));
3125: PetscCall(MatFDColoringDestroy(&matfdcoloring));
3127: PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes), &vstdout));
3128: if (flag_draw || flag_contour) {
3129: PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes), NULL, "Colored Jacobians", PETSC_DECIDE, PETSC_DECIDE, 300, 300, &vdraw));
3130: if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3131: } else vdraw = NULL;
3132: PetscCall(PetscViewerASCIIPrintf(vstdout, "Explicit preconditioning Jacobian\n"));
3133: if (flag_display) PetscCall(MatView(B, vstdout));
3134: if (vdraw) PetscCall(MatView(B, vdraw));
3135: PetscCall(PetscViewerASCIIPrintf(vstdout, "Colored Finite difference Jacobian\n"));
3136: if (flag_display) PetscCall(MatView(Bfd, vstdout));
3137: if (vdraw) PetscCall(MatView(Bfd, vdraw));
3138: PetscCall(MatAYPX(Bfd, -1.0, B, SAME_NONZERO_PATTERN));
3139: PetscCall(MatNorm(Bfd, NORM_1, &norm1));
3140: PetscCall(MatNorm(Bfd, NORM_FROBENIUS, &norm2));
3141: PetscCall(MatNorm(Bfd, NORM_MAX, &normmax));
3142: PetscCall(PetscViewerASCIIPrintf(vstdout, "User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n", (double)norm1, (double)norm2, (double)normmax));
3143: if (flag_display) PetscCall(MatView(Bfd, vstdout));
3144: if (vdraw) { /* Always use contour for the difference */
3145: PetscCall(PetscViewerPushFormat(vdraw, PETSC_VIEWER_DRAW_CONTOUR));
3146: PetscCall(MatView(Bfd, vdraw));
3147: PetscCall(PetscViewerPopFormat(vdraw));
3148: }
3149: if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
3151: if (flag_threshold) {
3152: PetscInt bs, rstart, rend, i;
3153: PetscCall(MatGetBlockSize(B, &bs));
3154: PetscCall(MatGetOwnershipRange(B, &rstart, &rend));
3155: for (i = rstart; i < rend; i++) {
3156: const PetscScalar *ba, *ca;
3157: const PetscInt *bj, *cj;
3158: PetscInt bn, cn, j, maxentrycol = -1, maxdiffcol = -1, maxrdiffcol = -1;
3159: PetscReal maxentry = 0, maxdiff = 0, maxrdiff = 0;
3160: PetscCall(MatGetRow(B, i, &bn, &bj, &ba));
3161: PetscCall(MatGetRow(Bfd, i, &cn, &cj, &ca));
3162: PetscCheck(bn == cn, ((PetscObject)A)->comm, PETSC_ERR_PLIB, "Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
3163: for (j = 0; j < bn; j++) {
3164: PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3165: if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
3166: maxentrycol = bj[j];
3167: maxentry = PetscRealPart(ba[j]);
3168: }
3169: if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
3170: maxdiffcol = bj[j];
3171: maxdiff = PetscRealPart(ca[j]);
3172: }
3173: if (rdiff > maxrdiff) {
3174: maxrdiffcol = bj[j];
3175: maxrdiff = rdiff;
3176: }
3177: }
3178: if (maxrdiff > 1) {
3179: 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));
3180: for (j = 0; j < bn; j++) {
3181: PetscReal rdiff;
3182: rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol * PetscAbsScalar(ba[j]));
3183: if (rdiff > 1) PetscCall(PetscViewerASCIIPrintf(vstdout, " (%" PetscInt_FMT ",%g:%g)", bj[j], (double)PetscRealPart(ba[j]), (double)PetscRealPart(ca[j])));
3184: }
3185: PetscCall(PetscViewerASCIIPrintf(vstdout, "\n"));
3186: }
3187: PetscCall(MatRestoreRow(B, i, &bn, &bj, &ba));
3188: PetscCall(MatRestoreRow(Bfd, i, &cn, &cj, &ca));
3189: }
3190: }
3191: PetscCall(PetscViewerDestroy(&vdraw));
3192: PetscCall(MatDestroy(&Bfd));
3193: }
3194: }
3195: PetscFunctionReturn(PETSC_SUCCESS);
3196: }
3198: /*@C
3199: SNESSetJacobian - Sets the function to compute Jacobian as well as the
3200: location to store the matrix.
3202: Logically Collective
3204: Input Parameters:
3205: + snes - the `SNES` context
3206: . Amat - the matrix that defines the (approximate) Jacobian
3207: . Pmat - the matrix to be used in constructing the preconditioner, usually the same as `Amat`.
3208: . J - Jacobian evaluation routine (if `NULL` then `SNES` retains any previously set value), see `SNESJacobianFn` for details
3209: - ctx - [optional] user-defined context for private data for the
3210: Jacobian evaluation routine (may be `NULL`) (if `NULL` then `SNES` retains any previously set value)
3212: Level: beginner
3214: Notes:
3215: If the `Amat` matrix and `Pmat` matrix are different you must call `MatAssemblyBegin()`/`MatAssemblyEnd()` on
3216: each matrix.
3218: If you know the operator `Amat` has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
3219: space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
3221: If using `SNESComputeJacobianDefaultColor()` to assemble a Jacobian, the `ctx` argument
3222: must be a `MatFDColoring`.
3224: Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian. One common
3225: example is to use the "Picard linearization" which only differentiates through the highest order parts of each term using `SNESSetPicard()`
3227: .seealso: [](ch_snes), `SNES`, `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`,
3228: `SNESSetPicard()`, `SNESJacobianFn`, `SNESFunctionFn`
3229: @*/
3230: PetscErrorCode SNESSetJacobian(SNES snes, Mat Amat, Mat Pmat, SNESJacobianFn *J, PetscCtx ctx)
3231: {
3232: DM dm;
3234: PetscFunctionBegin;
3238: if (Amat) PetscCheckSameComm(snes, 1, Amat, 2);
3239: if (Pmat) PetscCheckSameComm(snes, 1, Pmat, 3);
3240: PetscCall(SNESGetDM(snes, &dm));
3241: PetscCall(DMSNESSetJacobian(dm, J, ctx));
3242: if (Amat) {
3243: PetscCall(PetscObjectReference((PetscObject)Amat));
3244: PetscCall(MatDestroy(&snes->jacobian));
3246: snes->jacobian = Amat;
3247: }
3248: if (Pmat) {
3249: PetscCall(PetscObjectReference((PetscObject)Pmat));
3250: PetscCall(MatDestroy(&snes->jacobian_pre));
3252: snes->jacobian_pre = Pmat;
3253: }
3254: PetscFunctionReturn(PETSC_SUCCESS);
3255: }
3257: /*@C
3258: SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3259: provided context for evaluating the Jacobian.
3261: Not Collective, but `Mat` object will be parallel if `SNES` is
3263: Input Parameter:
3264: . snes - the nonlinear solver context
3266: Output Parameters:
3267: + Amat - location to stash (approximate) Jacobian matrix (or `NULL`)
3268: . Pmat - location to stash matrix used to compute the preconditioner (or `NULL`)
3269: . J - location to put Jacobian function (or `NULL`), for calling sequence see `SNESJacobianFn`
3270: - ctx - location to stash Jacobian ctx (or `NULL`)
3272: Level: advanced
3274: .seealso: [](ch_snes), `SNES`, `Mat`, `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFn`, `SNESGetFunction()`
3275: @*/
3276: PetscErrorCode SNESGetJacobian(SNES snes, Mat *Amat, Mat *Pmat, SNESJacobianFn **J, PetscCtxRt ctx)
3277: {
3278: DM dm;
3280: PetscFunctionBegin;
3282: if (Amat) *Amat = snes->jacobian;
3283: if (Pmat) *Pmat = snes->jacobian_pre;
3284: PetscCall(SNESGetDM(snes, &dm));
3285: PetscCall(DMSNESGetJacobian(dm, J, ctx));
3286: PetscFunctionReturn(PETSC_SUCCESS);
3287: }
3289: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3290: {
3291: DM dm;
3292: DMSNES sdm;
3294: PetscFunctionBegin;
3295: PetscCall(SNESGetDM(snes, &dm));
3296: PetscCall(DMGetDMSNES(dm, &sdm));
3297: if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3298: DM dm;
3299: PetscBool isdense, ismf;
3301: PetscCall(SNESGetDM(snes, &dm));
3302: PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &isdense, MATSEQDENSE, MATMPIDENSE, MATDENSE, NULL));
3303: PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre, &ismf, MATMFFD, MATSHELL, NULL));
3304: if (isdense) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefault, NULL));
3305: else if (!ismf) PetscCall(DMSNESSetJacobian(dm, SNESComputeJacobianDefaultColor, NULL));
3306: }
3307: PetscFunctionReturn(PETSC_SUCCESS);
3308: }
3310: /*@
3311: SNESSetUp - Sets up the internal data structures for the later use
3312: of a nonlinear solver `SNESSolve()`.
3314: Collective
3316: Input Parameter:
3317: . snes - the `SNES` context
3319: Level: advanced
3321: Note:
3322: For basic use of the `SNES` solvers the user does not need to explicitly call
3323: `SNESSetUp()`, since these actions will automatically occur during
3324: the call to `SNESSolve()`. However, if one wishes to control this
3325: phase separately, `SNESSetUp()` should be called after `SNESCreate()`
3326: and optional routines of the form SNESSetXXX(), but before `SNESSolve()`.
3328: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`, `SNESDestroy()`, `SNESSetFromOptions()`
3329: @*/
3330: PetscErrorCode SNESSetUp(SNES snes)
3331: {
3332: DM dm;
3333: DMSNES sdm;
3334: SNESLineSearch linesearch, pclinesearch;
3335: void *lsprectx, *lspostctx;
3336: PetscBool mf_operator, mf;
3337: Vec f, fpc;
3338: void *funcctx;
3339: void *jacctx, *appctx;
3340: Mat j, jpre;
3341: PetscErrorCode (*precheck)(SNESLineSearch, Vec, Vec, PetscBool *, PetscCtx);
3342: PetscErrorCode (*postcheck)(SNESLineSearch, Vec, Vec, Vec, PetscBool *, PetscBool *, PetscCtx);
3343: SNESFunctionFn *func;
3344: SNESJacobianFn *jac;
3346: PetscFunctionBegin;
3348: if (snes->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
3349: PetscCall(PetscLogEventBegin(SNES_SetUp, snes, 0, 0, 0));
3351: if (!((PetscObject)snes)->type_name) PetscCall(SNESSetType(snes, SNESNEWTONLS));
3353: PetscCall(SNESGetFunction(snes, &snes->vec_func, NULL, NULL));
3355: PetscCall(SNESGetDM(snes, &dm));
3356: PetscCall(DMGetDMSNES(dm, &sdm));
3357: PetscCall(SNESSetDefaultComputeJacobian(snes));
3359: if (!snes->vec_func) PetscCall(DMCreateGlobalVector(dm, &snes->vec_func));
3361: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
3363: if (snes->linesearch) {
3364: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
3365: PetscCall(SNESLineSearchSetFunction(snes->linesearch, SNESComputeFunction));
3366: }
3368: PetscCall(SNESGetUseMatrixFree(snes, &mf_operator, &mf));
3369: if (snes->npc && snes->npcside == PC_LEFT) {
3370: snes->mf = PETSC_TRUE;
3371: snes->mf_operator = PETSC_FALSE;
3372: }
3374: if (snes->npc) {
3375: /* copy the DM over */
3376: PetscCall(SNESGetDM(snes, &dm));
3377: PetscCall(SNESSetDM(snes->npc, dm));
3379: PetscCall(SNESGetFunction(snes, &f, &func, &funcctx));
3380: PetscCall(VecDuplicate(f, &fpc));
3381: PetscCall(SNESSetFunction(snes->npc, fpc, func, funcctx));
3382: PetscCall(SNESGetJacobian(snes, &j, &jpre, &jac, &jacctx));
3383: PetscCall(SNESSetJacobian(snes->npc, j, jpre, jac, jacctx));
3384: PetscCall(SNESGetApplicationContext(snes, &appctx));
3385: PetscCall(SNESSetApplicationContext(snes->npc, appctx));
3386: PetscCall(SNESSetUseMatrixFree(snes->npc, mf_operator, mf));
3387: PetscCall(VecDestroy(&fpc));
3389: /* copy the function pointers over */
3390: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)snes, (PetscObject)snes->npc));
3392: /* default to 1 iteration */
3393: PetscCall(SNESSetTolerances(snes->npc, 0.0, 0.0, 0.0, 1, snes->npc->max_funcs));
3394: if (snes->npcside == PC_RIGHT) {
3395: PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_FINAL_ONLY));
3396: } else {
3397: PetscCall(SNESSetNormSchedule(snes->npc, SNES_NORM_NONE));
3398: }
3399: PetscCall(SNESSetFromOptions(snes->npc));
3401: /* copy the line search context over */
3402: if (snes->linesearch && snes->npc->linesearch) {
3403: PetscCall(SNESGetLineSearch(snes, &linesearch));
3404: PetscCall(SNESGetLineSearch(snes->npc, &pclinesearch));
3405: PetscCall(SNESLineSearchGetPreCheck(linesearch, &precheck, &lsprectx));
3406: PetscCall(SNESLineSearchGetPostCheck(linesearch, &postcheck, &lspostctx));
3407: PetscCall(SNESLineSearchSetPreCheck(pclinesearch, precheck, lsprectx));
3408: PetscCall(SNESLineSearchSetPostCheck(pclinesearch, postcheck, lspostctx));
3409: PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
3410: }
3411: }
3412: if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));
3413: if (snes->ops->ctxcompute && !snes->ctx) PetscCallBack("SNES callback compute application context", (*snes->ops->ctxcompute)(snes, &snes->ctx));
3415: snes->jac_iter = 0;
3416: snes->pre_iter = 0;
3418: PetscTryTypeMethod(snes, setup);
3420: PetscCall(SNESSetDefaultComputeJacobian(snes));
3422: if (snes->npc && snes->npcside == PC_LEFT) {
3423: if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3424: if (snes->linesearch) {
3425: PetscCall(SNESGetLineSearch(snes, &linesearch));
3426: PetscCall(SNESLineSearchSetFunction(linesearch, SNESComputeFunctionDefaultNPC));
3427: }
3428: }
3429: }
3430: PetscCall(PetscLogEventEnd(SNES_SetUp, snes, 0, 0, 0));
3431: snes->setupcalled = PETSC_TRUE;
3432: PetscFunctionReturn(PETSC_SUCCESS);
3433: }
3435: /*@
3436: 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
3438: Collective
3440: Input Parameter:
3441: . snes - the nonlinear iterative solver context obtained from `SNESCreate()`
3443: Level: intermediate
3445: Notes:
3446: Any options set on the `SNES` object, including those set with `SNESSetFromOptions()` remain.
3448: Call this if you wish to reuse a `SNES` but with different size vectors
3450: Also calls the application context destroy routine set with `SNESSetComputeApplicationContext()`
3452: .seealso: [](ch_snes), `SNES`, `SNESDestroy()`, `SNESCreate()`, `SNESSetUp()`, `SNESSolve()`
3453: @*/
3454: PetscErrorCode SNESReset(SNES snes)
3455: {
3456: PetscFunctionBegin;
3458: if (snes->ops->ctxdestroy && snes->ctx) {
3459: PetscCallBack("SNES callback destroy application context", (*snes->ops->ctxdestroy)(&snes->ctx));
3460: snes->ctx = NULL;
3461: }
3462: if (snes->npc) PetscCall(SNESReset(snes->npc));
3464: PetscTryTypeMethod(snes, reset);
3465: if (snes->ksp) PetscCall(KSPReset(snes->ksp));
3467: if (snes->linesearch) PetscCall(SNESLineSearchReset(snes->linesearch));
3469: PetscCall(VecDestroy(&snes->vec_rhs));
3470: PetscCall(VecDestroy(&snes->vec_sol));
3471: PetscCall(VecDestroy(&snes->vec_sol_update));
3472: PetscCall(VecDestroy(&snes->vec_func));
3473: PetscCall(MatDestroy(&snes->jacobian));
3474: PetscCall(MatDestroy(&snes->jacobian_pre));
3475: PetscCall(MatDestroy(&snes->picard));
3476: PetscCall(VecDestroyVecs(snes->nwork, &snes->work));
3477: PetscCall(VecDestroyVecs(snes->nvwork, &snes->vwork));
3479: snes->alwayscomputesfinalresidual = PETSC_FALSE;
3481: snes->nwork = snes->nvwork = 0;
3482: snes->setupcalled = PETSC_FALSE;
3483: PetscFunctionReturn(PETSC_SUCCESS);
3484: }
3486: /*@
3487: SNESConvergedReasonViewCancel - Clears all the reason view functions for a `SNES` object provided with `SNESConvergedReasonViewSet()` also
3488: removes the default viewer.
3490: Collective
3492: Input Parameter:
3493: . snes - the nonlinear iterative solver context obtained from `SNESCreate()`
3495: Level: intermediate
3497: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESReset()`, `SNESConvergedReasonViewSet()`
3498: @*/
3499: PetscErrorCode SNESConvergedReasonViewCancel(SNES snes)
3500: {
3501: PetscInt i;
3503: PetscFunctionBegin;
3505: for (i = 0; i < snes->numberreasonviews; i++) {
3506: if (snes->reasonviewdestroy[i]) PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3507: }
3508: snes->numberreasonviews = 0;
3509: PetscCall(PetscViewerDestroy(&snes->convergedreasonviewer));
3510: PetscFunctionReturn(PETSC_SUCCESS);
3511: }
3513: /*@
3514: SNESDestroy - Destroys the nonlinear solver context that was created
3515: with `SNESCreate()`.
3517: Collective
3519: Input Parameter:
3520: . snes - the `SNES` context
3522: Level: beginner
3524: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESSolve()`
3525: @*/
3526: PetscErrorCode SNESDestroy(SNES *snes)
3527: {
3528: DM dm;
3530: PetscFunctionBegin;
3531: if (!*snes) PetscFunctionReturn(PETSC_SUCCESS);
3533: if (--((PetscObject)*snes)->refct > 0) {
3534: *snes = NULL;
3535: PetscFunctionReturn(PETSC_SUCCESS);
3536: }
3538: PetscCall(SNESReset(*snes));
3539: PetscCall(SNESDestroy(&(*snes)->npc));
3541: /* if memory was published with SAWs then destroy it */
3542: PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
3543: PetscTryTypeMethod(*snes, destroy);
3545: dm = (*snes)->dm;
3546: while (dm) {
3547: PetscCall(DMCoarsenHookRemove(dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, *snes));
3548: PetscCall(DMGetCoarseDM(dm, &dm));
3549: }
3551: PetscCall(DMDestroy(&(*snes)->dm));
3552: PetscCall(KSPDestroy(&(*snes)->ksp));
3553: PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));
3555: PetscCall(PetscFree((*snes)->kspconvctx));
3556: if ((*snes)->ops->convergeddestroy) PetscCall((*(*snes)->ops->convergeddestroy)(&(*snes)->cnvP));
3557: if ((*snes)->conv_hist_alloc) PetscCall(PetscFree2((*snes)->conv_hist, (*snes)->conv_hist_its));
3558: PetscCall(SNESMonitorCancel(*snes));
3559: PetscCall(SNESConvergedReasonViewCancel(*snes));
3560: PetscCall(PetscHeaderDestroy(snes));
3561: PetscFunctionReturn(PETSC_SUCCESS);
3562: }
3564: /* ----------- Routines to set solver parameters ---------- */
3566: /*@
3567: SNESSetLagPreconditioner - Sets when the preconditioner is rebuilt in the nonlinear solve `SNESSolve()`.
3569: Logically Collective
3571: Input Parameters:
3572: + snes - the `SNES` context
3573: - lag - 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3574: the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3576: Options Database Keys:
3577: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3578: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3579: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple `SNESSolve()`
3580: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3582: Level: intermediate
3584: Notes:
3585: The default is 1
3587: The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or `SNESSetLagPreconditionerPersists()` was called
3589: `SNESSetLagPreconditionerPersists()` allows using the same uniform lagging (for example every second linear solve) across multiple nonlinear solves.
3591: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`,
3592: `SNESSetLagJacobianPersists()`, `SNES`, `SNESSolve()`
3593: @*/
3594: PetscErrorCode SNESSetLagPreconditioner(SNES snes, PetscInt lag)
3595: {
3596: PetscFunctionBegin;
3598: PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3599: PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3601: snes->lagpreconditioner = lag;
3602: PetscFunctionReturn(PETSC_SUCCESS);
3603: }
3605: /*@
3606: SNESSetGridSequence - sets the number of steps of grid sequencing that `SNES` will do
3608: Logically Collective
3610: Input Parameters:
3611: + snes - the `SNES` context
3612: - steps - the number of refinements to do, defaults to 0
3614: Options Database Key:
3615: . -snes_grid_sequence steps - Use grid sequencing to generate initial guess
3617: Level: intermediate
3619: Notes:
3620: Once grid sequencing is turned on `SNESSolve()` will automatically perform the solve on each grid refinement.
3622: Use `SNESGetSolution()` to extract the fine grid solution after grid sequencing.
3624: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`,
3625: `SNESSetDM()`, `SNESSolve()`
3626: @*/
3627: PetscErrorCode SNESSetGridSequence(SNES snes, PetscInt steps)
3628: {
3629: PetscFunctionBegin;
3632: snes->gridsequence = steps;
3633: PetscFunctionReturn(PETSC_SUCCESS);
3634: }
3636: /*@
3637: SNESGetGridSequence - gets the number of steps of grid sequencing that `SNES` will do
3639: Logically Collective
3641: Input Parameter:
3642: . snes - the `SNES` context
3644: Output Parameter:
3645: . steps - the number of refinements to do, defaults to 0
3647: Level: intermediate
3649: .seealso: [](ch_snes), `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()`
3650: @*/
3651: PetscErrorCode SNESGetGridSequence(SNES snes, PetscInt *steps)
3652: {
3653: PetscFunctionBegin;
3655: *steps = snes->gridsequence;
3656: PetscFunctionReturn(PETSC_SUCCESS);
3657: }
3659: /*@
3660: SNESGetLagPreconditioner - Return how often the preconditioner is rebuilt
3662: Not Collective
3664: Input Parameter:
3665: . snes - the `SNES` context
3667: Output Parameter:
3668: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3669: the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3671: Level: intermediate
3673: Notes:
3674: The default is 1
3676: The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3678: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3679: @*/
3680: PetscErrorCode SNESGetLagPreconditioner(SNES snes, PetscInt *lag)
3681: {
3682: PetscFunctionBegin;
3684: *lag = snes->lagpreconditioner;
3685: PetscFunctionReturn(PETSC_SUCCESS);
3686: }
3688: /*@
3689: SNESSetLagJacobian - Set when the Jacobian is rebuilt in the nonlinear solve. See `SNESSetLagPreconditioner()` for determining how
3690: often the preconditioner is rebuilt.
3692: Logically Collective
3694: Input Parameters:
3695: + snes - the `SNES` context
3696: - lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3697: the Jacobian is built etc. -2 means rebuild at next chance but then never again
3699: Options Database Keys:
3700: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3701: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3702: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3703: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag.
3705: Level: intermediate
3707: Notes:
3708: The default is 1
3710: The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3712: 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
3713: at the next Newton step but never again (unless it is reset to another value)
3715: .seealso: [](ch_snes), `SNES`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3716: @*/
3717: PetscErrorCode SNESSetLagJacobian(SNES snes, PetscInt lag)
3718: {
3719: PetscFunctionBegin;
3721: PetscCheck(lag >= -2, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag must be -2, -1, 1 or greater");
3722: PetscCheck(lag, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Lag cannot be 0");
3724: snes->lagjacobian = lag;
3725: PetscFunctionReturn(PETSC_SUCCESS);
3726: }
3728: /*@
3729: SNESGetLagJacobian - Get how often the Jacobian is rebuilt. See `SNESGetLagPreconditioner()` to determine when the preconditioner is rebuilt
3731: Not Collective
3733: Input Parameter:
3734: . snes - the `SNES` context
3736: Output Parameter:
3737: . lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3738: the Jacobian is built etc.
3740: Level: intermediate
3742: Notes:
3743: The default is 1
3745: The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or `SNESSetLagJacobianPersists()` was called.
3747: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobian()`, `SNESSetLagPreconditioner()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3748: @*/
3749: PetscErrorCode SNESGetLagJacobian(SNES snes, PetscInt *lag)
3750: {
3751: PetscFunctionBegin;
3753: *lag = snes->lagjacobian;
3754: PetscFunctionReturn(PETSC_SUCCESS);
3755: }
3757: /*@
3758: SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple nonlinear solves
3760: Logically collective
3762: Input Parameters:
3763: + snes - the `SNES` context
3764: - flg - jacobian lagging persists if true
3766: Options Database Keys:
3767: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3768: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3769: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3770: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3772: Level: advanced
3774: Notes:
3775: Normally when `SNESSetLagJacobian()` is used, the Jacobian is always rebuilt at the beginning of each new nonlinear solve, this removes that behavior
3777: This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
3778: several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
3779: timesteps may present huge efficiency gains.
3781: .seealso: [](ch_snes), `SNES`, `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`
3782: @*/
3783: PetscErrorCode SNESSetLagJacobianPersists(SNES snes, PetscBool flg)
3784: {
3785: PetscFunctionBegin;
3788: snes->lagjac_persist = flg;
3789: PetscFunctionReturn(PETSC_SUCCESS);
3790: }
3792: /*@
3793: SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves
3795: Logically Collective
3797: Input Parameters:
3798: + snes - the `SNES` context
3799: - flg - preconditioner lagging persists if true
3801: Options Database Keys:
3802: + -snes_lag_jacobian_persists (true|false) - sets the persistence through multiple SNES solves
3803: . -snes_lag_jacobian (-2|1|2|...) - sets the lag
3804: . -snes_lag_preconditioner_persists (true|false) - sets the persistence through multiple SNES solves
3805: - -snes_lag_preconditioner (-2|1|2|...) - sets the lag
3807: Level: developer
3809: Notes:
3810: Normally when `SNESSetLagPreconditioner()` is used, the preconditioner is always rebuilt at the beginning of each new nonlinear solve, this removes that behavior
3812: This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
3813: by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
3814: several timesteps may present huge efficiency gains.
3816: .seealso: [](ch_snes), `SNES`, `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
3817: @*/
3818: PetscErrorCode SNESSetLagPreconditionerPersists(SNES snes, PetscBool flg)
3819: {
3820: PetscFunctionBegin;
3823: snes->lagpre_persist = flg;
3824: PetscFunctionReturn(PETSC_SUCCESS);
3825: }
3827: /*@
3828: SNESSetForceIteration - force `SNESSolve()` to take at least one iteration regardless of the initial residual norm
3830: Logically Collective
3832: Input Parameters:
3833: + snes - the `SNES` context
3834: - force - `PETSC_TRUE` require at least one iteration
3836: Options Database Key:
3837: . -snes_force_iteration force - Sets forcing an iteration
3839: Level: intermediate
3841: Note:
3842: This is used sometimes with `TS` to prevent `TS` from detecting a false steady state solution
3844: .seealso: [](ch_snes), `SNES`, `TS`, `SNESSetDivergenceTolerance()`
3845: @*/
3846: PetscErrorCode SNESSetForceIteration(SNES snes, PetscBool force)
3847: {
3848: PetscFunctionBegin;
3850: snes->forceiteration = force;
3851: PetscFunctionReturn(PETSC_SUCCESS);
3852: }
3854: /*@
3855: SNESGetForceIteration - Check whether or not `SNESSolve()` take at least one iteration regardless of the initial residual norm
3857: Logically Collective
3859: Input Parameter:
3860: . snes - the `SNES` context
3862: Output Parameter:
3863: . force - `PETSC_TRUE` requires at least one iteration.
3865: Level: intermediate
3867: .seealso: [](ch_snes), `SNES`, `SNESSetForceIteration()`, `SNESSetDivergenceTolerance()`
3868: @*/
3869: PetscErrorCode SNESGetForceIteration(SNES snes, PetscBool *force)
3870: {
3871: PetscFunctionBegin;
3873: *force = snes->forceiteration;
3874: PetscFunctionReturn(PETSC_SUCCESS);
3875: }
3877: /*@
3878: SNESSetTolerances - Sets various parameters used in `SNES` convergence tests.
3880: Logically Collective
3882: Input Parameters:
3883: + snes - the `SNES` context
3884: . abstol - the absolute convergence tolerance, $ F(x^n) \le abstol $
3885: . rtol - the relative convergence tolerance, $ F(x^n) \le reltol * F(x^0) $
3886: . stol - convergence tolerance in terms of the norm of the change in the solution between steps, || delta x || < stol*|| x ||
3887: . maxit - the maximum number of iterations allowed in the solver, default 50.
3888: - maxf - the maximum number of function evaluations allowed in the solver (use `PETSC_UNLIMITED` indicates no limit), default 10,000
3890: Options Database Keys:
3891: + -snes_atol abstol - Sets `abstol`
3892: . -snes_rtol rtol - Sets `rtol`
3893: . -snes_stol stol - Sets `stol`
3894: . -snes_max_it maxit - Sets `maxit`
3895: - -snes_max_funcs maxf - Sets `maxf` (use `unlimited` to have no maximum)
3897: Level: intermediate
3899: Note:
3900: All parameters must be non-negative
3902: Use `PETSC_CURRENT` to retain the current value of any parameter and `PETSC_DETERMINE` to use the default value for the given `SNES`.
3903: The default value is the value in the object when its type is set.
3905: Use `PETSC_UNLIMITED` on `maxit` or `maxf` to indicate there is no bound on the number of iterations or number of function evaluations.
3907: Fortran Note:
3908: Use `PETSC_CURRENT_INTEGER`, `PETSC_CURRENT_REAL`, `PETSC_UNLIMITED_INTEGER`, `PETSC_DETERMINE_INTEGER`, or `PETSC_DETERMINE_REAL`
3910: .seealso: [](ch_snes), `SNESSolve()`, `SNES`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()`
3911: @*/
3912: PetscErrorCode SNESSetTolerances(SNES snes, PetscReal abstol, PetscReal rtol, PetscReal stol, PetscInt maxit, PetscInt maxf)
3913: {
3914: PetscFunctionBegin;
3922: if (abstol == (PetscReal)PETSC_DETERMINE) {
3923: snes->abstol = snes->default_abstol;
3924: } else if (abstol != (PetscReal)PETSC_CURRENT) {
3925: PetscCheck(abstol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)abstol);
3926: snes->abstol = abstol;
3927: }
3929: if (rtol == (PetscReal)PETSC_DETERMINE) {
3930: snes->rtol = snes->default_rtol;
3931: } else if (rtol != (PetscReal)PETSC_CURRENT) {
3932: 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);
3933: snes->rtol = rtol;
3934: }
3936: if (stol == (PetscReal)PETSC_DETERMINE) {
3937: snes->stol = snes->default_stol;
3938: } else if (stol != (PetscReal)PETSC_CURRENT) {
3939: PetscCheck(stol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Step tolerance %g must be non-negative", (double)stol);
3940: snes->stol = stol;
3941: }
3943: if (maxit == PETSC_DETERMINE) {
3944: snes->max_its = snes->default_max_its;
3945: } else if (maxit == PETSC_UNLIMITED) {
3946: snes->max_its = PETSC_INT_MAX;
3947: } else if (maxit != PETSC_CURRENT) {
3948: PetscCheck(maxit >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of iterations %" PetscInt_FMT " must be non-negative", maxit);
3949: snes->max_its = maxit;
3950: }
3952: if (maxf == PETSC_DETERMINE) {
3953: snes->max_funcs = snes->default_max_funcs;
3954: } else if (maxf == PETSC_UNLIMITED || maxf == -1) {
3955: snes->max_funcs = PETSC_UNLIMITED;
3956: } else if (maxf != PETSC_CURRENT) {
3957: PetscCheck(maxf >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of function evaluations %" PetscInt_FMT " must be nonnegative", maxf);
3958: snes->max_funcs = maxf;
3959: }
3960: PetscFunctionReturn(PETSC_SUCCESS);
3961: }
3963: /*@
3964: SNESSetDivergenceTolerance - Sets the divergence tolerance used for the `SNES` divergence test.
3966: Logically Collective
3968: Input Parameters:
3969: + snes - the `SNES` context
3970: - 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
3971: is stopped due to divergence.
3973: Options Database Key:
3974: . -snes_divergence_tolerance divtol - Sets `divtol`
3976: Level: intermediate
3978: Notes:
3979: Use `PETSC_DETERMINE` to use the default value from when the object's type was set.
3981: Fortran Note:
3982: Use ``PETSC_DETERMINE_REAL` or `PETSC_UNLIMITED_REAL`
3984: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetTolerances()`, `SNESGetDivergenceTolerance()`
3985: @*/
3986: PetscErrorCode SNESSetDivergenceTolerance(SNES snes, PetscReal divtol)
3987: {
3988: PetscFunctionBegin;
3992: if (divtol == (PetscReal)PETSC_DETERMINE) {
3993: snes->divtol = snes->default_divtol;
3994: } else if (divtol == (PetscReal)PETSC_UNLIMITED || divtol == -1) {
3995: snes->divtol = PETSC_UNLIMITED;
3996: } else if (divtol != (PetscReal)PETSC_CURRENT) {
3997: PetscCheck(divtol >= 1.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Divergence tolerance %g must be greater than 1.0", (double)divtol);
3998: snes->divtol = divtol;
3999: }
4000: PetscFunctionReturn(PETSC_SUCCESS);
4001: }
4003: /*@
4004: SNESGetTolerances - Gets various parameters used in `SNES` convergence tests.
4006: Not Collective
4008: Input Parameter:
4009: . snes - the `SNES` context
4011: Output Parameters:
4012: + atol - the absolute convergence tolerance
4013: . rtol - the relative convergence tolerance
4014: . stol - convergence tolerance in terms of the norm of the change in the solution between steps
4015: . maxit - the maximum number of iterations allowed
4016: - maxf - the maximum number of function evaluations allowed, `PETSC_UNLIMITED` indicates no bound
4018: Level: intermediate
4020: Notes:
4021: See `SNESSetTolerances()` for details on the parameters.
4023: The user can specify `NULL` for any parameter that is not needed.
4025: .seealso: [](ch_snes), `SNES`, `SNESSetTolerances()`
4026: @*/
4027: PetscErrorCode SNESGetTolerances(SNES snes, PetscReal *atol, PetscReal *rtol, PetscReal *stol, PetscInt *maxit, PetscInt *maxf)
4028: {
4029: PetscFunctionBegin;
4031: if (atol) *atol = snes->abstol;
4032: if (rtol) *rtol = snes->rtol;
4033: if (stol) *stol = snes->stol;
4034: if (maxit) *maxit = snes->max_its;
4035: if (maxf) *maxf = snes->max_funcs;
4036: PetscFunctionReturn(PETSC_SUCCESS);
4037: }
4039: /*@
4040: SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.
4042: Not Collective
4044: Input Parameters:
4045: + snes - the `SNES` context
4046: - divtol - divergence tolerance
4048: Level: intermediate
4050: .seealso: [](ch_snes), `SNES`, `SNESSetDivergenceTolerance()`
4051: @*/
4052: PetscErrorCode SNESGetDivergenceTolerance(SNES snes, PetscReal *divtol)
4053: {
4054: PetscFunctionBegin;
4056: if (divtol) *divtol = snes->divtol;
4057: PetscFunctionReturn(PETSC_SUCCESS);
4058: }
4060: PETSC_INTERN PetscErrorCode SNESMonitorRange_Private(SNES, PetscInt, PetscReal *);
4062: PetscErrorCode SNESMonitorLGRange(SNES snes, PetscInt n, PetscReal rnorm, PetscCtx monctx)
4063: {
4064: PetscDrawLG lg;
4065: PetscReal x, y, per;
4066: PetscViewer v = (PetscViewer)monctx;
4067: static PetscReal prev; /* should be in the context */
4068: PetscDraw draw;
4070: PetscFunctionBegin;
4072: PetscCall(PetscViewerDrawGetDrawLG(v, 0, &lg));
4073: if (!n) PetscCall(PetscDrawLGReset(lg));
4074: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4075: PetscCall(PetscDrawSetTitle(draw, "Residual norm"));
4076: x = (PetscReal)n;
4077: if (rnorm > 0.0) y = PetscLog10Real(rnorm);
4078: else y = -15.0;
4079: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4080: if (n < 20 || !(n % 5) || snes->reason) {
4081: PetscCall(PetscDrawLGDraw(lg));
4082: PetscCall(PetscDrawLGSave(lg));
4083: }
4085: PetscCall(PetscViewerDrawGetDrawLG(v, 1, &lg));
4086: if (!n) PetscCall(PetscDrawLGReset(lg));
4087: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4088: PetscCall(PetscDrawSetTitle(draw, "% elements > .2*max element"));
4089: PetscCall(SNESMonitorRange_Private(snes, n, &per));
4090: x = (PetscReal)n;
4091: y = 100.0 * per;
4092: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4093: if (n < 20 || !(n % 5) || snes->reason) {
4094: PetscCall(PetscDrawLGDraw(lg));
4095: PetscCall(PetscDrawLGSave(lg));
4096: }
4098: PetscCall(PetscViewerDrawGetDrawLG(v, 2, &lg));
4099: if (!n) {
4100: prev = rnorm;
4101: PetscCall(PetscDrawLGReset(lg));
4102: }
4103: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4104: PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm"));
4105: x = (PetscReal)n;
4106: y = (prev - rnorm) / prev;
4107: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4108: if (n < 20 || !(n % 5) || snes->reason) {
4109: PetscCall(PetscDrawLGDraw(lg));
4110: PetscCall(PetscDrawLGSave(lg));
4111: }
4113: PetscCall(PetscViewerDrawGetDrawLG(v, 3, &lg));
4114: if (!n) PetscCall(PetscDrawLGReset(lg));
4115: PetscCall(PetscDrawLGGetDraw(lg, &draw));
4116: PetscCall(PetscDrawSetTitle(draw, "(norm -oldnorm)/oldnorm*(% > .2 max)"));
4117: x = (PetscReal)n;
4118: y = (prev - rnorm) / (prev * per);
4119: if (n > 2) { /*skip initial crazy value */
4120: PetscCall(PetscDrawLGAddPoint(lg, &x, &y));
4121: }
4122: if (n < 20 || !(n % 5) || snes->reason) {
4123: PetscCall(PetscDrawLGDraw(lg));
4124: PetscCall(PetscDrawLGSave(lg));
4125: }
4126: prev = rnorm;
4127: PetscFunctionReturn(PETSC_SUCCESS);
4128: }
4130: /*@
4131: SNESConverged - Run the convergence test and update the `SNESConvergedReason`.
4133: Collective
4135: Input Parameters:
4136: + snes - the `SNES` context
4137: . it - current iteration
4138: . xnorm - 2-norm of current iterate
4139: . snorm - 2-norm of current step
4140: - fnorm - 2-norm of function
4142: Level: developer
4144: Note:
4145: This routine is called by the `SNESSolve()` implementations.
4146: It does not typically need to be called by the user.
4148: .seealso: [](ch_snes), `SNES`, `SNESSolve`, `SNESSetConvergenceTest()`
4149: @*/
4150: PetscErrorCode SNESConverged(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm)
4151: {
4152: PetscFunctionBegin;
4153: if (!snes->reason) {
4154: if (snes->normschedule == SNES_NORM_ALWAYS) PetscUseTypeMethod(snes, converged, it, xnorm, snorm, fnorm, &snes->reason, snes->cnvP);
4155: if (it == snes->max_its && !snes->reason) {
4156: if (snes->normschedule == SNES_NORM_ALWAYS) {
4157: PetscCall(PetscInfo(snes, "Maximum number of iterations has been reached: %" PetscInt_FMT "\n", snes->max_its));
4158: snes->reason = SNES_DIVERGED_MAX_IT;
4159: } else snes->reason = SNES_CONVERGED_ITS;
4160: }
4161: }
4162: PetscFunctionReturn(PETSC_SUCCESS);
4163: }
4165: /*@
4166: SNESMonitor - runs any `SNES` monitor routines provided with `SNESMonitor()` or the options database
4168: Collective
4170: Input Parameters:
4171: + snes - nonlinear solver context obtained from `SNESCreate()`
4172: . iter - current iteration number
4173: - rnorm - current relative norm of the residual
4175: Level: developer
4177: Note:
4178: This routine is called by the `SNESSolve()` implementations.
4179: It does not typically need to be called by the user.
4181: .seealso: [](ch_snes), `SNES`, `SNESMonitorSet()`
4182: @*/
4183: PetscErrorCode SNESMonitor(SNES snes, PetscInt iter, PetscReal rnorm)
4184: {
4185: PetscInt i, n = snes->numbermonitors;
4187: PetscFunctionBegin;
4188: PetscCall(VecLockReadPush(snes->vec_sol));
4189: for (i = 0; i < n; i++) PetscCall((*snes->monitor[i])(snes, iter, rnorm, snes->monitorcontext[i]));
4190: PetscCall(VecLockReadPop(snes->vec_sol));
4191: PetscFunctionReturn(PETSC_SUCCESS);
4192: }
4194: /* ------------ Routines to set performance monitoring options ----------- */
4196: /*MC
4197: SNESMonitorFunction - functional form passed to `SNESMonitorSet()` to monitor convergence of nonlinear solver
4199: Synopsis:
4200: #include <petscsnes.h>
4201: PetscErrorCode SNESMonitorFunction(SNES snes, PetscInt its, PetscReal norm, PetscCtx mctx)
4203: Collective
4205: Input Parameters:
4206: + snes - the `SNES` context
4207: . its - iteration number
4208: . norm - 2-norm function value (may be estimated)
4209: - mctx - [optional] monitoring context
4211: Level: advanced
4213: .seealso: [](ch_snes), `SNESMonitorSet()`, `PetscCtx`
4214: M*/
4216: /*@C
4217: SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
4218: iteration of the `SNES` nonlinear solver to display the iteration's
4219: progress.
4221: Logically Collective
4223: Input Parameters:
4224: + snes - the `SNES` context
4225: . f - the monitor function, for the calling sequence see `SNESMonitorFunction`
4226: . mctx - [optional] user-defined context for private data for the monitor routine (use `NULL` if no context is desired)
4227: - monitordestroy - [optional] routine that frees monitor context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
4229: Calling sequence of f:
4230: + snes - the `SNES` object
4231: . it - the current iteration
4232: . rnorm - norm of the residual
4233: - mctx - the optional monitor context
4235: Options Database Keys:
4236: + -snes_monitor - sets `SNESMonitorDefault()`
4237: . -snes_monitor draw::draw_lg - sets line graph monitor,
4238: - -snes_monitor_cancel - cancels all monitors that have been hardwired into a code by calls to `SNESMonitorSet()`, but does not cancel those set via
4239: the options database.
4241: Level: intermediate
4243: Note:
4244: Several different monitoring routines may be set by calling
4245: `SNESMonitorSet()` multiple times; all will be called in the
4246: order in which they were set.
4248: Fortran Note:
4249: Only a single monitor function can be set for each `SNES` object
4251: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction`, `PetscCtxDestroyFn`
4252: @*/
4253: PetscErrorCode SNESMonitorSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscInt it, PetscReal rnorm, PetscCtx mctx), PetscCtx mctx, PetscCtxDestroyFn *monitordestroy)
4254: {
4255: PetscFunctionBegin;
4257: for (PetscInt i = 0; i < snes->numbermonitors; i++) {
4258: PetscBool identical;
4260: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, mctx, monitordestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->monitor[i], snes->monitorcontext[i], snes->monitordestroy[i], &identical));
4261: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4262: }
4263: PetscCheck(snes->numbermonitors < MAXSNESMONITORS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many monitors set");
4264: snes->monitor[snes->numbermonitors] = f;
4265: snes->monitordestroy[snes->numbermonitors] = monitordestroy;
4266: snes->monitorcontext[snes->numbermonitors++] = mctx;
4267: PetscFunctionReturn(PETSC_SUCCESS);
4268: }
4270: /*@
4271: SNESMonitorCancel - Clears all the monitor functions for a `SNES` object.
4273: Logically Collective
4275: Input Parameter:
4276: . snes - the `SNES` context
4278: Options Database Key:
4279: . -snes_monitor_cancel - cancels all monitors that have been hardwired
4280: into a code by calls to `SNESMonitorSet()`, but does not cancel those
4281: set via the options database
4283: Level: intermediate
4285: Note:
4286: There is no way to clear one specific monitor from a `SNES` object.
4288: .seealso: [](ch_snes), `SNES`, `SNESMonitorDefault()`, `SNESMonitorSet()`
4289: @*/
4290: PetscErrorCode SNESMonitorCancel(SNES snes)
4291: {
4292: PetscInt i;
4294: PetscFunctionBegin;
4296: for (i = 0; i < snes->numbermonitors; i++) {
4297: if (snes->monitordestroy[i]) PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4298: }
4299: snes->numbermonitors = 0;
4300: PetscFunctionReturn(PETSC_SUCCESS);
4301: }
4303: /*@C
4304: SNESSetConvergenceTest - Sets the function that is to be used
4305: to test for convergence of the nonlinear iterative solution.
4307: Logically Collective
4309: Input Parameters:
4310: + snes - the `SNES` context
4311: . func - routine to test for convergence
4312: . ctx - [optional] context for private data for the convergence routine (may be `NULL`)
4313: - destroy - [optional] destructor for the context (may be `NULL`; `PETSC_NULL_FUNCTION` in Fortran)
4315: Calling sequence of func:
4316: + snes - the `SNES` context
4317: . it - the current iteration number
4318: . xnorm - the norm of the new solution
4319: . snorm - the norm of the step
4320: . fnorm - the norm of the function value
4321: . reason - output, the reason convergence or divergence as declared
4322: - ctx - the optional convergence test context
4324: Level: advanced
4326: .seealso: [](ch_snes), `SNES`, `SNESConvergedDefault()`, `SNESConvergedSkip()`
4327: @*/
4328: PetscErrorCode SNESSetConvergenceTest(SNES snes, PetscErrorCode (*func)(SNES snes, PetscInt it, PetscReal xnorm, PetscReal snorm, PetscReal fnorm, SNESConvergedReason *reason, PetscCtx ctx), PetscCtx ctx, PetscCtxDestroyFn *destroy)
4329: {
4330: PetscFunctionBegin;
4332: if (!func) func = SNESConvergedSkip;
4333: if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(&snes->cnvP));
4334: snes->ops->converged = func;
4335: snes->ops->convergeddestroy = destroy;
4336: snes->cnvP = ctx;
4337: PetscFunctionReturn(PETSC_SUCCESS);
4338: }
4340: /*@
4341: SNESGetConvergedReason - Gets the reason the `SNES` iteration was stopped, which may be due to convergence, divergence, or stagnation
4343: Not Collective
4345: Input Parameter:
4346: . snes - the `SNES` context
4348: Output Parameter:
4349: . reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` for the individual convergence tests for complete lists
4351: Options Database Key:
4352: . -snes_converged_reason - prints the reason to standard out
4354: Level: intermediate
4356: Note:
4357: Should only be called after the call the `SNESSolve()` is complete, if it is called earlier it returns the value `SNES__CONVERGED_ITERATING`.
4359: .seealso: [](ch_snes), `SNESSolve()`, `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason`, `SNESGetConvergedReasonString()`
4360: @*/
4361: PetscErrorCode SNESGetConvergedReason(SNES snes, SNESConvergedReason *reason)
4362: {
4363: PetscFunctionBegin;
4365: PetscAssertPointer(reason, 2);
4366: *reason = snes->reason;
4367: PetscFunctionReturn(PETSC_SUCCESS);
4368: }
4370: /*@C
4371: SNESGetConvergedReasonString - Return a human readable string for `SNESConvergedReason`
4373: Not Collective
4375: Input Parameter:
4376: . snes - the `SNES` context
4378: Output Parameter:
4379: . strreason - a human readable string that describes `SNES` converged reason
4381: Level: beginner
4383: .seealso: [](ch_snes), `SNES`, `SNESGetConvergedReason()`
4384: @*/
4385: PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char **strreason)
4386: {
4387: PetscFunctionBegin;
4389: PetscAssertPointer(strreason, 2);
4390: *strreason = SNESConvergedReasons[snes->reason];
4391: PetscFunctionReturn(PETSC_SUCCESS);
4392: }
4394: /*@
4395: SNESSetConvergedReason - Sets the reason the `SNES` iteration was stopped.
4397: Not Collective
4399: Input Parameters:
4400: + snes - the `SNES` context
4401: - reason - negative value indicates diverged, positive value converged, see `SNESConvergedReason` or the
4402: manual pages for the individual convergence tests for complete lists
4404: Level: developer
4406: Developer Note:
4407: Called inside the various `SNESSolve()` implementations
4409: .seealso: [](ch_snes), `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason`
4410: @*/
4411: PetscErrorCode SNESSetConvergedReason(SNES snes, SNESConvergedReason reason)
4412: {
4413: PetscFunctionBegin;
4415: PetscCheck(!snes->errorifnotconverged || reason > 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_PLIB, "SNES code should have previously errored due to negative reason");
4416: snes->reason = reason;
4417: PetscFunctionReturn(PETSC_SUCCESS);
4418: }
4420: /*@
4421: SNESSetConvergenceHistory - Sets the arrays used to hold the convergence history.
4423: Logically Collective
4425: Input Parameters:
4426: + snes - iterative context obtained from `SNESCreate()`
4427: . a - array to hold history, this array will contain the function norms computed at each step
4428: . its - integer array holds the number of linear iterations for each solve.
4429: . na - size of `a` and `its`
4430: - reset - `PETSC_TRUE` indicates each new nonlinear solve resets the history counter to zero,
4431: else it continues storing new values for new nonlinear solves after the old ones
4433: Level: intermediate
4435: Notes:
4436: If 'a' and 'its' are `NULL` then space is allocated for the history. If 'na' is `PETSC_DECIDE` (or, deprecated, `PETSC_DEFAULT`) then a
4437: default array of length 1,000 is allocated.
4439: This routine is useful, e.g., when running a code for purposes
4440: of accurate performance monitoring, when no I/O should be done
4441: during the section of code that is being timed.
4443: If the arrays run out of space after a number of iterations then the later values are not saved in the history
4445: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetConvergenceHistory()`
4446: @*/
4447: PetscErrorCode SNESSetConvergenceHistory(SNES snes, PetscReal a[], PetscInt its[], PetscInt na, PetscBool reset)
4448: {
4449: PetscFunctionBegin;
4451: if (a) PetscAssertPointer(a, 2);
4452: if (its) PetscAssertPointer(its, 3);
4453: if (!a) {
4454: if (na == PETSC_DECIDE) na = 1000;
4455: PetscCall(PetscCalloc2(na, &a, na, &its));
4456: snes->conv_hist_alloc = PETSC_TRUE;
4457: }
4458: snes->conv_hist = a;
4459: snes->conv_hist_its = its;
4460: snes->conv_hist_max = (size_t)na;
4461: snes->conv_hist_len = 0;
4462: snes->conv_hist_reset = reset;
4463: PetscFunctionReturn(PETSC_SUCCESS);
4464: }
4466: #if defined(PETSC_HAVE_MATLAB)
4467: #include <engine.h> /* MATLAB include file */
4468: #include <mex.h> /* MATLAB include file */
4470: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4471: {
4472: mxArray *mat;
4473: PetscInt i;
4474: PetscReal *ar;
4476: mat = mxCreateDoubleMatrix(snes->conv_hist_len, 1, mxREAL);
4477: ar = (PetscReal *)mxGetData(mat);
4478: for (i = 0; i < snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4479: return mat;
4480: }
4481: #endif
4483: /*@C
4484: SNESGetConvergenceHistory - Gets the arrays used to hold the convergence history.
4486: Not Collective
4488: Input Parameter:
4489: . snes - iterative context obtained from `SNESCreate()`
4491: Output Parameters:
4492: + a - array to hold history, usually was set with `SNESSetConvergenceHistory()`
4493: . its - integer array holds the number of linear iterations (or
4494: negative if not converged) for each solve.
4495: - na - size of `a` and `its`
4497: Level: intermediate
4499: Note:
4500: This routine is useful, e.g., when running a code for purposes
4501: of accurate performance monitoring, when no I/O should be done
4502: during the section of code that is being timed.
4504: Fortran Notes:
4505: Return the arrays with ``SNESRestoreConvergenceHistory()`
4507: Use the arguments
4508: .vb
4509: PetscReal, pointer :: a(:)
4510: PetscInt, pointer :: its(:)
4511: .ve
4513: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetConvergenceHistory()`
4514: @*/
4515: PetscErrorCode SNESGetConvergenceHistory(SNES snes, PetscReal *a[], PetscInt *its[], PetscInt *na)
4516: {
4517: PetscFunctionBegin;
4519: if (a) *a = snes->conv_hist;
4520: if (its) *its = snes->conv_hist_its;
4521: if (na) *na = (PetscInt)snes->conv_hist_len;
4522: PetscFunctionReturn(PETSC_SUCCESS);
4523: }
4525: /*@C
4526: SNESSetUpdate - Sets the general-purpose update function called
4527: at the beginning of every iteration of the nonlinear solve. Specifically
4528: it is called just before the Jacobian is "evaluated" and after the function
4529: evaluation.
4531: Logically Collective
4533: Input Parameters:
4534: + snes - The nonlinear solver context
4535: - func - The update function; for calling sequence see `SNESUpdateFn`
4537: Level: advanced
4539: Notes:
4540: 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
4541: to `SNESSetFunction()`, or `SNESSetPicard()`
4542: This is not used by most users, and it is intended to provide a general hook that is run
4543: right before the direction step is computed.
4545: Users are free to modify the current residual vector,
4546: the current linearization point, or any other vector associated to the specific solver used.
4547: If such modifications take place, it is the user responsibility to update all the relevant
4548: vectors. For example, if one is adjusting the model parameters at each Newton step their code may look like
4549: .vb
4550: PetscErrorCode update(SNES snes, PetscInt iteration)
4551: {
4552: PetscFunctionBeginUser;
4553: if (iteration > 0) {
4554: // update the model parameters here
4555: Vec x,f;
4556: PetscCall(SNESGetSolution(snes,&x));
4557: PetcCall(SNESGetFunction(snes,&f,NULL,NULL));
4558: PetscCall(SNESComputeFunction(snes,x,f));
4559: }
4560: PetscFunctionReturn(PETSC_SUCCESS);
4561: }
4562: .ve
4564: 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.
4566: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetJacobian()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`,
4567: `SNESMonitorSet()`
4568: @*/
4569: PetscErrorCode SNESSetUpdate(SNES snes, SNESUpdateFn *func)
4570: {
4571: PetscFunctionBegin;
4573: snes->ops->update = func;
4574: PetscFunctionReturn(PETSC_SUCCESS);
4575: }
4577: /*@
4578: SNESConvergedReasonView - Displays the reason a `SNES` solve converged or diverged to a viewer
4580: Collective
4582: Input Parameters:
4583: + snes - iterative context obtained from `SNESCreate()`
4584: - viewer - the viewer to display the reason
4586: Options Database Keys:
4587: + -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4588: - -snes_converged_reason ::failed - only print reason and number of iterations when diverged
4590: Level: beginner
4592: Note:
4593: To change the format of the output call `PetscViewerPushFormat`(viewer,format) before this call. Use `PETSC_VIEWER_DEFAULT` for the default,
4594: use `PETSC_VIEWER_FAILED` to only display a reason if it fails.
4596: .seealso: [](ch_snes), `SNESConvergedReason`, `PetscViewer`, `SNES`,
4597: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`,
4598: `SNESConvergedReasonViewFromOptions()`,
4599: `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
4600: @*/
4601: PetscErrorCode SNESConvergedReasonView(SNES snes, PetscViewer viewer)
4602: {
4603: PetscViewerFormat format;
4604: PetscBool isAscii;
4606: PetscFunctionBegin;
4607: if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4608: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isAscii));
4609: if (isAscii) {
4610: PetscCall(PetscViewerGetFormat(viewer, &format));
4611: PetscCall(PetscViewerASCIIAddTab(viewer, ((PetscObject)snes)->tablevel + 1));
4612: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4613: DM dm;
4614: Vec u;
4615: PetscDS prob;
4616: PetscInt Nf, f;
4617: PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4618: void **exactCtx;
4619: PetscReal error;
4621: PetscCall(SNESGetDM(snes, &dm));
4622: PetscCall(SNESGetSolution(snes, &u));
4623: PetscCall(DMGetDS(dm, &prob));
4624: PetscCall(PetscDSGetNumFields(prob, &Nf));
4625: PetscCall(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx));
4626: for (f = 0; f < Nf; ++f) PetscCall(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]));
4627: PetscCall(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error));
4628: PetscCall(PetscFree2(exactSol, exactCtx));
4629: if (error < 1.0e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n"));
4630: else PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", (double)error));
4631: }
4632: if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4633: if (((PetscObject)snes)->prefix) {
4634: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve converged due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4635: } else {
4636: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve converged due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4637: }
4638: } else if (snes->reason <= 0) {
4639: if (((PetscObject)snes)->prefix) {
4640: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n", ((PetscObject)snes)->prefix, SNESConvergedReasons[snes->reason], snes->iter));
4641: } else {
4642: PetscCall(PetscViewerASCIIPrintf(viewer, "Nonlinear solve did not converge due to %s iterations %" PetscInt_FMT "\n", SNESConvergedReasons[snes->reason], snes->iter));
4643: }
4644: }
4645: PetscCall(PetscViewerASCIISubtractTab(viewer, ((PetscObject)snes)->tablevel + 1));
4646: }
4647: PetscFunctionReturn(PETSC_SUCCESS);
4648: }
4650: /*@C
4651: SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4652: end of the nonlinear solver to display the convergence reason of the nonlinear solver.
4654: Logically Collective
4656: Input Parameters:
4657: + snes - the `SNES` context
4658: . f - the `SNESConvergedReason` view function
4659: . vctx - [optional] user-defined context for private data for the `SNESConvergedReason` view function (use `NULL` if no context is desired)
4660: - reasonviewdestroy - [optional] routine that frees the context (may be `NULL`), see `PetscCtxDestroyFn` for the calling sequence
4662: Calling sequence of `f`:
4663: + snes - the `SNES` context
4664: - vctx - [optional] context for private data for the function
4666: Options Database Keys:
4667: + -snes_converged_reason - sets a default `SNESConvergedReasonView()`
4668: - -snes_converged_reason_view_cancel - cancels all converged reason viewers that have been hardwired into a code by
4669: calls to `SNESConvergedReasonViewSet()`, but does not cancel those set via the options database.
4671: Level: intermediate
4673: Note:
4674: Several different converged reason view routines may be set by calling
4675: `SNESConvergedReasonViewSet()` multiple times; all will be called in the
4676: order in which they were set.
4678: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESConvergedReason`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()`,
4679: `PetscCtxDestroyFn`
4680: @*/
4681: PetscErrorCode SNESConvergedReasonViewSet(SNES snes, PetscErrorCode (*f)(SNES snes, PetscCtx vctx), PetscCtx vctx, PetscCtxDestroyFn *reasonviewdestroy)
4682: {
4683: PetscFunctionBegin;
4685: for (PetscInt i = 0; i < snes->numberreasonviews; i++) {
4686: PetscBool identical;
4688: PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))(PetscVoidFn *)f, vctx, reasonviewdestroy, (PetscErrorCode (*)(void))(PetscVoidFn *)snes->reasonview[i], snes->reasonviewcontext[i], snes->reasonviewdestroy[i], &identical));
4689: if (identical) PetscFunctionReturn(PETSC_SUCCESS);
4690: }
4691: PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Too many SNES reasonview set");
4692: snes->reasonview[snes->numberreasonviews] = f;
4693: snes->reasonviewdestroy[snes->numberreasonviews] = reasonviewdestroy;
4694: snes->reasonviewcontext[snes->numberreasonviews++] = vctx;
4695: PetscFunctionReturn(PETSC_SUCCESS);
4696: }
4698: /*@
4699: SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a `SNESConvergedReason` is to be viewed at the end of `SNESSolve()`
4700: All the user-provided viewer routines set with `SNESConvergedReasonViewSet()` will be called, if they exist.
4702: Collective
4704: Input Parameter:
4705: . snes - the `SNES` object
4707: Level: advanced
4709: .seealso: [](ch_snes), `SNES`, `SNESConvergedReason`, `SNESConvergedReasonViewSet()`, `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`,
4710: `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`
4711: @*/
4712: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4713: {
4714: static PetscBool incall = PETSC_FALSE;
4716: PetscFunctionBegin;
4717: if (incall) PetscFunctionReturn(PETSC_SUCCESS);
4718: incall = PETSC_TRUE;
4720: /* All user-provided viewers are called first, if they exist. */
4721: for (PetscInt i = 0; i < snes->numberreasonviews; i++) PetscCall((*snes->reasonview[i])(snes, snes->reasonviewcontext[i]));
4723: /* Call PETSc default routine if users ask for it */
4724: if (snes->convergedreasonviewer) {
4725: PetscCall(PetscViewerPushFormat(snes->convergedreasonviewer, snes->convergedreasonformat));
4726: PetscCall(SNESConvergedReasonView(snes, snes->convergedreasonviewer));
4727: PetscCall(PetscViewerPopFormat(snes->convergedreasonviewer));
4728: }
4729: incall = PETSC_FALSE;
4730: PetscFunctionReturn(PETSC_SUCCESS);
4731: }
4733: /*@
4734: SNESSolve - Solves a nonlinear system $F(x) = b $ associated with a `SNES` object
4736: Collective
4738: Input Parameters:
4739: + snes - the `SNES` context
4740: . b - the constant part of the equation $F(x) = b$, or `NULL` to use zero.
4741: - x - the solution vector.
4743: Level: beginner
4745: Note:
4746: The user should initialize the vector, `x`, with the initial guess
4747: for the nonlinear solve prior to calling `SNESSolve()` .
4749: .seealso: [](ch_snes), `SNES`, `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`,
4750: `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`,
4751: `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()`
4752: @*/
4753: PetscErrorCode SNESSolve(SNES snes, Vec b, Vec x)
4754: {
4755: PetscBool flg;
4756: PetscInt grid;
4757: Vec xcreated = NULL;
4758: DM dm;
4760: PetscFunctionBegin;
4763: if (x) PetscCheckSameComm(snes, 1, x, 3);
4765: if (b) PetscCheckSameComm(snes, 1, b, 2);
4767: /* High level operations using the nonlinear solver */
4768: {
4769: PetscViewer viewer;
4770: PetscViewerFormat format;
4771: PetscInt num;
4772: PetscBool flg;
4773: static PetscBool incall = PETSC_FALSE;
4775: if (!incall) {
4776: /* Estimate the convergence rate of the discretization */
4777: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
4778: if (flg) {
4779: PetscConvEst conv;
4780: DM dm;
4781: PetscReal *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4782: PetscInt Nf;
4784: incall = PETSC_TRUE;
4785: PetscCall(SNESGetDM(snes, &dm));
4786: PetscCall(DMGetNumFields(dm, &Nf));
4787: PetscCall(PetscCalloc1(Nf, &alpha));
4788: PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)snes), &conv));
4789: PetscCall(PetscConvEstSetSolver(conv, (PetscObject)snes));
4790: PetscCall(PetscConvEstSetFromOptions(conv));
4791: PetscCall(PetscConvEstSetUp(conv));
4792: PetscCall(PetscConvEstGetConvRate(conv, alpha));
4793: PetscCall(PetscViewerPushFormat(viewer, format));
4794: PetscCall(PetscConvEstRateView(conv, alpha, viewer));
4795: PetscCall(PetscViewerPopFormat(viewer));
4796: PetscCall(PetscViewerDestroy(&viewer));
4797: PetscCall(PetscConvEstDestroy(&conv));
4798: PetscCall(PetscFree(alpha));
4799: incall = PETSC_FALSE;
4800: }
4801: /* Adaptively refine the initial grid */
4802: num = 1;
4803: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_initial", &num, &flg));
4804: if (flg) {
4805: DMAdaptor adaptor;
4807: incall = PETSC_TRUE;
4808: PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4809: PetscCall(DMAdaptorSetSolver(adaptor, snes));
4810: PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4811: PetscCall(DMAdaptorSetFromOptions(adaptor));
4812: PetscCall(DMAdaptorSetUp(adaptor));
4813: PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
4814: PetscCall(DMAdaptorDestroy(&adaptor));
4815: incall = PETSC_FALSE;
4816: }
4817: /* Use grid sequencing to adapt */
4818: num = 0;
4819: PetscCall(PetscOptionsGetInt(NULL, ((PetscObject)snes)->prefix, "-snes_adapt_sequence", &num, NULL));
4820: if (num) {
4821: DMAdaptor adaptor;
4822: const char *prefix;
4824: incall = PETSC_TRUE;
4825: PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4826: PetscCall(SNESGetOptionsPrefix(snes, &prefix));
4827: PetscCall(DMAdaptorSetOptionsPrefix(adaptor, prefix));
4828: PetscCall(DMAdaptorSetSolver(adaptor, snes));
4829: PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4830: PetscCall(DMAdaptorSetFromOptions(adaptor));
4831: PetscCall(DMAdaptorSetUp(adaptor));
4832: PetscCall(PetscObjectViewFromOptions((PetscObject)adaptor, NULL, "-snes_adapt_view"));
4833: PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
4834: PetscCall(DMAdaptorDestroy(&adaptor));
4835: incall = PETSC_FALSE;
4836: }
4837: }
4838: }
4839: if (!x) x = snes->vec_sol;
4840: if (!x) {
4841: PetscCall(SNESGetDM(snes, &dm));
4842: PetscCall(DMCreateGlobalVector(dm, &xcreated));
4843: x = xcreated;
4844: }
4845: PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view_pre"));
4847: for (grid = 0; grid < snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4848: for (grid = 0; grid < snes->gridsequence + 1; grid++) {
4849: /* set solution vector */
4850: if (!grid) PetscCall(PetscObjectReference((PetscObject)x));
4851: PetscCall(VecDestroy(&snes->vec_sol));
4852: snes->vec_sol = x;
4853: PetscCall(SNESGetDM(snes, &dm));
4855: /* set affine vector if provided */
4856: if (b) PetscCall(PetscObjectReference((PetscObject)b));
4857: PetscCall(VecDestroy(&snes->vec_rhs));
4858: snes->vec_rhs = b;
4860: 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");
4861: PetscCheck(snes->vec_func != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be function vector");
4862: PetscCheck(snes->vec_rhs != snes->vec_sol, PETSC_COMM_SELF, PETSC_ERR_ARG_IDN, "Solution vector cannot be right-hand side vector");
4863: if (!snes->vec_sol_update /* && snes->vec_sol */) PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_sol_update));
4864: PetscCall(DMShellSetGlobalVector(dm, snes->vec_sol));
4865: PetscCall(SNESSetUp(snes));
4867: if (!grid) {
4868: if (snes->ops->computeinitialguess) PetscCallBack("SNES callback compute initial guess", (*snes->ops->computeinitialguess)(snes, snes->vec_sol, snes->initialguessP));
4869: }
4871: if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4872: PetscCall(SNESResetCounters(snes));
4873: snes->reason = SNES_CONVERGED_ITERATING;
4874: PetscCall(PetscLogEventBegin(SNES_Solve, snes, 0, 0, 0));
4875: PetscUseTypeMethod(snes, solve);
4876: PetscCall(PetscLogEventEnd(SNES_Solve, snes, 0, 0, 0));
4877: PetscCheck(snes->reason, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Internal error, solver %s returned without setting converged reason", ((PetscObject)snes)->type_name);
4878: snes->functiondomainerror = PETSC_FALSE; /* clear the flag if it has been set */
4879: snes->objectivedomainerror = PETSC_FALSE; /* clear the flag if it has been set */
4880: snes->jacobiandomainerror = PETSC_FALSE; /* clear the flag if it has been set */
4882: if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4883: if (snes->lagpre_persist) snes->pre_iter += snes->iter;
4885: PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)snes), ((PetscObject)snes)->options, ((PetscObject)snes)->prefix, "-snes_test_local_min", NULL, NULL, &flg));
4886: if (flg && !PetscPreLoadingOn) PetscCall(SNESTestLocalMin(snes));
4887: /* Call converged reason views. This may involve user-provided viewers as well */
4888: PetscCall(SNESConvergedReasonViewFromOptions(snes));
4890: if (snes->errorifnotconverged) {
4891: if (snes->reason < 0) PetscCall(SNESMonitorCancel(snes));
4892: PetscCheck(snes->reason >= 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_NOT_CONVERGED, "SNESSolve has not converged");
4893: }
4894: if (snes->reason < 0) break;
4895: if (grid < snes->gridsequence) {
4896: DM fine;
4897: Vec xnew;
4898: Mat interp;
4900: PetscCall(DMRefine(snes->dm, PetscObjectComm((PetscObject)snes), &fine));
4901: PetscCheck(fine, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_INCOMP, "DMRefine() did not perform any refinement, cannot continue grid sequencing");
4902: PetscCall(DMGetCoordinatesLocalSetUp(fine));
4903: PetscCall(DMCreateInterpolation(snes->dm, fine, &interp, NULL));
4904: PetscCall(DMCreateGlobalVector(fine, &xnew));
4905: PetscCall(MatInterpolate(interp, x, xnew));
4906: PetscCall(DMInterpolate(snes->dm, interp, fine));
4907: PetscCall(MatDestroy(&interp));
4908: x = xnew;
4910: PetscCall(SNESReset(snes));
4911: PetscCall(SNESSetDM(snes, fine));
4912: PetscCall(SNESResetFromOptions(snes));
4913: PetscCall(DMDestroy(&fine));
4914: PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4915: }
4916: }
4917: PetscCall(SNESViewFromOptions(snes, NULL, "-snes_view"));
4918: PetscCall(VecViewFromOptions(snes->vec_sol, (PetscObject)snes, "-snes_view_solution"));
4919: PetscCall(DMMonitor(snes->dm));
4920: PetscCall(SNESMonitorPauseFinal_Internal(snes));
4922: PetscCall(VecDestroy(&xcreated));
4923: PetscCall(PetscObjectSAWsBlock((PetscObject)snes));
4924: PetscFunctionReturn(PETSC_SUCCESS);
4925: }
4927: /* --------- Internal routines for SNES Package --------- */
4929: /*@
4930: SNESSetType - Sets the algorithm/method to be used to solve the nonlinear system with the given `SNES`
4932: Collective
4934: Input Parameters:
4935: + snes - the `SNES` context
4936: - type - a known method
4938: Options Database Key:
4939: . -snes_type type - Sets the method; see `SNESType`
4941: Level: intermediate
4943: Notes:
4944: See `SNESType` for available methods (for instance)
4945: + `SNESNEWTONLS` - Newton's method with line search
4946: (systems of nonlinear equations)
4947: - `SNESNEWTONTR` - Newton's method with trust region
4948: (systems of nonlinear equations)
4950: Normally, it is best to use the `SNESSetFromOptions()` command and then
4951: set the `SNES` solver type from the options database rather than by using
4952: this routine. Using the options database provides the user with
4953: maximum flexibility in evaluating the many nonlinear solvers.
4954: The `SNESSetType()` routine is provided for those situations where it
4955: is necessary to set the nonlinear solver independently of the command
4956: line or options database. This might be the case, for example, when
4957: the choice of solver changes during the execution of the program,
4958: and the user's application is taking responsibility for choosing the
4959: appropriate method.
4961: Developer Note:
4962: `SNESRegister()` adds a constructor for a new `SNESType` to `SNESList`, `SNESSetType()` locates
4963: the constructor in that list and calls it to create the specific object.
4965: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()`
4966: @*/
4967: PetscErrorCode SNESSetType(SNES snes, SNESType type)
4968: {
4969: PetscBool match;
4970: PetscErrorCode (*r)(SNES);
4972: PetscFunctionBegin;
4974: PetscAssertPointer(type, 2);
4976: PetscCall(PetscObjectTypeCompare((PetscObject)snes, type, &match));
4977: if (match) PetscFunctionReturn(PETSC_SUCCESS);
4979: PetscCall(PetscFunctionListFind(SNESList, type, &r));
4980: PetscCheck(r, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unable to find requested SNES type %s", type);
4981: /* Destroy the previous private SNES context */
4982: PetscTryTypeMethod(snes, destroy);
4983: /* Reinitialize type-specific function pointers in SNESOps structure */
4984: snes->ops->reset = NULL;
4985: snes->ops->setup = NULL;
4986: snes->ops->solve = NULL;
4987: snes->ops->view = NULL;
4988: snes->ops->setfromoptions = NULL;
4989: snes->ops->destroy = NULL;
4991: /* It may happen the user has customized the line search before calling SNESSetType */
4992: if (((PetscObject)snes)->type_name) PetscCall(SNESLineSearchDestroy(&snes->linesearch));
4994: /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4995: snes->setupcalled = PETSC_FALSE;
4997: PetscCall(PetscObjectChangeTypeName((PetscObject)snes, type));
4998: PetscCall((*r)(snes));
4999: PetscFunctionReturn(PETSC_SUCCESS);
5000: }
5002: /*@
5003: SNESGetType - Gets the `SNES` method type and name (as a string).
5005: Not Collective
5007: Input Parameter:
5008: . snes - nonlinear solver context
5010: Output Parameter:
5011: . type - `SNES` method (a character string)
5013: Level: intermediate
5015: .seealso: [](ch_snes), `SNESSetType()`, `SNESType`, `SNESSetFromOptions()`, `SNES`
5016: @*/
5017: PetscErrorCode SNESGetType(SNES snes, SNESType *type)
5018: {
5019: PetscFunctionBegin;
5021: PetscAssertPointer(type, 2);
5022: *type = ((PetscObject)snes)->type_name;
5023: PetscFunctionReturn(PETSC_SUCCESS);
5024: }
5026: /*@
5027: SNESSetSolution - Sets the solution vector for use by the `SNES` routines.
5029: Logically Collective
5031: Input Parameters:
5032: + snes - the `SNES` context obtained from `SNESCreate()`
5033: - u - the solution vector
5035: Level: beginner
5037: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESGetSolution()`, `Vec`
5038: @*/
5039: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
5040: {
5041: DM dm;
5043: PetscFunctionBegin;
5046: PetscCall(PetscObjectReference((PetscObject)u));
5047: PetscCall(VecDestroy(&snes->vec_sol));
5049: snes->vec_sol = u;
5051: PetscCall(SNESGetDM(snes, &dm));
5052: PetscCall(DMShellSetGlobalVector(dm, u));
5053: PetscFunctionReturn(PETSC_SUCCESS);
5054: }
5056: /*@
5057: SNESGetSolution - Returns the vector where the approximate solution is
5058: stored. This is the fine grid solution when using `SNESSetGridSequence()`.
5060: Not Collective, but `x` is parallel if `snes` is parallel
5062: Input Parameter:
5063: . snes - the `SNES` context
5065: Output Parameter:
5066: . x - the solution
5068: Level: intermediate
5070: .seealso: [](ch_snes), `SNESSetSolution()`, `SNESSolve()`, `SNES`, `SNESGetSolutionUpdate()`, `SNESGetFunction()`
5071: @*/
5072: PetscErrorCode SNESGetSolution(SNES snes, Vec *x)
5073: {
5074: PetscFunctionBegin;
5076: PetscAssertPointer(x, 2);
5077: *x = snes->vec_sol;
5078: PetscFunctionReturn(PETSC_SUCCESS);
5079: }
5081: /*@
5082: SNESGetSolutionUpdate - Returns the vector where the solution update is
5083: stored.
5085: Not Collective, but `x` is parallel if `snes` is parallel
5087: Input Parameter:
5088: . snes - the `SNES` context
5090: Output Parameter:
5091: . x - the solution update
5093: Level: advanced
5095: .seealso: [](ch_snes), `SNES`, `SNESGetSolution()`, `SNESGetFunction()`
5096: @*/
5097: PetscErrorCode SNESGetSolutionUpdate(SNES snes, Vec *x)
5098: {
5099: PetscFunctionBegin;
5101: PetscAssertPointer(x, 2);
5102: *x = snes->vec_sol_update;
5103: PetscFunctionReturn(PETSC_SUCCESS);
5104: }
5106: /*@C
5107: SNESGetFunction - Returns the function that defines the nonlinear system set with `SNESSetFunction()`
5109: Not Collective, but `r` is parallel if `snes` is parallel. Collective if `r` is requested, but has not been created yet.
5111: Input Parameter:
5112: . snes - the `SNES` context
5114: Output Parameters:
5115: + r - the vector that is used to store residuals (or `NULL` if you don't want it)
5116: . f - the function (or `NULL` if you don't want it); for calling sequence see `SNESFunctionFn`
5117: - ctx - the function context (or `NULL` if you don't want it)
5119: Level: advanced
5121: Note:
5122: The vector `r` DOES NOT, in general, contain the current value of the `SNES` nonlinear function
5124: .seealso: [](ch_snes), `SNES`, `SNESSolve()`, `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunctionFn`
5125: @*/
5126: PetscErrorCode SNESGetFunction(SNES snes, Vec *r, SNESFunctionFn **f, PetscCtxRt ctx)
5127: {
5128: DM dm;
5130: PetscFunctionBegin;
5132: if (r) {
5133: if (!snes->vec_func) {
5134: if (snes->vec_rhs) {
5135: PetscCall(VecDuplicate(snes->vec_rhs, &snes->vec_func));
5136: } else if (snes->vec_sol) {
5137: PetscCall(VecDuplicate(snes->vec_sol, &snes->vec_func));
5138: } else if (snes->dm) {
5139: PetscCall(DMCreateGlobalVector(snes->dm, &snes->vec_func));
5140: }
5141: }
5142: *r = snes->vec_func;
5143: }
5144: PetscCall(SNESGetDM(snes, &dm));
5145: PetscCall(DMSNESGetFunction(dm, f, ctx));
5146: PetscFunctionReturn(PETSC_SUCCESS);
5147: }
5149: /*@C
5150: SNESGetNGS - Returns the function and context set with `SNESSetNGS()`
5152: Input Parameter:
5153: . snes - the `SNES` context
5155: Output Parameters:
5156: + f - the function (or `NULL`) see `SNESNGSFn` for calling sequence
5157: - ctx - the function context (or `NULL`)
5159: Level: advanced
5161: .seealso: [](ch_snes), `SNESSetNGS()`, `SNESGetFunction()`, `SNESNGSFn`
5162: @*/
5163: PetscErrorCode SNESGetNGS(SNES snes, SNESNGSFn **f, PetscCtxRt ctx)
5164: {
5165: DM dm;
5167: PetscFunctionBegin;
5169: PetscCall(SNESGetDM(snes, &dm));
5170: PetscCall(DMSNESGetNGS(dm, f, ctx));
5171: PetscFunctionReturn(PETSC_SUCCESS);
5172: }
5174: /*@
5175: SNESSetOptionsPrefix - Sets the prefix used for searching for all
5176: `SNES` options in the database.
5178: Logically Collective
5180: Input Parameters:
5181: + snes - the `SNES` context
5182: - prefix - the prefix to prepend to all option names
5184: Level: advanced
5186: Note:
5187: A hyphen (-) must NOT be given at the beginning of the prefix name.
5188: The first character of all runtime options is AUTOMATICALLY the hyphen.
5190: .seealso: [](ch_snes), `SNES`, `SNESSetFromOptions()`, `SNESAppendOptionsPrefix()`
5191: @*/
5192: PetscErrorCode SNESSetOptionsPrefix(SNES snes, const char prefix[])
5193: {
5194: PetscFunctionBegin;
5196: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes, prefix));
5197: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5198: if (snes->linesearch) {
5199: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5200: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch, prefix));
5201: }
5202: PetscCall(KSPSetOptionsPrefix(snes->ksp, prefix));
5203: PetscFunctionReturn(PETSC_SUCCESS);
5204: }
5206: /*@
5207: SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5208: `SNES` options in the database.
5210: Logically Collective
5212: Input Parameters:
5213: + snes - the `SNES` context
5214: - prefix - the prefix to prepend to all option names
5216: Level: advanced
5218: Note:
5219: A hyphen (-) must NOT be given at the beginning of the prefix name.
5220: The first character of all runtime options is AUTOMATICALLY the hyphen.
5222: .seealso: [](ch_snes), `SNESGetOptionsPrefix()`, `SNESSetOptionsPrefix()`
5223: @*/
5224: PetscErrorCode SNESAppendOptionsPrefix(SNES snes, const char prefix[])
5225: {
5226: PetscFunctionBegin;
5228: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes, prefix));
5229: if (!snes->ksp) PetscCall(SNESGetKSP(snes, &snes->ksp));
5230: if (snes->linesearch) {
5231: PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
5232: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch, prefix));
5233: }
5234: PetscCall(KSPAppendOptionsPrefix(snes->ksp, prefix));
5235: PetscFunctionReturn(PETSC_SUCCESS);
5236: }
5238: /*@
5239: SNESGetOptionsPrefix - Gets the prefix used for searching for all
5240: `SNES` options in the database.
5242: Not Collective
5244: Input Parameter:
5245: . snes - the `SNES` context
5247: Output Parameter:
5248: . prefix - pointer to the prefix string used
5250: Level: advanced
5252: .seealso: [](ch_snes), `SNES`, `SNESSetOptionsPrefix()`, `SNESAppendOptionsPrefix()`
5253: @*/
5254: PetscErrorCode SNESGetOptionsPrefix(SNES snes, const char *prefix[])
5255: {
5256: PetscFunctionBegin;
5258: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes, prefix));
5259: PetscFunctionReturn(PETSC_SUCCESS);
5260: }
5262: /*@C
5263: SNESRegister - Adds a method to the nonlinear solver package.
5265: Not Collective
5267: Input Parameters:
5268: + sname - name of a new user-defined solver
5269: - function - routine to create method context
5271: Level: advanced
5273: Note:
5274: `SNESRegister()` may be called multiple times to add several user-defined solvers.
5276: Example Usage:
5277: .vb
5278: SNESRegister("my_solver", MySolverCreate);
5279: .ve
5281: Then, your solver can be chosen with the procedural interface via
5282: .vb
5283: SNESSetType(snes, "my_solver")
5284: .ve
5285: or at runtime via the option
5286: .vb
5287: -snes_type my_solver
5288: .ve
5290: .seealso: [](ch_snes), `SNESRegisterAll()`, `SNESRegisterDestroy()`
5291: @*/
5292: PetscErrorCode SNESRegister(const char sname[], PetscErrorCode (*function)(SNES))
5293: {
5294: PetscFunctionBegin;
5295: PetscCall(SNESInitializePackage());
5296: PetscCall(PetscFunctionListAdd(&SNESList, sname, function));
5297: PetscFunctionReturn(PETSC_SUCCESS);
5298: }
5300: PetscErrorCode SNESTestLocalMin(SNES snes)
5301: {
5302: PetscInt N, i, j;
5303: Vec u, uh, fh;
5304: PetscScalar value;
5305: PetscReal norm;
5307: PetscFunctionBegin;
5308: PetscCall(SNESGetSolution(snes, &u));
5309: PetscCall(VecDuplicate(u, &uh));
5310: PetscCall(VecDuplicate(u, &fh));
5312: /* currently only works for sequential */
5313: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "Testing FormFunction() for local min\n"));
5314: PetscCall(VecGetSize(u, &N));
5315: for (i = 0; i < N; i++) {
5316: PetscCall(VecCopy(u, uh));
5317: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), "i = %" PetscInt_FMT "\n", i));
5318: for (j = -10; j < 11; j++) {
5319: value = PetscSign(j) * PetscExpReal(PetscAbs(j) - 10.0);
5320: PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5321: PetscCall(SNESComputeFunction(snes, uh, fh));
5322: PetscCall(VecNorm(fh, NORM_2, &norm)); /* does not handle use of SNESSetFunctionDomainError() correctly */
5323: PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes), " j norm %" PetscInt_FMT " %18.16e\n", j, (double)norm));
5324: value = -value;
5325: PetscCall(VecSetValue(uh, i, value, ADD_VALUES));
5326: }
5327: }
5328: PetscCall(VecDestroy(&uh));
5329: PetscCall(VecDestroy(&fh));
5330: PetscFunctionReturn(PETSC_SUCCESS);
5331: }
5333: /*@
5334: SNESGetLineSearch - Returns the line search associated with the `SNES`.
5336: Not Collective
5338: Input Parameter:
5339: . snes - iterative context obtained from `SNESCreate()`
5341: Output Parameter:
5342: . linesearch - linesearch context
5344: Level: beginner
5346: Notes:
5347: It creates a default line search instance which can be configured as needed in case it has not been already set with `SNESSetLineSearch()`.
5349: You can also use the options database keys `-snes_linesearch_*` to configure the line search. See `SNESLineSearchSetFromOptions()` for the possible options.
5351: .seealso: [](ch_snes), `SNESLineSearch`, `SNESSetLineSearch()`, `SNESLineSearchCreate()`, `SNESLineSearchSetFromOptions()`
5352: @*/
5353: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5354: {
5355: const char *optionsprefix;
5357: PetscFunctionBegin;
5359: PetscAssertPointer(linesearch, 2);
5360: if (!snes->linesearch) {
5361: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5362: PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
5363: PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes));
5364: PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
5365: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->linesearch, (PetscObject)snes, 1));
5366: }
5367: *linesearch = snes->linesearch;
5368: PetscFunctionReturn(PETSC_SUCCESS);
5369: }
5371: /*@
5372: SNESKSPSetUseEW - Sets `SNES` to the use Eisenstat-Walker method for
5373: computing relative tolerance for linear solvers within an inexact
5374: Newton method.
5376: Logically Collective
5378: Input Parameters:
5379: + snes - `SNES` context
5380: - flag - `PETSC_TRUE` or `PETSC_FALSE`
5382: Options Database Keys:
5383: + -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
5384: . -snes_ksp_ew_version ver - version of Eisenstat-Walker method
5385: . -snes_ksp_ew_rtol0 rtol0 - Sets rtol0
5386: . -snes_ksp_ew_rtolmax rtolmax - Sets rtolmax
5387: . -snes_ksp_ew_gamma gamma - Sets gamma
5388: . -snes_ksp_ew_alpha alpha - Sets alpha
5389: . -snes_ksp_ew_alpha2 alpha2 - Sets alpha2
5390: - -snes_ksp_ew_threshold threshold - Sets threshold
5392: Level: advanced
5394: Note:
5395: The default is to use a constant relative tolerance for
5396: the inner linear solvers. Alternatively, one can use the
5397: Eisenstat-Walker method {cite}`ew96`, where the relative convergence tolerance
5398: is reset at each Newton iteration according progress of the nonlinear
5399: solver.
5401: .seealso: [](ch_snes), `KSP`, `SNES`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5402: @*/
5403: PetscErrorCode SNESKSPSetUseEW(SNES snes, PetscBool flag)
5404: {
5405: PetscFunctionBegin;
5408: snes->ksp_ewconv = flag;
5409: PetscFunctionReturn(PETSC_SUCCESS);
5410: }
5412: /*@
5413: SNESKSPGetUseEW - Gets if `SNES` is using Eisenstat-Walker method
5414: for computing relative tolerance for linear solvers within an
5415: inexact Newton method.
5417: Not Collective
5419: Input Parameter:
5420: . snes - `SNES` context
5422: Output Parameter:
5423: . flag - `PETSC_TRUE` or `PETSC_FALSE`
5425: Level: advanced
5427: .seealso: [](ch_snes), `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5428: @*/
5429: PetscErrorCode SNESKSPGetUseEW(SNES snes, PetscBool *flag)
5430: {
5431: PetscFunctionBegin;
5433: PetscAssertPointer(flag, 2);
5434: *flag = snes->ksp_ewconv;
5435: PetscFunctionReturn(PETSC_SUCCESS);
5436: }
5438: /*@
5439: SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5440: convergence criteria for the linear solvers within an inexact
5441: Newton method.
5443: Logically Collective
5445: Input Parameters:
5446: + snes - `SNES` context
5447: . version - version 1, 2 (default is 2), 3 or 4
5448: . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5449: . rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5450: . gamma - multiplicative factor for version 2 rtol computation
5451: (0 <= gamma2 <= 1)
5452: . alpha - power for version 2 rtol computation (1 < alpha <= 2)
5453: . alpha2 - power for safeguard
5454: - threshold - threshold for imposing safeguard (0 < threshold < 1)
5456: Level: advanced
5458: Notes:
5459: Version 3 was contributed by Luis Chacon, June 2006.
5461: Use `PETSC_CURRENT` to retain the default for any of the parameters.
5463: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`
5464: @*/
5465: PetscErrorCode SNESKSPSetParametersEW(SNES snes, PetscInt version, PetscReal rtol_0, PetscReal rtol_max, PetscReal gamma, PetscReal alpha, PetscReal alpha2, PetscReal threshold)
5466: {
5467: SNESKSPEW *kctx;
5469: PetscFunctionBegin;
5471: kctx = (SNESKSPEW *)snes->kspconvctx;
5472: PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5481: if (version != PETSC_CURRENT) kctx->version = version;
5482: if (rtol_0 != (PetscReal)PETSC_CURRENT) kctx->rtol_0 = rtol_0;
5483: if (rtol_max != (PetscReal)PETSC_CURRENT) kctx->rtol_max = rtol_max;
5484: if (gamma != (PetscReal)PETSC_CURRENT) kctx->gamma = gamma;
5485: if (alpha != (PetscReal)PETSC_CURRENT) kctx->alpha = alpha;
5486: if (alpha2 != (PetscReal)PETSC_CURRENT) kctx->alpha2 = alpha2;
5487: if (threshold != (PetscReal)PETSC_CURRENT) kctx->threshold = threshold;
5489: 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);
5490: 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);
5491: 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);
5492: 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);
5493: 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);
5494: 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);
5495: PetscFunctionReturn(PETSC_SUCCESS);
5496: }
5498: /*@
5499: SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5500: convergence criteria for the linear solvers within an inexact
5501: Newton method.
5503: Not Collective
5505: Input Parameter:
5506: . snes - `SNES` context
5508: Output Parameters:
5509: + version - version 1, 2 (default is 2), 3 or 4
5510: . rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5511: . rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5512: . gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5513: . alpha - power for version 2 rtol computation (1 < alpha <= 2)
5514: . alpha2 - power for safeguard
5515: - threshold - threshold for imposing safeguard (0 < threshold < 1)
5517: Level: advanced
5519: .seealso: [](ch_snes), `SNES`, `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()`
5520: @*/
5521: PetscErrorCode SNESKSPGetParametersEW(SNES snes, PetscInt *version, PetscReal *rtol_0, PetscReal *rtol_max, PetscReal *gamma, PetscReal *alpha, PetscReal *alpha2, PetscReal *threshold)
5522: {
5523: SNESKSPEW *kctx;
5525: PetscFunctionBegin;
5527: kctx = (SNESKSPEW *)snes->kspconvctx;
5528: PetscCheck(kctx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "No Eisenstat-Walker context existing");
5529: if (version) *version = kctx->version;
5530: if (rtol_0) *rtol_0 = kctx->rtol_0;
5531: if (rtol_max) *rtol_max = kctx->rtol_max;
5532: if (gamma) *gamma = kctx->gamma;
5533: if (alpha) *alpha = kctx->alpha;
5534: if (alpha2) *alpha2 = kctx->alpha2;
5535: if (threshold) *threshold = kctx->threshold;
5536: PetscFunctionReturn(PETSC_SUCCESS);
5537: }
5539: PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5540: {
5541: SNES snes = (SNES)ctx;
5542: SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5543: PetscReal rtol = PETSC_CURRENT, stol;
5545: PetscFunctionBegin;
5546: if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5547: if (!snes->iter) {
5548: rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5549: PetscCall(VecNorm(snes->vec_func, NORM_2, &kctx->norm_first));
5550: } else {
5551: PetscCheck(kctx->version >= 1 && kctx->version <= 4, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Only versions 1-4 are supported: %" PetscInt_FMT, kctx->version);
5552: if (kctx->version == 1) {
5553: rtol = PetscAbsReal(snes->norm - kctx->lresid_last) / kctx->norm_last;
5554: stol = PetscPowReal(kctx->rtol_last, kctx->alpha2);
5555: if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5556: } else if (kctx->version == 2) {
5557: rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5558: stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5559: if (stol > kctx->threshold) rtol = PetscMax(rtol, stol);
5560: } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5561: rtol = kctx->gamma * PetscPowReal(snes->norm / kctx->norm_last, kctx->alpha);
5562: /* safeguard: avoid sharp decrease of rtol */
5563: stol = kctx->gamma * PetscPowReal(kctx->rtol_last, kctx->alpha);
5564: stol = PetscMax(rtol, stol);
5565: rtol = PetscMin(kctx->rtol_0, stol);
5566: /* safeguard: avoid oversolving */
5567: stol = kctx->gamma * (kctx->norm_first * snes->rtol) / snes->norm;
5568: stol = PetscMax(rtol, stol);
5569: rtol = PetscMin(kctx->rtol_0, stol);
5570: } else /* if (kctx->version == 4) */ {
5571: /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */
5572: PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm);
5573: PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last);
5574: PetscReal rk = ared / pred;
5575: if (rk < kctx->v4_p1) rtol = 1. - 2. * kctx->v4_p1;
5576: else if (rk < kctx->v4_p2) rtol = kctx->rtol_last;
5577: else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last;
5578: else rtol = kctx->v4_m2 * kctx->rtol_last;
5580: 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;
5581: kctx->rtol_last_2 = kctx->rtol_last;
5582: kctx->rk_last_2 = kctx->rk_last;
5583: kctx->rk_last = rk;
5584: }
5585: }
5586: /* safeguard: avoid rtol greater than rtol_max */
5587: rtol = PetscMin(rtol, kctx->rtol_max);
5588: PetscCall(KSPSetTolerances(ksp, rtol, PETSC_CURRENT, PETSC_CURRENT, PETSC_CURRENT));
5589: PetscCall(PetscInfo(snes, "iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n", snes->iter, kctx->version, (double)rtol));
5590: PetscFunctionReturn(PETSC_SUCCESS);
5591: }
5593: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, PetscCtx ctx)
5594: {
5595: SNES snes = (SNES)ctx;
5596: SNESKSPEW *kctx = (SNESKSPEW *)snes->kspconvctx;
5597: PCSide pcside;
5598: Vec lres;
5600: PetscFunctionBegin;
5601: if (!snes->ksp_ewconv) PetscFunctionReturn(PETSC_SUCCESS);
5602: PetscCall(KSPGetTolerances(ksp, &kctx->rtol_last, NULL, NULL, NULL));
5603: kctx->norm_last = snes->norm;
5604: if (kctx->version == 1 || kctx->version == 4) {
5605: PC pc;
5606: PetscBool getRes;
5608: PetscCall(KSPGetPC(ksp, &pc));
5609: PetscCall(PetscObjectTypeCompare((PetscObject)pc, PCNONE, &getRes));
5610: if (!getRes) {
5611: KSPNormType normtype;
5613: PetscCall(KSPGetNormType(ksp, &normtype));
5614: getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED);
5615: }
5616: PetscCall(KSPGetPCSide(ksp, &pcside));
5617: if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */
5618: PetscCall(KSPGetResidualNorm(ksp, &kctx->lresid_last));
5619: } else {
5620: /* KSP residual is preconditioned residual */
5621: /* compute true linear residual norm */
5622: Mat J;
5623: PetscCall(KSPGetOperators(ksp, &J, NULL));
5624: PetscCall(VecDuplicate(b, &lres));
5625: PetscCall(MatMult(J, x, lres));
5626: PetscCall(VecAYPX(lres, -1.0, b));
5627: PetscCall(VecNorm(lres, NORM_2, &kctx->lresid_last));
5628: PetscCall(VecDestroy(&lres));
5629: }
5630: }
5631: PetscFunctionReturn(PETSC_SUCCESS);
5632: }
5634: /*@
5635: SNESGetKSP - Returns the `KSP` context for a `SNES` solver.
5637: Not Collective, but if `snes` is parallel, then `ksp` is parallel
5639: Input Parameter:
5640: . snes - the `SNES` context
5642: Output Parameter:
5643: . ksp - the `KSP` context
5645: Level: beginner
5647: Notes:
5648: The user can then directly manipulate the `KSP` context to set various
5649: options, etc. Likewise, the user can then extract and manipulate the
5650: `PC` contexts as well.
5652: 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.
5654: .seealso: [](ch_snes), `SNES`, `KSP`, `PC`, `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
5655: @*/
5656: PetscErrorCode SNESGetKSP(SNES snes, KSP *ksp)
5657: {
5658: PetscFunctionBegin;
5660: PetscAssertPointer(ksp, 2);
5662: if (!snes->ksp) {
5663: PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes), &snes->ksp));
5664: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp, (PetscObject)snes, 1));
5666: PetscCall(KSPSetPreSolve(snes->ksp, KSPPreSolve_SNESEW, snes));
5667: PetscCall(KSPSetPostSolve(snes->ksp, KSPPostSolve_SNESEW, snes));
5669: PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
5670: PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp, ((PetscObject)snes)->options));
5671: }
5672: *ksp = snes->ksp;
5673: PetscFunctionReturn(PETSC_SUCCESS);
5674: }
5676: #include <petsc/private/dmimpl.h>
5677: /*@
5678: SNESSetDM - Sets the `DM` that may be used by some `SNES` nonlinear solvers or their underlying preconditioners
5680: Logically Collective
5682: Input Parameters:
5683: + snes - the nonlinear solver context
5684: - dm - the `DM`, cannot be `NULL`
5686: Level: intermediate
5688: Note:
5689: A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
5690: even when not using interfaces like `DMSNESSetFunction()`. Use `DMClone()` to get a distinct `DM` when solving different
5691: problems using the same function space.
5693: .seealso: [](ch_snes), `DM`, `SNES`, `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()`
5694: @*/
5695: PetscErrorCode SNESSetDM(SNES snes, DM dm)
5696: {
5697: KSP ksp;
5698: DMSNES sdm;
5700: PetscFunctionBegin;
5703: PetscCall(PetscObjectReference((PetscObject)dm));
5704: if (snes->dm) { /* Move the DMSNES context over to the new DM unless the new DM already has one */
5705: if (snes->dm->dmsnes && !dm->dmsnes) {
5706: PetscCall(DMCopyDMSNES(snes->dm, dm));
5707: PetscCall(DMGetDMSNES(snes->dm, &sdm));
5708: if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5709: }
5710: PetscCall(DMCoarsenHookRemove(snes->dm, DMCoarsenHook_SNESVecSol, DMRestrictHook_SNESVecSol, snes));
5711: PetscCall(DMDestroy(&snes->dm));
5712: }
5713: snes->dm = dm;
5714: snes->dmAuto = PETSC_FALSE;
5716: PetscCall(SNESGetKSP(snes, &ksp));
5717: PetscCall(KSPSetDM(ksp, dm));
5718: PetscCall(KSPSetDMActive(ksp, KSP_DMACTIVE_ALL, PETSC_FALSE));
5719: if (snes->npc) {
5720: PetscCall(SNESSetDM(snes->npc, snes->dm));
5721: PetscCall(SNESSetNPCSide(snes, snes->npcside));
5722: }
5723: PetscFunctionReturn(PETSC_SUCCESS);
5724: }
5726: /*@
5727: SNESGetDM - Gets the `DM` that may be used by some `SNES` nonlinear solvers/preconditioners
5729: Not Collective but `dm` obtained is parallel on `snes`
5731: Input Parameter:
5732: . snes - the `SNES` context
5734: Output Parameter:
5735: . dm - the `DM`
5737: Level: intermediate
5739: .seealso: [](ch_snes), `DM`, `SNES`, `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()`
5740: @*/
5741: PetscErrorCode SNESGetDM(SNES snes, DM *dm)
5742: {
5743: PetscFunctionBegin;
5745: if (!snes->dm) {
5746: PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes), &snes->dm));
5747: snes->dmAuto = PETSC_TRUE;
5748: }
5749: *dm = snes->dm;
5750: PetscFunctionReturn(PETSC_SUCCESS);
5751: }
5753: /*@
5754: SNESSetNPC - Sets the nonlinear preconditioner to be used.
5756: Collective
5758: Input Parameters:
5759: + snes - iterative context obtained from `SNESCreate()`
5760: - npc - the `SNES` nonlinear preconditioner object
5762: Options Database Key:
5763: . -npc_snes_type type - set the type of the `SNES` to use as the nonlinear preconditioner
5765: Level: developer
5767: Notes:
5768: This is rarely used, rather use `SNESGetNPC()` to retrieve the preconditioner and configure it using the API.
5770: Only some `SNESType` can use a nonlinear preconditioner
5772: .seealso: [](ch_snes), `SNES`, `SNESNGS`, `SNESFAS`, `SNESGetNPC()`, `SNESHasNPC()`
5773: @*/
5774: PetscErrorCode SNESSetNPC(SNES snes, SNES npc)
5775: {
5776: PetscFunctionBegin;
5779: PetscCheckSameComm(snes, 1, npc, 2);
5780: PetscCall(PetscObjectReference((PetscObject)npc));
5781: PetscCall(SNESDestroy(&snes->npc));
5782: snes->npc = npc;
5783: PetscFunctionReturn(PETSC_SUCCESS);
5784: }
5786: /*@
5787: SNESGetNPC - Gets a nonlinear preconditioning solver SNES` to be used to precondition the original nonlinear solver.
5789: Not Collective; but any changes to the obtained the `pc` object must be applied collectively
5791: Input Parameter:
5792: . snes - iterative context obtained from `SNESCreate()`
5794: Output Parameter:
5795: . pc - the `SNES` preconditioner context
5797: Options Database Key:
5798: . -npc_snes_type type - set the type of the `SNES` to use as the nonlinear preconditioner
5800: Level: advanced
5802: Notes:
5803: If a `SNES` was previously set with `SNESSetNPC()` then that value is returned, otherwise a new `SNES` object is created that will
5804: be used as the nonlinear preconditioner for the current `SNES`.
5806: The (preconditioner) `SNES` returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5807: `SNES`. These may be overwritten if needed.
5809: Use the options database prefixes `-npc_snes`, `-npc_ksp`, etc., to control the configuration of the nonlinear preconditioner
5811: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()`
5812: @*/
5813: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5814: {
5815: const char *optionsprefix;
5817: PetscFunctionBegin;
5819: PetscAssertPointer(pc, 2);
5820: if (!snes->npc) {
5821: PetscCtx ctx;
5823: PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes), &snes->npc));
5824: PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc, (PetscObject)snes, 1));
5825: PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5826: PetscCall(SNESSetOptionsPrefix(snes->npc, optionsprefix));
5827: PetscCall(SNESAppendOptionsPrefix(snes->npc, "npc_"));
5828: if (snes->ops->ctxcompute) {
5829: PetscCall(SNESSetComputeApplicationContext(snes, snes->ops->ctxcompute, snes->ops->ctxdestroy));
5830: } else {
5831: PetscCall(SNESGetApplicationContext(snes, &ctx));
5832: PetscCall(SNESSetApplicationContext(snes->npc, ctx));
5833: }
5834: PetscCall(SNESSetCountersReset(snes->npc, PETSC_FALSE));
5835: }
5836: *pc = snes->npc;
5837: PetscFunctionReturn(PETSC_SUCCESS);
5838: }
5840: /*@
5841: SNESHasNPC - Returns whether a nonlinear preconditioner is associated with the given `SNES`
5843: Not Collective
5845: Input Parameter:
5846: . snes - iterative context obtained from `SNESCreate()`
5848: Output Parameter:
5849: . has_npc - whether the `SNES` has a nonlinear preconditioner or not
5851: Level: developer
5853: .seealso: [](ch_snes), `SNESSetNPC()`, `SNESGetNPC()`
5854: @*/
5855: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5856: {
5857: PetscFunctionBegin;
5859: PetscAssertPointer(has_npc, 2);
5860: *has_npc = snes->npc ? PETSC_TRUE : PETSC_FALSE;
5861: PetscFunctionReturn(PETSC_SUCCESS);
5862: }
5864: /*@
5865: SNESSetNPCSide - Sets the nonlinear preconditioning side used by the nonlinear preconditioner inside `SNES`.
5867: Logically Collective
5869: Input Parameter:
5870: . snes - iterative context obtained from `SNESCreate()`
5872: Output Parameter:
5873: . side - the preconditioning side, where side is one of
5874: .vb
5875: PC_LEFT - left preconditioning
5876: PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5877: .ve
5879: Options Database Key:
5880: . -snes_npc_side (right|left) - nonlinear preconditioner side
5882: Level: intermediate
5884: Note:
5885: `SNESNRICHARDSON` and `SNESNCG` only support left preconditioning.
5887: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESNRICHARDSON`, `SNESNCG`, `SNESType`, `SNESGetNPCSide()`, `KSPSetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
5888: @*/
5889: PetscErrorCode SNESSetNPCSide(SNES snes, PCSide side)
5890: {
5891: PetscFunctionBegin;
5894: if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
5895: PetscCheck((side == PC_LEFT) || (side == PC_RIGHT), PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONG, "Only PC_LEFT and PC_RIGHT are supported");
5896: snes->npcside = side;
5897: PetscFunctionReturn(PETSC_SUCCESS);
5898: }
5900: /*@
5901: SNESGetNPCSide - Gets the preconditioning side used by the nonlinear preconditioner inside `SNES`.
5903: Not Collective
5905: Input Parameter:
5906: . snes - iterative context obtained from `SNESCreate()`
5908: Output Parameter:
5909: . side - the preconditioning side, where side is one of
5910: .vb
5911: `PC_LEFT` - left preconditioning
5912: `PC_RIGHT` - right preconditioning (default for most nonlinear solvers)
5913: .ve
5915: Level: intermediate
5917: .seealso: [](ch_snes), `SNES`, `SNESGetNPC()`, `SNESSetNPCSide()`, `KSPGetPCSide()`, `PC_LEFT`, `PC_RIGHT`, `PCSide`
5918: @*/
5919: PetscErrorCode SNESGetNPCSide(SNES snes, PCSide *side)
5920: {
5921: PetscFunctionBegin;
5923: PetscAssertPointer(side, 2);
5924: *side = snes->npcside;
5925: PetscFunctionReturn(PETSC_SUCCESS);
5926: }
5928: /*@
5929: SNESSetLineSearch - Sets the `SNESLineSearch` to be used for a given `SNES`
5931: Collective
5933: Input Parameters:
5934: + snes - iterative context obtained from `SNESCreate()`
5935: - linesearch - the linesearch object
5937: Level: developer
5939: Note:
5940: This is almost never used, rather one uses `SNESGetLineSearch()` to retrieve the line search and set options on it
5941: to configure it using the API).
5943: .seealso: [](ch_snes), `SNES`, `SNESLineSearch`, `SNESGetLineSearch()`
5944: @*/
5945: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5946: {
5947: PetscFunctionBegin;
5950: PetscCheckSameComm(snes, 1, linesearch, 2);
5951: PetscCall(PetscObjectReference((PetscObject)linesearch));
5952: PetscCall(SNESLineSearchDestroy(&snes->linesearch));
5954: snes->linesearch = linesearch;
5955: PetscFunctionReturn(PETSC_SUCCESS);
5956: }