xref: /petsc/src/snes/interface/snes.c (revision 04346f8ccbfaa9fb73fb7dce6ecc10b18d1c2572)
1 #include <petsc/private/snesimpl.h>      /*I "petscsnes.h"  I*/
2 #include <petscdmshell.h>
3 #include <petscdraw.h>
4 #include <petscds.h>
5 #include <petscdmadaptor.h>
6 #include <petscconvest.h>
7 
8 PetscBool         SNESRegisterAllCalled = PETSC_FALSE;
9 PetscFunctionList SNESList              = NULL;
10 
11 /* Logging support */
12 PetscClassId  SNES_CLASSID, DMSNES_CLASSID;
13 PetscLogEvent SNES_Solve, SNES_Setup, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NPCSolve, SNES_ObjectiveEval;
14 
15 /*@
16    SNESSetErrorIfNotConverged - Causes SNESSolve() to generate an error if the solver has not converged.
17 
18    Logically Collective on SNES
19 
20    Input Parameters:
21 +  snes - iterative context obtained from SNESCreate()
22 -  flg - PETSC_TRUE indicates you want the error generated
23 
24    Options database keys:
25 .  -snes_error_if_not_converged <true,false> - cause an immediate error condition and stop the program if the solver does not converge
26 
27    Level: intermediate
28 
29    Notes:
30     Normally PETSc continues if a linear solver fails to converge, you can call SNESGetConvergedReason() after a SNESSolve()
31     to determine if it has converged.
32 
33 .seealso: `SNESGetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()`
34 @*/
35 PetscErrorCode  SNESSetErrorIfNotConverged(SNES snes,PetscBool flg)
36 {
37   PetscFunctionBegin;
38   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
39   PetscValidLogicalCollectiveBool(snes,flg,2);
40   snes->errorifnotconverged = flg;
41   PetscFunctionReturn(0);
42 }
43 
44 /*@
45    SNESGetErrorIfNotConverged - Will SNESSolve() generate an error if the solver does not converge?
46 
47    Not Collective
48 
49    Input Parameter:
50 .  snes - iterative context obtained from SNESCreate()
51 
52    Output Parameter:
53 .  flag - PETSC_TRUE if it will generate an error, else PETSC_FALSE
54 
55    Level: intermediate
56 
57 .seealso: `SNESSetErrorIfNotConverged()`, `KSPGetErrorIfNotConverged()`, `KSPSetErrorIfNotConverged()`
58 @*/
59 PetscErrorCode  SNESGetErrorIfNotConverged(SNES snes,PetscBool  *flag)
60 {
61   PetscFunctionBegin;
62   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
63   PetscValidBoolPointer(flag,2);
64   *flag = snes->errorifnotconverged;
65   PetscFunctionReturn(0);
66 }
67 
68 /*@
69     SNESSetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?
70 
71    Logically Collective on SNES
72 
73     Input Parameters:
74 +   snes - the shell SNES
75 -   flg - is the residual computed?
76 
77    Level: advanced
78 
79 .seealso: `SNESGetAlwaysComputesFinalResidual()`
80 @*/
81 PetscErrorCode  SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
82 {
83   PetscFunctionBegin;
84   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
85   snes->alwayscomputesfinalresidual = flg;
86   PetscFunctionReturn(0);
87 }
88 
89 /*@
90     SNESGetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?
91 
92    Logically Collective on SNES
93 
94     Input Parameter:
95 .   snes - the shell SNES
96 
97     Output Parameter:
98 .   flg - is the residual computed?
99 
100    Level: advanced
101 
102 .seealso: `SNESSetAlwaysComputesFinalResidual()`
103 @*/
104 PetscErrorCode  SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
105 {
106   PetscFunctionBegin;
107   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
108   *flg = snes->alwayscomputesfinalresidual;
109   PetscFunctionReturn(0);
110 }
111 
112 /*@
113    SNESSetFunctionDomainError - tells SNES that the input vector to your SNESFunction is not
114      in the functions domain. For example, a step with negative pressure.
115 
116    Logically Collective on SNES
117 
118    Input Parameters:
119 .  snes - the SNES context
120 
121    Level: advanced
122 
123    Note:
124    You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
125    `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
126 
127 .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction`, `SNESSetJacobianDomainError()`, `SNESVISetVariableBounds()`,
128           `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
129 @*/
130 PetscErrorCode  SNESSetFunctionDomainError(SNES snes)
131 {
132   PetscFunctionBegin;
133   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
134   PetscCheck(!snes->errorifnotconverged,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates input vector is not in the function domain");
135   snes->domainerror = PETSC_TRUE;
136   PetscFunctionReturn(0);
137 }
138 
139 /*@
140    SNESSetJacobianDomainError - tells SNES that computeJacobian does not make sense at the proposed step. For example there is a negative element transformation.
141 
142    Logically Collective on SNES
143 
144    Input Parameters:
145 .  snes - the SNES context
146 
147    Level: advanced
148 
149    Note:
150    You can direct `SNES` to avoid certain steps by using `SNESVISetVariableBounds()`, `SNESVISetComputeVariableBounds()` or
151    `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
152 
153 .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESVISetVariableBounds()`,
154           `SNESVISetComputeVariableBounds()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`
155 @*/
156 PetscErrorCode SNESSetJacobianDomainError(SNES snes)
157 {
158   PetscFunctionBegin;
159   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
160   PetscCheck(!snes->errorifnotconverged,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates computeJacobian does not make sense");
161   snes->jacobiandomainerror = PETSC_TRUE;
162   PetscFunctionReturn(0);
163 }
164 
165 /*@
166    SNESSetCheckJacobianDomainError - if or not to check jacobian domain error after each Jacobian evaluation. By default, we check Jacobian domain error
167    in the debug mode, and do not check it in the optimized mode.
168 
169    Logically Collective on SNES
170 
171    Input Parameters:
172 +  snes - the SNES context
173 -  flg  - indicates if or not to check jacobian domain error after each Jacobian evaluation
174 
175    Level: advanced
176 
177 .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESGetCheckJacobianDomainError()`
178 @*/
179 PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg)
180 {
181   PetscFunctionBegin;
182   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
183   snes->checkjacdomainerror = flg;
184   PetscFunctionReturn(0);
185 }
186 
187 /*@
188    SNESGetCheckJacobianDomainError - Get an indicator whether or not we are checking Jacobian domain errors after each Jacobian evaluation.
189 
190    Logically Collective on SNES
191 
192    Input Parameters:
193 .  snes - the SNES context
194 
195    Output Parameters:
196 .  flg  - PETSC_FALSE indicates that we don't check jacobian domain errors after each Jacobian evaluation
197 
198    Level: advanced
199 
200 .seealso: `SNESCreate()`, `SNESSetFunction()`, `SNESFunction()`, `SNESSetFunctionDomainError()`, `SNESSetCheckJacobianDomainError()`
201 @*/
202 PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
203 {
204   PetscFunctionBegin;
205   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
206   PetscValidBoolPointer(flg,2);
207   *flg = snes->checkjacdomainerror;
208   PetscFunctionReturn(0);
209 }
210 
211 /*@
212    SNESGetFunctionDomainError - Gets the status of the domain error after a call to SNESComputeFunction;
213 
214    Logically Collective on SNES
215 
216    Input Parameters:
217 .  snes - the SNES context
218 
219    Output Parameters:
220 .  domainerror - Set to PETSC_TRUE if there's a domain error; PETSC_FALSE otherwise.
221 
222    Level: advanced
223 
224 .seealso: `SNESSetFunctionDomainError()`, `SNESComputeFunction()`
225 @*/
226 PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
227 {
228   PetscFunctionBegin;
229   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
230   PetscValidBoolPointer(domainerror,2);
231   *domainerror = snes->domainerror;
232   PetscFunctionReturn(0);
233 }
234 
235 /*@
236    SNESGetJacobianDomainError - Gets the status of the Jacobian domain error after a call to SNESComputeJacobian;
237 
238    Logically Collective on SNES
239 
240    Input Parameters:
241 .  snes - the SNES context
242 
243    Output Parameters:
244 .  domainerror - Set to PETSC_TRUE if there's a jacobian domain error; PETSC_FALSE otherwise.
245 
246    Level: advanced
247 
248 .seealso: `SNESSetFunctionDomainError()`, `SNESComputeFunction()`, `SNESGetFunctionDomainError()`
249 @*/
250 PetscErrorCode SNESGetJacobianDomainError(SNES snes, PetscBool *domainerror)
251 {
252   PetscFunctionBegin;
253   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
254   PetscValidBoolPointer(domainerror,2);
255   *domainerror = snes->jacobiandomainerror;
256   PetscFunctionReturn(0);
257 }
258 
259 /*@C
260   SNESLoad - Loads a SNES that has been stored in binary  with SNESView().
261 
262   Collective on PetscViewer
263 
264   Input Parameters:
265 + newdm - the newly loaded SNES, this needs to have been created with SNESCreate() or
266            some related function before a call to SNESLoad().
267 - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
268 
269    Level: intermediate
270 
271   Notes:
272    The type is determined by the data in the file, any type set into the SNES before this call is ignored.
273 
274   Notes for advanced users:
275   Most users should not need to know the details of the binary storage
276   format, since SNESLoad() and TSView() completely hide these details.
277   But for anyone who's interested, the standard binary matrix storage
278   format is
279 .vb
280      has not yet been determined
281 .ve
282 
283 .seealso: `PetscViewerBinaryOpen()`, `SNESView()`, `MatLoad()`, `VecLoad()`
284 @*/
285 PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
286 {
287   PetscBool      isbinary;
288   PetscInt       classid;
289   char           type[256];
290   KSP            ksp;
291   DM             dm;
292   DMSNES         dmsnes;
293 
294   PetscFunctionBegin;
295   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
296   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
297   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
298   PetscCheck(isbinary,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
299 
300   PetscCall(PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT));
301   PetscCheck(classid == SNES_FILE_CLASSID,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
302   PetscCall(PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR));
303   PetscCall(SNESSetType(snes, type));
304   if (snes->ops->load) PetscCall((*snes->ops->load)(snes,viewer));
305   PetscCall(SNESGetDM(snes,&dm));
306   PetscCall(DMGetDMSNES(dm,&dmsnes));
307   PetscCall(DMSNESLoad(dmsnes,viewer));
308   PetscCall(SNESGetKSP(snes,&ksp));
309   PetscCall(KSPLoad(ksp,viewer));
310   PetscFunctionReturn(0);
311 }
312 
313 #include <petscdraw.h>
314 #if defined(PETSC_HAVE_SAWS)
315 #include <petscviewersaws.h>
316 #endif
317 
318 /*@C
319    SNESViewFromOptions - View from Options
320 
321    Collective on SNES
322 
323    Input Parameters:
324 +  A - the application ordering context
325 .  obj - Optional object
326 -  name - command line option
327 
328    Level: intermediate
329 .seealso: `SNES`, `SNESView`, `PetscObjectViewFromOptions()`, `SNESCreate()`
330 @*/
331 PetscErrorCode  SNESViewFromOptions(SNES A,PetscObject obj,const char name[])
332 {
333   PetscFunctionBegin;
334   PetscValidHeaderSpecific(A,SNES_CLASSID,1);
335   PetscCall(PetscObjectViewFromOptions((PetscObject)A,obj,name));
336   PetscFunctionReturn(0);
337 }
338 
339 PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES,Vec,Mat,Mat,void*);
340 
341 /*@C
342    SNESView - Prints the SNES data structure.
343 
344    Collective on SNES
345 
346    Input Parameters:
347 +  SNES - the SNES context
348 -  viewer - visualization context
349 
350    Options Database Key:
351 .  -snes_view - Calls SNESView() at end of SNESSolve()
352 
353    Notes:
354    The available visualization contexts include
355 +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
356 -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
357          output where only the first processor opens
358          the file.  All other processors send their
359          data to the first processor to print.
360 
361    The available formats include
362 +     PETSC_VIEWER_DEFAULT - standard output (default)
363 -     PETSC_VIEWER_ASCII_INFO_DETAIL - more verbose output for SNESNASM
364 
365    The user can open an alternative visualization context with
366    PetscViewerASCIIOpen() - output to a specified file.
367 
368   In the debugger you can do "call SNESView(snes,0)" to display the SNES solver. (The same holds for any PETSc object viewer).
369 
370    Level: beginner
371 
372 .seealso: `PetscViewerASCIIOpen()`
373 @*/
374 PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
375 {
376   SNESKSPEW      *kctx;
377   KSP            ksp;
378   SNESLineSearch linesearch;
379   PetscBool      iascii,isstring,isbinary,isdraw;
380   DMSNES         dmsnes;
381 #if defined(PETSC_HAVE_SAWS)
382   PetscBool      issaws;
383 #endif
384 
385   PetscFunctionBegin;
386   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
387   if (!viewer) {
388     PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer));
389   }
390   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
391   PetscCheckSameComm(snes,1,viewer,2);
392 
393   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii));
394   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring));
395   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
396   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw));
397 #if defined(PETSC_HAVE_SAWS)
398   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws));
399 #endif
400   if (iascii) {
401     SNESNormSchedule normschedule;
402     DM               dm;
403     PetscErrorCode   (*cJ)(SNES,Vec,Mat,Mat,void*);
404     void             *ctx;
405     const char       *pre = "";
406 
407     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer));
408     if (!snes->setupcalled) {
409       PetscCall(PetscViewerASCIIPrintf(viewer,"  SNES has not been set up so information may be incomplete\n"));
410     }
411     if (snes->ops->view) {
412       PetscCall(PetscViewerASCIIPushTab(viewer));
413       PetscCall((*snes->ops->view)(snes,viewer));
414       PetscCall(PetscViewerASCIIPopTab(viewer));
415     }
416     PetscCall(PetscViewerASCIIPrintf(viewer,"  maximum iterations=%" PetscInt_FMT ", maximum function evaluations=%" PetscInt_FMT "\n",snes->max_its,snes->max_funcs));
417     PetscCall(PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol));
418     if (snes->usesksp) {
419       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%" PetscInt_FMT "\n",snes->linear_its));
420     }
421     PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%" PetscInt_FMT "\n",snes->nfuncs));
422     PetscCall(SNESGetNormSchedule(snes, &normschedule));
423     if (normschedule > 0) PetscCall(PetscViewerASCIIPrintf(viewer,"  norm schedule %s\n",SNESNormSchedules[normschedule]));
424     if (snes->gridsequence) {
425       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of grid sequence refinements=%" PetscInt_FMT "\n",snes->gridsequence));
426     }
427     if (snes->ksp_ewconv) {
428       kctx = (SNESKSPEW*)snes->kspconvctx;
429       if (kctx) {
430         PetscCall(PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %" PetscInt_FMT ")\n",kctx->version));
431         PetscCall(PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold));
432         PetscCall(PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2));
433       }
434     }
435     if (snes->lagpreconditioner == -1) {
436       PetscCall(PetscViewerASCIIPrintf(viewer,"  Preconditioned is never rebuilt\n"));
437     } else if (snes->lagpreconditioner > 1) {
438       PetscCall(PetscViewerASCIIPrintf(viewer,"  Preconditioned is rebuilt every %" PetscInt_FMT " new Jacobians\n",snes->lagpreconditioner));
439     }
440     if (snes->lagjacobian == -1) {
441       PetscCall(PetscViewerASCIIPrintf(viewer,"  Jacobian is never rebuilt\n"));
442     } else if (snes->lagjacobian > 1) {
443       PetscCall(PetscViewerASCIIPrintf(viewer,"  Jacobian is rebuilt every %" PetscInt_FMT " SNES iterations\n",snes->lagjacobian));
444     }
445     PetscCall(SNESGetDM(snes,&dm));
446     PetscCall(DMSNESGetJacobian(dm,&cJ,&ctx));
447     if (snes->mf_operator) {
448       PetscCall(PetscViewerASCIIPrintf(viewer,"  Jacobian is applied matrix-free with differencing\n"));
449       pre  = "Preconditioning ";
450     }
451     if (cJ == SNESComputeJacobianDefault) {
452       PetscCall(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using finite differences one column at a time\n",pre));
453     } else if (cJ == SNESComputeJacobianDefaultColor) {
454       PetscCall(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using finite differences with coloring\n",pre));
455     /* it slightly breaks data encapsulation for access the DMDA information directly */
456     } else if (cJ == SNESComputeJacobian_DMDA) {
457       MatFDColoring fdcoloring;
458       PetscCall(PetscObjectQuery((PetscObject)dm,"DMDASNES_FDCOLORING",(PetscObject*)&fdcoloring));
459       if (fdcoloring) {
460         PetscCall(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using colored finite differences on a DMDA\n",pre));
461       } else {
462         PetscCall(PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using a DMDA local Jacobian\n",pre));
463       }
464     } else if (snes->mf) {
465       PetscCall(PetscViewerASCIIPrintf(viewer,"  Jacobian is applied matrix-free with differencing, no explicit Jacobian\n"));
466     }
467   } else if (isstring) {
468     const char *type;
469     PetscCall(SNESGetType(snes,&type));
470     PetscCall(PetscViewerStringSPrintf(viewer," SNESType: %-7.7s",type));
471     if (snes->ops->view) PetscCall((*snes->ops->view)(snes,viewer));
472   } else if (isbinary) {
473     PetscInt    classid = SNES_FILE_CLASSID;
474     MPI_Comm    comm;
475     PetscMPIInt rank;
476     char        type[256];
477 
478     PetscCall(PetscObjectGetComm((PetscObject)snes,&comm));
479     PetscCallMPI(MPI_Comm_rank(comm,&rank));
480     if (rank == 0) {
481       PetscCall(PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT));
482       PetscCall(PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type)));
483       PetscCall(PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR));
484     }
485     if (snes->ops->view) PetscCall((*snes->ops->view)(snes,viewer));
486   } else if (isdraw) {
487     PetscDraw draw;
488     char      str[36];
489     PetscReal x,y,bottom,h;
490 
491     PetscCall(PetscViewerDrawGetDraw(viewer,0,&draw));
492     PetscCall(PetscDrawGetCurrentPoint(draw,&x,&y));
493     PetscCall(PetscStrncpy(str,"SNES: ",sizeof(str)));
494     PetscCall(PetscStrlcat(str,((PetscObject)snes)->type_name,sizeof(str)));
495     PetscCall(PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h));
496     bottom = y - h;
497     PetscCall(PetscDrawPushCurrentPoint(draw,x,bottom));
498     if (snes->ops->view) PetscCall((*snes->ops->view)(snes,viewer));
499 #if defined(PETSC_HAVE_SAWS)
500   } else if (issaws) {
501     PetscMPIInt rank;
502     const char *name;
503 
504     PetscCall(PetscObjectGetName((PetscObject)snes,&name));
505     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD,&rank));
506     if (!((PetscObject)snes)->amsmem && rank == 0) {
507       char       dir[1024];
508 
509       PetscCall(PetscObjectViewSAWs((PetscObject)snes,viewer));
510       PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name));
511       PetscCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
512       if (!snes->conv_hist) {
513         PetscCall(SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE));
514       }
515       PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name));
516       PetscCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
517     }
518 #endif
519   }
520   if (snes->linesearch) {
521     PetscCall(SNESGetLineSearch(snes, &linesearch));
522     PetscCall(PetscViewerASCIIPushTab(viewer));
523     PetscCall(SNESLineSearchView(linesearch, viewer));
524     PetscCall(PetscViewerASCIIPopTab(viewer));
525   }
526   if (snes->npc && snes->usesnpc) {
527     PetscCall(PetscViewerASCIIPushTab(viewer));
528     PetscCall(SNESView(snes->npc, viewer));
529     PetscCall(PetscViewerASCIIPopTab(viewer));
530   }
531   PetscCall(PetscViewerASCIIPushTab(viewer));
532   PetscCall(DMGetDMSNES(snes->dm,&dmsnes));
533   PetscCall(DMSNESView(dmsnes, viewer));
534   PetscCall(PetscViewerASCIIPopTab(viewer));
535   if (snes->usesksp) {
536     PetscCall(SNESGetKSP(snes,&ksp));
537     PetscCall(PetscViewerASCIIPushTab(viewer));
538     PetscCall(KSPView(ksp,viewer));
539     PetscCall(PetscViewerASCIIPopTab(viewer));
540   }
541   if (isdraw) {
542     PetscDraw draw;
543     PetscCall(PetscViewerDrawGetDraw(viewer,0,&draw));
544     PetscCall(PetscDrawPopCurrentPoint(draw));
545   }
546   PetscFunctionReturn(0);
547 }
548 
549 /*
550   We retain a list of functions that also take SNES command
551   line options. These are called at the end SNESSetFromOptions()
552 */
553 #define MAXSETFROMOPTIONS 5
554 static PetscInt numberofsetfromoptions;
555 static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);
556 
557 /*@C
558   SNESAddOptionsChecker - Adds an additional function to check for SNES options.
559 
560   Not Collective
561 
562   Input Parameter:
563 . snescheck - function that checks for options
564 
565   Level: developer
566 
567 .seealso: `SNESSetFromOptions()`
568 @*/
569 PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
570 {
571   PetscFunctionBegin;
572   PetscCheck(numberofsetfromoptions < MAXSETFROMOPTIONS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %d allowed", MAXSETFROMOPTIONS);
573   othersetfromoptions[numberofsetfromoptions++] = snescheck;
574   PetscFunctionReturn(0);
575 }
576 
577 PETSC_INTERN PetscErrorCode SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*);
578 
579 static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
580 {
581   Mat            J;
582   MatNullSpace   nullsp;
583 
584   PetscFunctionBegin;
585   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
586 
587   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
588     Mat A = snes->jacobian, B = snes->jacobian_pre;
589     PetscCall(MatCreateVecs(A ? A : B, NULL,&snes->vec_func));
590   }
591 
592   if (version == 1) {
593     PetscCall(MatCreateSNESMF(snes,&J));
594     PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
595     PetscCall(MatSetFromOptions(J));
596     /* TODO: the version 2 code should be merged into the MatCreateSNESMF() and MatCreateMFFD() infrastructure and then removed */
597   } else if (version == 2) {
598     PetscCheck(snes->vec_func,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
599 #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
600     PetscCall(SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J));
601 #else
602     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
603 #endif
604   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");
605 
606   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
607   if (snes->jacobian) {
608     PetscCall(MatGetNullSpace(snes->jacobian,&nullsp));
609     if (nullsp) PetscCall(MatSetNullSpace(J,nullsp));
610   }
611 
612   PetscCall(PetscInfo(snes,"Setting default matrix-free operator routines (version %" PetscInt_FMT ")\n", version));
613   if (hasOperator) {
614 
615     /* This version replaces the user provided Jacobian matrix with a
616        matrix-free version but still employs the user-provided preconditioner matrix. */
617     PetscCall(SNESSetJacobian(snes,J,NULL,NULL,NULL));
618   } else {
619     /* This version replaces both the user-provided Jacobian and the user-
620      provided preconditioner Jacobian with the default matrix free version. */
621     if (snes->npcside == PC_LEFT && snes->npc) {
622       if (!snes->jacobian) PetscCall(SNESSetJacobian(snes,J,NULL,NULL,NULL));
623     } else {
624       KSP       ksp;
625       PC        pc;
626       PetscBool match;
627 
628       PetscCall(SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,NULL));
629       /* Force no preconditioner */
630       PetscCall(SNESGetKSP(snes,&ksp));
631       PetscCall(KSPGetPC(ksp,&pc));
632       PetscCall(PetscObjectTypeCompareAny((PetscObject)pc,&match,PCSHELL,PCH2OPUS,""));
633       if (!match) {
634         PetscCall(PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n"));
635         PetscCall(PCSetType(pc,PCNONE));
636       }
637     }
638   }
639   PetscCall(MatDestroy(&J));
640   PetscFunctionReturn(0);
641 }
642 
643 static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
644 {
645   SNES           snes = (SNES)ctx;
646   Vec            Xfine,Xfine_named = NULL,Xcoarse;
647 
648   PetscFunctionBegin;
649   if (PetscLogPrintInfo) {
650     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
651     PetscCall(DMGetRefineLevel(dmfine,&finelevel));
652     PetscCall(DMGetCoarsenLevel(dmfine,&fineclevel));
653     PetscCall(DMGetRefineLevel(dmcoarse,&coarselevel));
654     PetscCall(DMGetCoarsenLevel(dmcoarse,&coarseclevel));
655     PetscCall(PetscInfo(dmfine,"Restricting SNES solution vector from level %" PetscInt_FMT "-%" PetscInt_FMT " to level %" PetscInt_FMT "-%" PetscInt_FMT "\n",finelevel,fineclevel,coarselevel,coarseclevel));
656   }
657   if (dmfine == snes->dm) Xfine = snes->vec_sol;
658   else {
659     PetscCall(DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named));
660     Xfine = Xfine_named;
661   }
662   PetscCall(DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse));
663   if (Inject) {
664     PetscCall(MatRestrict(Inject,Xfine,Xcoarse));
665   } else {
666     PetscCall(MatRestrict(Restrict,Xfine,Xcoarse));
667     PetscCall(VecPointwiseMult(Xcoarse,Xcoarse,Rscale));
668   }
669   PetscCall(DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse));
670   if (Xfine_named) PetscCall(DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named));
671   PetscFunctionReturn(0);
672 }
673 
674 static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
675 {
676   PetscFunctionBegin;
677   PetscCall(DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx));
678   PetscFunctionReturn(0);
679 }
680 
681 /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
682  * safely call SNESGetDM() in their residual evaluation routine. */
683 static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
684 {
685   SNES           snes = (SNES)ctx;
686   Vec            X,Xnamed = NULL;
687   DM             dmsave;
688   void           *ctxsave;
689   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL;
690 
691   PetscFunctionBegin;
692   dmsave = snes->dm;
693   PetscCall(KSPGetDM(ksp,&snes->dm));
694   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
695   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
696     PetscCall(DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed));
697     X    = Xnamed;
698     PetscCall(SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave));
699     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
700     if (jac == SNESComputeJacobianDefaultColor) {
701       PetscCall(SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,NULL));
702     }
703   }
704   /* Make sure KSP DM has the Jacobian computation routine */
705   {
706     DMSNES sdm;
707 
708     PetscCall(DMGetDMSNES(snes->dm, &sdm));
709     if (!sdm->ops->computejacobian) {
710       PetscCall(DMCopyDMSNES(dmsave, snes->dm));
711     }
712   }
713   /* Compute the operators */
714   PetscCall(SNESComputeJacobian(snes,X,A,B));
715   /* Put the previous context back */
716   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
717     PetscCall(SNESSetJacobian(snes,NULL,NULL,jac,ctxsave));
718   }
719 
720   if (Xnamed) PetscCall(DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed));
721   snes->dm = dmsave;
722   PetscFunctionReturn(0);
723 }
724 
725 /*@
726    SNESSetUpMatrices - ensures that matrices are available for SNES, to be called by SNESSetUp_XXX()
727 
728    Collective
729 
730    Input Parameter:
731 .  snes - snes to configure
732 
733    Level: developer
734 
735 .seealso: `SNESSetUp()`
736 @*/
737 PetscErrorCode SNESSetUpMatrices(SNES snes)
738 {
739   DM             dm;
740   DMSNES         sdm;
741 
742   PetscFunctionBegin;
743   PetscCall(SNESGetDM(snes,&dm));
744   PetscCall(DMGetDMSNES(dm,&sdm));
745   if (!snes->jacobian && snes->mf) {
746     Mat  J;
747     void *functx;
748     PetscCall(MatCreateSNESMF(snes,&J));
749     PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
750     PetscCall(MatSetFromOptions(J));
751     PetscCall(SNESGetFunction(snes,NULL,NULL,&functx));
752     PetscCall(SNESSetJacobian(snes,J,J,NULL,NULL));
753     PetscCall(MatDestroy(&J));
754   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
755     Mat J,B;
756     PetscCall(MatCreateSNESMF(snes,&J));
757     PetscCall(MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix));
758     PetscCall(MatSetFromOptions(J));
759     PetscCall(DMCreateMatrix(snes->dm,&B));
760     /* sdm->computejacobian was already set to reach here */
761     PetscCall(SNESSetJacobian(snes,J,B,NULL,NULL));
762     PetscCall(MatDestroy(&J));
763     PetscCall(MatDestroy(&B));
764   } else if (!snes->jacobian_pre) {
765     PetscDS   prob;
766     Mat       J, B;
767     PetscBool hasPrec   = PETSC_FALSE;
768 
769     J    = snes->jacobian;
770     PetscCall(DMGetDS(dm, &prob));
771     if (prob) PetscCall(PetscDSHasJacobianPreconditioner(prob, &hasPrec));
772     if (J)            PetscCall(PetscObjectReference((PetscObject) J));
773     else if (hasPrec) PetscCall(DMCreateMatrix(snes->dm, &J));
774     PetscCall(DMCreateMatrix(snes->dm, &B));
775     PetscCall(SNESSetJacobian(snes, J ? J : B, B, NULL, NULL));
776     PetscCall(MatDestroy(&J));
777     PetscCall(MatDestroy(&B));
778   }
779   {
780     KSP ksp;
781     PetscCall(SNESGetKSP(snes,&ksp));
782     PetscCall(KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes));
783     PetscCall(DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes));
784   }
785   PetscFunctionReturn(0);
786 }
787 
788 static PetscErrorCode SNESMonitorPauseFinal_Internal(SNES snes)
789 {
790   PetscInt       i;
791 
792   PetscFunctionBegin;
793   if (!snes->pauseFinal) PetscFunctionReturn(0);
794   for (i = 0; i < snes->numbermonitors; ++i) {
795     PetscViewerAndFormat *vf = (PetscViewerAndFormat *) snes->monitorcontext[i];
796     PetscDraw             draw;
797     PetscReal             lpause;
798 
799     if (!vf) continue;
800     if (vf->lg) {
801       if (!PetscCheckPointer(vf->lg, PETSC_OBJECT)) continue;
802       if (((PetscObject) vf->lg)->classid != PETSC_DRAWLG_CLASSID) continue;
803       PetscCall(PetscDrawLGGetDraw(vf->lg, &draw));
804       PetscCall(PetscDrawGetPause(draw, &lpause));
805       PetscCall(PetscDrawSetPause(draw, -1.0));
806       PetscCall(PetscDrawPause(draw));
807       PetscCall(PetscDrawSetPause(draw, lpause));
808     } else {
809       PetscBool isdraw;
810 
811       if (!PetscCheckPointer(vf->viewer, PETSC_OBJECT)) continue;
812       if (((PetscObject) vf->viewer)->classid != PETSC_VIEWER_CLASSID) continue;
813       PetscCall(PetscObjectTypeCompare((PetscObject) vf->viewer, PETSCVIEWERDRAW, &isdraw));
814       if (!isdraw) continue;
815       PetscCall(PetscViewerDrawGetDraw(vf->viewer, 0, &draw));
816       PetscCall(PetscDrawGetPause(draw, &lpause));
817       PetscCall(PetscDrawSetPause(draw, -1.0));
818       PetscCall(PetscDrawPause(draw));
819       PetscCall(PetscDrawSetPause(draw, lpause));
820     }
821   }
822   PetscFunctionReturn(0);
823 }
824 
825 /*@C
826    SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
827 
828    Collective on SNES
829 
830    Input Parameters:
831 +  snes - SNES object you wish to monitor
832 .  name - the monitor type one is seeking
833 .  help - message indicating what monitoring is done
834 .  manual - manual page for the monitor
835 .  monitor - the monitor function
836 -  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
837 
838    Level: developer
839 
840 .seealso: `PetscOptionsGetViewer()`, `PetscOptionsGetReal()`, `PetscOptionsHasName()`, `PetscOptionsGetString()`,
841           `PetscOptionsGetIntArray()`, `PetscOptionsGetRealArray()`, `PetscOptionsBool()`
842           `PetscOptionsInt()`, `PetscOptionsString()`, `PetscOptionsReal()`, `PetscOptionsBool()`,
843           `PetscOptionsName()`, `PetscOptionsBegin()`, `PetscOptionsEnd()`, `PetscOptionsHeadBegin()`,
844           `PetscOptionsStringArray()`, `PetscOptionsRealArray()`, `PetscOptionsScalar()`,
845           `PetscOptionsBoolGroupBegin()`, `PetscOptionsBoolGroup()`, `PetscOptionsBoolGroupEnd()`,
846           `PetscOptionsFList()`, `PetscOptionsEList()`
847 @*/
848 PetscErrorCode  SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
849 {
850   PetscViewer       viewer;
851   PetscViewerFormat format;
852   PetscBool         flg;
853 
854   PetscFunctionBegin;
855   PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,name,&viewer,&format,&flg));
856   if (flg) {
857     PetscViewerAndFormat *vf;
858     PetscCall(PetscViewerAndFormatCreate(viewer,format,&vf));
859     PetscCall(PetscObjectDereference((PetscObject)viewer));
860     if (monitorsetup) PetscCall((*monitorsetup)(snes,vf));
861     PetscCall(SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy));
862   }
863   PetscFunctionReturn(0);
864 }
865 
866 PetscErrorCode SNESEWSetFromOptions_Private(SNESKSPEW* kctx, MPI_Comm comm, const char* prefix)
867 {
868   PetscFunctionBegin;
869   PetscOptionsBegin(comm,prefix,"Eisenstat and Walker type forcing options","KSP");
870   PetscCall(PetscOptionsInt("-ksp_ew_version","Version 1, 2 or 3",NULL,kctx->version,&kctx->version,NULL));
871   PetscCall(PetscOptionsReal("-ksp_ew_rtol0","0 <= rtol0 < 1",NULL,kctx->rtol_0,&kctx->rtol_0,NULL));
872   PetscCall(PetscOptionsReal("-ksp_ew_rtolmax","0 <= rtolmax < 1",NULL,kctx->rtol_max,&kctx->rtol_max,NULL));
873   PetscCall(PetscOptionsReal("-ksp_ew_gamma","0 <= gamma <= 1",NULL,kctx->gamma,&kctx->gamma,NULL));
874   PetscCall(PetscOptionsReal("-ksp_ew_alpha","1 < alpha <= 2",NULL,kctx->alpha,&kctx->alpha,NULL));
875   PetscCall(PetscOptionsReal("-ksp_ew_alpha2","alpha2",NULL,kctx->alpha2,&kctx->alpha2,NULL));
876   PetscCall(PetscOptionsReal("-ksp_ew_threshold","0 < threshold < 1",NULL,kctx->threshold,&kctx->threshold,NULL));
877   PetscCall(PetscOptionsReal("-ksp_ew_v4_p1","p1",NULL,kctx->v4_p1,&kctx->v4_p1,NULL));
878   PetscCall(PetscOptionsReal("-ksp_ew_v4_p2","p2",NULL,kctx->v4_p2,&kctx->v4_p2,NULL));
879   PetscCall(PetscOptionsReal("-ksp_ew_v4_p3","p3",NULL,kctx->v4_p3,&kctx->v4_p3,NULL));
880   PetscCall(PetscOptionsReal("-ksp_ew_v4_m1","Scaling when rk-1 in [p2,p3)",NULL,kctx->v4_m1,&kctx->v4_m1,NULL));
881   PetscCall(PetscOptionsReal("-ksp_ew_v4_m2","Scaling when rk-1 in [p3,+infty)",NULL,kctx->v4_m2,&kctx->v4_m2,NULL));
882   PetscCall(PetscOptionsReal("-ksp_ew_v4_m3","Threshold for successive rtol (0.1 in Eq.7)",NULL,kctx->v4_m3,&kctx->v4_m3,NULL));
883   PetscCall(PetscOptionsReal("-ksp_ew_v4_m4","Adaptation scaling (0.5 in Eq.7)",NULL,kctx->v4_m4,&kctx->v4_m4,NULL));
884   PetscOptionsEnd();
885   PetscFunctionReturn(0);
886 }
887 
888 /*@
889    SNESSetFromOptions - Sets various SNES and KSP parameters from user options.
890 
891    Collective on SNES
892 
893    Input Parameter:
894 .  snes - the SNES context
895 
896    Options Database Keys:
897 +  -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
898 .  -snes_stol - convergence tolerance in terms of the norm
899                 of the change in the solution between steps
900 .  -snes_atol <abstol> - absolute tolerance of residual norm
901 .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
902 .  -snes_divergence_tolerance <divtol> - if the residual goes above divtol*rnorm0, exit with divergence
903 .  -snes_force_iteration <force> - force SNESSolve() to take at least one iteration
904 .  -snes_max_it <max_it> - maximum number of iterations
905 .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
906 .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
907 .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
908 .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
909 .  -snes_lag_preconditioner_persists <true,false> - retains the -snes_lag_preconditioner information across multiple SNESSolve()
910 .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
911 .  -snes_lag_jacobian_persists <true,false> - retains the -snes_lag_jacobian information across multiple SNESSolve()
912 .  -snes_trtol <trtol> - trust region tolerance
913 .  -snes_convergence_test - <default,skip,correct_pressure> convergence test in nonlinear solver.
914                                default SNESConvergedDefault(). skip SNESConvergedSkip() means continue iterating until max_it or some other criterion is reached, saving expense
915                                of convergence test. correct_pressure SNESConvergedCorrectPressure() has special handling of a pressure null space.
916 .  -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
917 .  -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
918 .  -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
919 .  -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
920 .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
921 .  -snes_monitor_lg_range - plots residual norm at each iteration
922 .  -snes_monitor_pause_final - Pauses all monitor drawing after the solver ends
923 .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
924 .  -snes_fd_color - use finite differences with coloring to compute Jacobian
925 .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
926 .  -snes_converged_reason - print the reason for convergence/divergence after each solve
927 .  -npc_snes_type <type> - the SNES type to use as a nonlinear preconditioner
928 .   -snes_test_jacobian <optional threshold> - compare the user provided Jacobian with one computed via finite differences to check for errors.  If a threshold is given, display only those entries whose difference is greater than the threshold.
929 -   -snes_test_jacobian_view - 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.
930 
931     Options Database for Eisenstat-Walker method:
932 +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
933 .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
934 .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
935 .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
936 .  -snes_ksp_ew_gamma <gamma> - Sets gamma
937 .  -snes_ksp_ew_alpha <alpha> - Sets alpha
938 .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
939 -  -snes_ksp_ew_threshold <threshold> - Sets threshold
940 
941    Notes:
942    To see all options, run your program with the -help option or consult the users manual
943 
944    Notes:
945       SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explicitly with
946       finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.
947 
948    Level: beginner
949 
950 .seealso: `SNESSetOptionsPrefix()`, `SNESResetFromOptions()`, `SNES`, `SNESCreate()`
951 @*/
952 PetscErrorCode  SNESSetFromOptions(SNES snes)
953 {
954   PetscBool      flg,pcset,persist,set;
955   PetscInt       i,indx,lag,grids;
956   const char     *deft        = SNESNEWTONLS;
957   const char     *convtests[] = {"default","skip","correct_pressure"};
958   SNESKSPEW      *kctx        = NULL;
959   char           type[256], monfilename[PETSC_MAX_PATH_LEN], ewprefix[256];
960   PCSide         pcside;
961   const char     *optionsprefix;
962 
963   PetscFunctionBegin;
964   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
965   PetscCall(SNESRegisterAll());
966   PetscObjectOptionsBegin((PetscObject)snes);
967   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
968   PetscCall(PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg));
969   if (flg) {
970     PetscCall(SNESSetType(snes,type));
971   } else if (!((PetscObject)snes)->type_name) {
972     PetscCall(SNESSetType(snes,deft));
973   }
974   PetscCall(PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL));
975   PetscCall(PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL));
976 
977   PetscCall(PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL));
978   PetscCall(PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL));
979   PetscCall(PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL));
980   PetscCall(PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL));
981   PetscCall(PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL));
982   PetscCall(PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL));
983   PetscCall(PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL));
984   PetscCall(PetscOptionsBool("-snes_force_iteration","Force SNESSolve() to take at least one iteration","SNESSetForceIteration",snes->forceiteration,&snes->forceiteration,NULL));
985   PetscCall(PetscOptionsBool("-snes_check_jacobian_domain_error","Check Jacobian domain error after Jacobian evaluation","SNESCheckJacobianDomainError",snes->checkjacdomainerror,&snes->checkjacdomainerror,NULL));
986 
987   PetscCall(PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg));
988   if (flg) {
989     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");
990     PetscCall(SNESSetLagPreconditioner(snes,lag));
991   }
992   PetscCall(PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple SNES solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg));
993   if (flg) PetscCall(SNESSetLagPreconditionerPersists(snes,persist));
994   PetscCall(PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg));
995   if (flg) {
996     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");
997     PetscCall(SNESSetLagJacobian(snes,lag));
998   }
999   PetscCall(PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple SNES solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg));
1000   if (flg) PetscCall(SNESSetLagJacobianPersists(snes,persist));
1001 
1002   PetscCall(PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg));
1003   if (flg) PetscCall(SNESSetGridSequence(snes,grids));
1004 
1005   PetscCall(PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,sizeof(convtests)/sizeof(char*),"default",&indx,&flg));
1006   if (flg) {
1007     switch (indx) {
1008     case 0: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL)); break;
1009     case 1: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL)); break;
1010     case 2: PetscCall(SNESSetConvergenceTest(snes,SNESConvergedCorrectPressure,NULL,NULL)); break;
1011     }
1012   }
1013 
1014   PetscCall(PetscOptionsEList("-snes_norm_schedule","SNES Norm schedule","SNESSetNormSchedule",SNESNormSchedules,5,"function",&indx,&flg));
1015   if (flg) PetscCall(SNESSetNormSchedule(snes,(SNESNormSchedule)indx));
1016 
1017   PetscCall(PetscOptionsEList("-snes_function_type","SNES Norm schedule","SNESSetFunctionType",SNESFunctionTypes,2,"unpreconditioned",&indx,&flg));
1018   if (flg) PetscCall(SNESSetFunctionType(snes,(SNESFunctionType)indx));
1019 
1020   kctx = (SNESKSPEW*)snes->kspconvctx;
1021 
1022   PetscCall(PetscOptionsBool("-snes_ksp_ew","Use Eisentat-Walker linear system convergence test","SNESKSPSetUseEW",snes->ksp_ewconv,&snes->ksp_ewconv,NULL));
1023 
1024   PetscCall(SNESGetOptionsPrefix(snes,&optionsprefix));
1025   PetscCall(PetscSNPrintf(ewprefix,sizeof(ewprefix),"%s%s",optionsprefix ? optionsprefix : "","snes_"));
1026   PetscCall(SNESEWSetFromOptions_Private(kctx,PetscObjectComm((PetscObject)snes),ewprefix));
1027 
1028   PetscCall(PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL));
1029   PetscCall(PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL));
1030   PetscCall(PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL));
1031   PetscCall(PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL));
1032   PetscCall(PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL));
1033   PetscCall(PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL));
1034   PetscCall(PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL));
1035 
1036   flg  = PETSC_FALSE;
1037   PetscCall(PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set));
1038   if (set && flg) PetscCall(SNESMonitorCancel(snes));
1039 
1040   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor","Monitor norm of function","SNESMonitorDefault",SNESMonitorDefault,SNESMonitorDefaultSetUp));
1041   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_short","Monitor norm of function with fewer digits","SNESMonitorDefaultShort",SNESMonitorDefaultShort,NULL));
1042   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_range","Monitor range of elements of function","SNESMonitorRange",SNESMonitorRange,NULL));
1043 
1044   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp));
1045   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL));
1046   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL));
1047   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL));
1048   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL));
1049   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL));
1050   PetscCall(SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL));
1051   PetscCall(PetscOptionsBool("-snes_monitor_pause_final", "Pauses all draw monitors at the final iterate", "SNESMonitorPauseFinal_Internal", PETSC_FALSE, &snes->pauseFinal, NULL));
1052 
1053   PetscCall(PetscOptionsString("-snes_monitor_python","Use Python function","SNESMonitorSet",NULL,monfilename,sizeof(monfilename),&flg));
1054   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)snes,monfilename));
1055 
1056   flg  = PETSC_FALSE;
1057   PetscCall(PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL));
1058   if (flg) {
1059     PetscViewer ctx;
1060 
1061     PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx));
1062     PetscCall(SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy));
1063   }
1064 
1065   flg  = PETSC_FALSE;
1066   PetscCall(PetscOptionsBool("-snes_converged_reason_view_cancel","Remove all converged reason viewers","SNESConvergedReasonViewCancel",flg,&flg,&set));
1067   if (set && flg) PetscCall(SNESConvergedReasonViewCancel(snes));
1068 
1069   flg  = PETSC_FALSE;
1070   PetscCall(PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL));
1071   if (flg) {
1072     void    *functx;
1073     DM      dm;
1074     PetscCall(SNESGetDM(snes,&dm));
1075     PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1076     PetscCall(SNESGetFunction(snes,NULL,NULL,&functx));
1077     PetscCall(SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx));
1078     PetscCall(PetscInfo(snes,"Setting default finite difference Jacobian matrix\n"));
1079   }
1080 
1081   flg  = PETSC_FALSE;
1082   PetscCall(PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL));
1083   if (flg) PetscCall(SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL));
1084 
1085   flg  = PETSC_FALSE;
1086   PetscCall(PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL));
1087   if (flg) {
1088     DM             dm;
1089     PetscCall(SNESGetDM(snes,&dm));
1090     PetscCall(DMSNESUnsetJacobianContext_Internal(dm));
1091     PetscCall(SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,NULL));
1092     PetscCall(PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n"));
1093   }
1094 
1095   flg  = PETSC_FALSE;
1096   PetscCall(PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg));
1097   if (flg && snes->mf_operator) {
1098     snes->mf_operator = PETSC_TRUE;
1099     snes->mf          = PETSC_TRUE;
1100   }
1101   flg  = PETSC_FALSE;
1102   PetscCall(PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg));
1103   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1104   PetscCall(PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,NULL));
1105 
1106   flg  = PETSC_FALSE;
1107   PetscCall(SNESGetNPCSide(snes,&pcside));
1108   PetscCall(PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg));
1109   if (flg) PetscCall(SNESSetNPCSide(snes,pcside));
1110 
1111 #if defined(PETSC_HAVE_SAWS)
1112   /*
1113     Publish convergence information using SAWs
1114   */
1115   flg  = PETSC_FALSE;
1116   PetscCall(PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL));
1117   if (flg) {
1118     void *ctx;
1119     PetscCall(SNESMonitorSAWsCreate(snes,&ctx));
1120     PetscCall(SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy));
1121   }
1122 #endif
1123 #if defined(PETSC_HAVE_SAWS)
1124   {
1125   PetscBool set;
1126   flg  = PETSC_FALSE;
1127   PetscCall(PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set));
1128   if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)snes,flg));
1129   }
1130 #endif
1131 
1132   for (i = 0; i < numberofsetfromoptions; i++) {
1133     PetscCall((*othersetfromoptions[i])(snes));
1134   }
1135 
1136   if (snes->ops->setfromoptions) PetscCall((*snes->ops->setfromoptions)(PetscOptionsObject,snes));
1137 
1138   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1139   PetscCall(PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes));
1140   PetscOptionsEnd();
1141 
1142   if (snes->linesearch) {
1143     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
1144     PetscCall(SNESLineSearchSetFromOptions(snes->linesearch));
1145   }
1146 
1147   if (snes->usesksp) {
1148     if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp));
1149     PetscCall(KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre));
1150     PetscCall(KSPSetFromOptions(snes->ksp));
1151   }
1152 
1153   /* if user has set the SNES NPC type via options database, create it. */
1154   PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
1155   PetscCall(PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset));
1156   if (pcset && (!snes->npc)) {
1157     PetscCall(SNESGetNPC(snes, &snes->npc));
1158   }
1159   if (snes->npc) PetscCall(SNESSetFromOptions(snes->npc));
1160   snes->setfromoptionscalled++;
1161   PetscFunctionReturn(0);
1162 }
1163 
1164 /*@
1165    SNESResetFromOptions - Sets various SNES and KSP parameters from user options ONLY if the SNES was previously set from options
1166 
1167    Collective on SNES
1168 
1169    Input Parameter:
1170 .  snes - the SNES context
1171 
1172    Level: beginner
1173 
1174 .seealso: `SNESSetFromOptions()`, `SNESSetOptionsPrefix()`
1175 @*/
1176 PetscErrorCode SNESResetFromOptions(SNES snes)
1177 {
1178   PetscFunctionBegin;
1179   if (snes->setfromoptionscalled) PetscCall(SNESSetFromOptions(snes));
1180   PetscFunctionReturn(0);
1181 }
1182 
1183 /*@C
1184    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1185    the nonlinear solvers.
1186 
1187    Logically Collective on SNES
1188 
1189    Input Parameters:
1190 +  snes - the SNES context
1191 .  compute - function to compute the context
1192 -  destroy - function to destroy the context
1193 
1194    Level: intermediate
1195 
1196    Notes:
1197    This function is currently not available from Fortran.
1198 
1199 .seealso: `SNESGetApplicationContext()`, `SNESSetComputeApplicationContext()`, `SNESGetApplicationContext()`
1200 @*/
1201 PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1202 {
1203   PetscFunctionBegin;
1204   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1205   snes->ops->usercompute = compute;
1206   snes->ops->userdestroy = destroy;
1207   PetscFunctionReturn(0);
1208 }
1209 
1210 /*@
1211    SNESSetApplicationContext - Sets the optional user-defined context for
1212    the nonlinear solvers.
1213 
1214    Logically Collective on SNES
1215 
1216    Input Parameters:
1217 +  snes - the SNES context
1218 -  usrP - optional user context
1219 
1220    Level: intermediate
1221 
1222    Fortran Notes:
1223     To use this from Fortran you must write a Fortran interface definition for this
1224     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1225 
1226 .seealso: `SNESGetApplicationContext()`
1227 @*/
1228 PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1229 {
1230   KSP            ksp;
1231 
1232   PetscFunctionBegin;
1233   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1234   PetscCall(SNESGetKSP(snes,&ksp));
1235   PetscCall(KSPSetApplicationContext(ksp,usrP));
1236   snes->user = usrP;
1237   PetscFunctionReturn(0);
1238 }
1239 
1240 /*@
1241    SNESGetApplicationContext - Gets the user-defined context for the
1242    nonlinear solvers.
1243 
1244    Not Collective
1245 
1246    Input Parameter:
1247 .  snes - SNES context
1248 
1249    Output Parameter:
1250 .  usrP - user context
1251 
1252    Fortran Notes:
1253     To use this from Fortran you must write a Fortran interface definition for this
1254     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
1255 
1256    Level: intermediate
1257 
1258 .seealso: `SNESSetApplicationContext()`
1259 @*/
1260 PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1261 {
1262   PetscFunctionBegin;
1263   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1264   *(void**)usrP = snes->user;
1265   PetscFunctionReturn(0);
1266 }
1267 
1268 /*@
1269    SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply the Jacobian.
1270 
1271    Collective on SNES
1272 
1273    Input Parameters:
1274 +  snes - SNES context
1275 .  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
1276 -  mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
1277 
1278    Options Database:
1279 + -snes_mf - use matrix free for both the mat and pmat operator
1280 . -snes_mf_operator - use matrix free only for the mat operator
1281 . -snes_fd_color - compute the Jacobian via coloring and finite differences.
1282 - -snes_fd - compute the Jacobian via finite differences (slow)
1283 
1284    Level: intermediate
1285 
1286    Notes:
1287       SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explicitly with
1288       finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.
1289 
1290 .seealso: `SNESGetUseMatrixFree()`, `MatCreateSNESMF()`, `SNESComputeJacobianDefaultColor()`
1291 @*/
1292 PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1293 {
1294   PetscFunctionBegin;
1295   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1296   PetscValidLogicalCollectiveBool(snes,mf_operator,2);
1297   PetscValidLogicalCollectiveBool(snes,mf,3);
1298   snes->mf          = mf_operator ? PETSC_TRUE : mf;
1299   snes->mf_operator = mf_operator;
1300   PetscFunctionReturn(0);
1301 }
1302 
1303 /*@
1304    SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply the Jacobian.
1305 
1306    Collective on SNES
1307 
1308    Input Parameter:
1309 .  snes - SNES context
1310 
1311    Output Parameters:
1312 +  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used
1313 -  mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
1314 
1315    Options Database:
1316 + -snes_mf - use matrix free for both the mat and pmat operator
1317 - -snes_mf_operator - use matrix free only for the mat operator
1318 
1319    Level: intermediate
1320 
1321 .seealso: `SNESSetUseMatrixFree()`, `MatCreateSNESMF()`
1322 @*/
1323 PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1324 {
1325   PetscFunctionBegin;
1326   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1327   if (mf)          *mf          = snes->mf;
1328   if (mf_operator) *mf_operator = snes->mf_operator;
1329   PetscFunctionReturn(0);
1330 }
1331 
1332 /*@
1333    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1334    at this time.
1335 
1336    Not Collective
1337 
1338    Input Parameter:
1339 .  snes - SNES context
1340 
1341    Output Parameter:
1342 .  iter - iteration number
1343 
1344    Notes:
1345    For example, during the computation of iteration 2 this would return 1.
1346 
1347    This is useful for using lagged Jacobians (where one does not recompute the
1348    Jacobian at each SNES iteration). For example, the code
1349 .vb
1350       ierr = SNESGetIterationNumber(snes,&it);
1351       if (!(it % 2)) {
1352         [compute Jacobian here]
1353       }
1354 .ve
1355    can be used in your ComputeJacobian() function to cause the Jacobian to be
1356    recomputed every second SNES iteration.
1357 
1358    After the SNES solve is complete this will return the number of nonlinear iterations used.
1359 
1360    Level: intermediate
1361 
1362 .seealso: `SNESGetLinearSolveIterations()`
1363 @*/
1364 PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1365 {
1366   PetscFunctionBegin;
1367   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1368   PetscValidIntPointer(iter,2);
1369   *iter = snes->iter;
1370   PetscFunctionReturn(0);
1371 }
1372 
1373 /*@
1374    SNESSetIterationNumber - Sets the current iteration number.
1375 
1376    Not Collective
1377 
1378    Input Parameters:
1379 +  snes - SNES context
1380 -  iter - iteration number
1381 
1382    Level: developer
1383 
1384 .seealso: `SNESGetLinearSolveIterations()`
1385 @*/
1386 PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1387 {
1388   PetscFunctionBegin;
1389   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1390   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
1391   snes->iter = iter;
1392   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
1393   PetscFunctionReturn(0);
1394 }
1395 
1396 /*@
1397    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1398    attempted by the nonlinear solver.
1399 
1400    Not Collective
1401 
1402    Input Parameter:
1403 .  snes - SNES context
1404 
1405    Output Parameter:
1406 .  nfails - number of unsuccessful steps attempted
1407 
1408    Notes:
1409    This counter is reset to zero for each successive call to SNESSolve().
1410 
1411    Level: intermediate
1412 
1413 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1414           `SNESSetMaxNonlinearStepFailures()`, `SNESGetMaxNonlinearStepFailures()`
1415 @*/
1416 PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1417 {
1418   PetscFunctionBegin;
1419   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1420   PetscValidIntPointer(nfails,2);
1421   *nfails = snes->numFailures;
1422   PetscFunctionReturn(0);
1423 }
1424 
1425 /*@
1426    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1427    attempted by the nonlinear solver before it gives up.
1428 
1429    Not Collective
1430 
1431    Input Parameters:
1432 +  snes     - SNES context
1433 -  maxFails - maximum of unsuccessful steps
1434 
1435    Level: intermediate
1436 
1437 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1438           `SNESGetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
1439 @*/
1440 PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1441 {
1442   PetscFunctionBegin;
1443   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1444   snes->maxFailures = maxFails;
1445   PetscFunctionReturn(0);
1446 }
1447 
1448 /*@
1449    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1450    attempted by the nonlinear solver before it gives up.
1451 
1452    Not Collective
1453 
1454    Input Parameter:
1455 .  snes     - SNES context
1456 
1457    Output Parameter:
1458 .  maxFails - maximum of unsuccessful steps
1459 
1460    Level: intermediate
1461 
1462 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`,
1463           `SNESSetMaxNonlinearStepFailures()`, `SNESGetNonlinearStepFailures()`
1464 
1465 @*/
1466 PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1467 {
1468   PetscFunctionBegin;
1469   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1470   PetscValidIntPointer(maxFails,2);
1471   *maxFails = snes->maxFailures;
1472   PetscFunctionReturn(0);
1473 }
1474 
1475 /*@
1476    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1477      done by SNES.
1478 
1479    Not Collective
1480 
1481    Input Parameter:
1482 .  snes     - SNES context
1483 
1484    Output Parameter:
1485 .  nfuncs - number of evaluations
1486 
1487    Level: intermediate
1488 
1489    Notes:
1490     Reset every time SNESSolve is called unless SNESSetCountersReset() is used.
1491 
1492 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`, `SNESGetLinearSolveFailures()`, `SNESSetCountersReset()`
1493 @*/
1494 PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1495 {
1496   PetscFunctionBegin;
1497   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1498   PetscValidIntPointer(nfuncs,2);
1499   *nfuncs = snes->nfuncs;
1500   PetscFunctionReturn(0);
1501 }
1502 
1503 /*@
1504    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1505    linear solvers.
1506 
1507    Not Collective
1508 
1509    Input Parameter:
1510 .  snes - SNES context
1511 
1512    Output Parameter:
1513 .  nfails - number of failed solves
1514 
1515    Level: intermediate
1516 
1517    Options Database Keys:
1518 . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
1519 
1520    Notes:
1521    This counter is reset to zero for each successive call to SNESSolve().
1522 
1523 .seealso: `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`
1524 @*/
1525 PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1526 {
1527   PetscFunctionBegin;
1528   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1529   PetscValidIntPointer(nfails,2);
1530   *nfails = snes->numLinearSolveFailures;
1531   PetscFunctionReturn(0);
1532 }
1533 
1534 /*@
1535    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1536    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE
1537 
1538    Logically Collective on SNES
1539 
1540    Input Parameters:
1541 +  snes     - SNES context
1542 -  maxFails - maximum allowed linear solve failures
1543 
1544    Level: intermediate
1545 
1546    Options Database Keys:
1547 . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated
1548 
1549    Notes:
1550     By default this is 0; that is SNES returns on the first failed linear solve
1551 
1552 .seealso: `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESGetLinearSolveIterations()`
1553 @*/
1554 PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1555 {
1556   PetscFunctionBegin;
1557   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1558   PetscValidLogicalCollectiveInt(snes,maxFails,2);
1559   snes->maxLinearSolveFailures = maxFails;
1560   PetscFunctionReturn(0);
1561 }
1562 
1563 /*@
1564    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1565      are allowed before SNES terminates
1566 
1567    Not Collective
1568 
1569    Input Parameter:
1570 .  snes     - SNES context
1571 
1572    Output Parameter:
1573 .  maxFails - maximum of unsuccessful solves allowed
1574 
1575    Level: intermediate
1576 
1577    Notes:
1578     By default this is 1; that is SNES returns on the first failed linear solve
1579 
1580 .seealso: `SNESGetLinearSolveFailures()`, `SNESGetLinearSolveIterations()`, `SNESSetMaxLinearSolveFailures()`,
1581 @*/
1582 PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1583 {
1584   PetscFunctionBegin;
1585   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1586   PetscValidIntPointer(maxFails,2);
1587   *maxFails = snes->maxLinearSolveFailures;
1588   PetscFunctionReturn(0);
1589 }
1590 
1591 /*@
1592    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1593    used by the nonlinear solver.
1594 
1595    Not Collective
1596 
1597    Input Parameter:
1598 .  snes - SNES context
1599 
1600    Output Parameter:
1601 .  lits - number of linear iterations
1602 
1603    Notes:
1604    This counter is reset to zero for each successive call to SNESSolve() unless SNESSetCountersReset() is used.
1605 
1606    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
1607    then call KSPGetIterationNumber() after the failed solve.
1608 
1609    Level: intermediate
1610 
1611 .seealso: `SNESGetIterationNumber()`, `SNESGetLinearSolveFailures()`, `SNESGetMaxLinearSolveFailures()`, `SNESSetCountersReset()`
1612 @*/
1613 PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1614 {
1615   PetscFunctionBegin;
1616   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1617   PetscValidIntPointer(lits,2);
1618   *lits = snes->linear_its;
1619   PetscFunctionReturn(0);
1620 }
1621 
1622 /*@
1623    SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1624    are reset every time SNESSolve() is called.
1625 
1626    Logically Collective on SNES
1627 
1628    Input Parameters:
1629 +  snes - SNES context
1630 -  reset - whether to reset the counters or not
1631 
1632    Notes:
1633    This defaults to PETSC_TRUE
1634 
1635    Level: developer
1636 
1637 .seealso: `SNESGetNumberFunctionEvals()`, `SNESGetLinearSolveIterations()`, `SNESGetNPC()`
1638 @*/
1639 PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1640 {
1641   PetscFunctionBegin;
1642   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1643   PetscValidLogicalCollectiveBool(snes,reset,2);
1644   snes->counters_reset = reset;
1645   PetscFunctionReturn(0);
1646 }
1647 
1648 /*@
1649    SNESSetKSP - Sets a KSP context for the SNES object to use
1650 
1651    Not Collective, but the SNES and KSP objects must live on the same MPI_Comm
1652 
1653    Input Parameters:
1654 +  snes - the SNES context
1655 -  ksp - the KSP context
1656 
1657    Notes:
1658    The SNES object already has its KSP object, you can obtain with SNESGetKSP()
1659    so this routine is rarely needed.
1660 
1661    The KSP object that is already in the SNES object has its reference count
1662    decreased by one.
1663 
1664    Level: developer
1665 
1666 .seealso: `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
1667 @*/
1668 PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1669 {
1670   PetscFunctionBegin;
1671   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1672   PetscValidHeaderSpecific(ksp,KSP_CLASSID,2);
1673   PetscCheckSameComm(snes,1,ksp,2);
1674   PetscCall(PetscObjectReference((PetscObject)ksp));
1675   if (snes->ksp) PetscCall(PetscObjectDereference((PetscObject)snes->ksp));
1676   snes->ksp = ksp;
1677   PetscFunctionReturn(0);
1678 }
1679 
1680 /* -----------------------------------------------------------*/
1681 /*@
1682    SNESCreate - Creates a nonlinear solver context.
1683 
1684    Collective
1685 
1686    Input Parameters:
1687 .  comm - MPI communicator
1688 
1689    Output Parameter:
1690 .  outsnes - the new SNES context
1691 
1692    Options Database Keys:
1693 +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1694                and no preconditioning matrix
1695 .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1696                products, and a user-provided preconditioning matrix
1697                as set by SNESSetJacobian()
1698 -   -snes_fd - Uses (slow!) finite differences to compute Jacobian
1699 
1700    Level: beginner
1701 
1702    Developer Notes:
1703     SNES always creates a KSP object even though many SNES methods do not use it. This is
1704                     unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1705                     particular method does use KSP and regulates if the information about the KSP is printed
1706                     in SNESView(). TSSetFromOptions() does call SNESSetFromOptions() which can lead to users being confused
1707                     by help messages about meaningless SNES options.
1708 
1709                     SNES always creates the snes->kspconvctx even though it is used by only one type. This should
1710                     be fixed.
1711 
1712 .seealso: `SNESSolve()`, `SNESDestroy()`, `SNES`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
1713 
1714 @*/
1715 PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1716 {
1717   SNES      snes;
1718   SNESKSPEW *kctx;
1719 
1720   PetscFunctionBegin;
1721   PetscValidPointer(outsnes,2);
1722   *outsnes = NULL;
1723   PetscCall(SNESInitializePackage());
1724 
1725   PetscCall(PetscHeaderCreate(snes,SNES_CLASSID,"SNES","Nonlinear solver","SNES",comm,SNESDestroy,SNESView));
1726 
1727   snes->ops->converged    = SNESConvergedDefault;
1728   snes->usesksp           = PETSC_TRUE;
1729   snes->tolerancesset     = PETSC_FALSE;
1730   snes->max_its           = 50;
1731   snes->max_funcs         = 10000;
1732   snes->norm              = 0.0;
1733   snes->xnorm             = 0.0;
1734   snes->ynorm             = 0.0;
1735   snes->normschedule      = SNES_NORM_ALWAYS;
1736   snes->functype          = SNES_FUNCTION_DEFAULT;
1737 #if defined(PETSC_USE_REAL_SINGLE)
1738   snes->rtol              = 1.e-5;
1739 #else
1740   snes->rtol              = 1.e-8;
1741 #endif
1742   snes->ttol              = 0.0;
1743 #if defined(PETSC_USE_REAL_SINGLE)
1744   snes->abstol            = 1.e-25;
1745 #else
1746   snes->abstol            = 1.e-50;
1747 #endif
1748 #if defined(PETSC_USE_REAL_SINGLE)
1749   snes->stol              = 1.e-5;
1750 #else
1751   snes->stol              = 1.e-8;
1752 #endif
1753 #if defined(PETSC_USE_REAL_SINGLE)
1754   snes->deltatol          = 1.e-6;
1755 #else
1756   snes->deltatol          = 1.e-12;
1757 #endif
1758   snes->divtol            = 1.e4;
1759   snes->rnorm0            = 0;
1760   snes->nfuncs            = 0;
1761   snes->numFailures       = 0;
1762   snes->maxFailures       = 1;
1763   snes->linear_its        = 0;
1764   snes->lagjacobian       = 1;
1765   snes->jac_iter          = 0;
1766   snes->lagjac_persist    = PETSC_FALSE;
1767   snes->lagpreconditioner = 1;
1768   snes->pre_iter          = 0;
1769   snes->lagpre_persist    = PETSC_FALSE;
1770   snes->numbermonitors    = 0;
1771   snes->numberreasonviews = 0;
1772   snes->data              = NULL;
1773   snes->setupcalled       = PETSC_FALSE;
1774   snes->ksp_ewconv        = PETSC_FALSE;
1775   snes->nwork             = 0;
1776   snes->work              = NULL;
1777   snes->nvwork            = 0;
1778   snes->vwork             = NULL;
1779   snes->conv_hist_len     = 0;
1780   snes->conv_hist_max     = 0;
1781   snes->conv_hist         = NULL;
1782   snes->conv_hist_its     = NULL;
1783   snes->conv_hist_reset   = PETSC_TRUE;
1784   snes->counters_reset    = PETSC_TRUE;
1785   snes->vec_func_init_set = PETSC_FALSE;
1786   snes->reason            = SNES_CONVERGED_ITERATING;
1787   snes->npcside           = PC_RIGHT;
1788   snes->setfromoptionscalled = 0;
1789 
1790   snes->mf          = PETSC_FALSE;
1791   snes->mf_operator = PETSC_FALSE;
1792   snes->mf_version  = 1;
1793 
1794   snes->numLinearSolveFailures = 0;
1795   snes->maxLinearSolveFailures = 1;
1796 
1797   snes->vizerotolerance = 1.e-8;
1798   snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE;
1799 
1800   /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
1801   snes->alwayscomputesfinalresidual = PETSC_FALSE;
1802 
1803   /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
1804   PetscCall(PetscNewLog(snes,&kctx));
1805 
1806   snes->kspconvctx  = (void*)kctx;
1807   kctx->version     = 2;
1808   kctx->rtol_0      = 0.3; /* Eisenstat and Walker suggest rtol_0=.5, but
1809                              this was too large for some test cases */
1810   kctx->rtol_last   = 0.0;
1811   kctx->rtol_max    = 0.9;
1812   kctx->gamma       = 1.0;
1813   kctx->alpha       = 0.5*(1.0 + PetscSqrtReal(5.0));
1814   kctx->alpha2      = kctx->alpha;
1815   kctx->threshold   = 0.1;
1816   kctx->lresid_last = 0.0;
1817   kctx->norm_last   = 0.0;
1818 
1819   kctx->rk_last     = 0.0;
1820   kctx->rk_last_2   = 0.0;
1821   kctx->rtol_last_2 = 0.0;
1822   kctx->v4_p1       = 0.1;
1823   kctx->v4_p2       = 0.4;
1824   kctx->v4_p3       = 0.7;
1825   kctx->v4_m1       = 0.8;
1826   kctx->v4_m2       = 0.5;
1827   kctx->v4_m3       = 0.1;
1828   kctx->v4_m4       = 0.5;
1829 
1830   *outsnes = snes;
1831   PetscFunctionReturn(0);
1832 }
1833 
1834 /*MC
1835     SNESFunction - Functional form used to convey the nonlinear function to be solved by SNES
1836 
1837      Synopsis:
1838      #include "petscsnes.h"
1839      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);
1840 
1841      Collective on snes
1842 
1843      Input Parameters:
1844 +     snes - the SNES context
1845 .     x    - state at which to evaluate residual
1846 -     ctx     - optional user-defined function context, passed in with SNESSetFunction()
1847 
1848      Output Parameter:
1849 .     f  - vector to put residual (function value)
1850 
1851    Level: intermediate
1852 
1853 .seealso: `SNESSetFunction()`, `SNESGetFunction()`
1854 M*/
1855 
1856 /*@C
1857    SNESSetFunction - Sets the function evaluation routine and function
1858    vector for use by the SNES routines in solving systems of nonlinear
1859    equations.
1860 
1861    Logically Collective on SNES
1862 
1863    Input Parameters:
1864 +  snes - the SNES context
1865 .  r - vector to store function values, may be NULL
1866 .  f - function evaluation routine; see SNESFunction for calling sequence details
1867 -  ctx - [optional] user-defined context for private data for the
1868          function evaluation routine (may be NULL)
1869 
1870    Notes:
1871    The Newton-like methods typically solve linear systems of the form
1872 $      f'(x) x = -f(x),
1873    where f'(x) denotes the Jacobian matrix and f(x) is the function.
1874 
1875    Level: beginner
1876 
1877 .seealso: `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetPicard()`, `SNESFunction`
1878 @*/
1879 PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1880 {
1881   DM             dm;
1882 
1883   PetscFunctionBegin;
1884   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1885   if (r) {
1886     PetscValidHeaderSpecific(r,VEC_CLASSID,2);
1887     PetscCheckSameComm(snes,1,r,2);
1888     PetscCall(PetscObjectReference((PetscObject)r));
1889     PetscCall(VecDestroy(&snes->vec_func));
1890     snes->vec_func = r;
1891   }
1892   PetscCall(SNESGetDM(snes,&dm));
1893   PetscCall(DMSNESSetFunction(dm,f,ctx));
1894   if (f == SNESPicardComputeFunction) {
1895     PetscCall(DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx));
1896   }
1897   PetscFunctionReturn(0);
1898 }
1899 
1900 /*@C
1901    SNESSetInitialFunction - Sets the function vector to be used as the
1902    function norm at the initialization of the method.  In some
1903    instances, the user has precomputed the function before calling
1904    SNESSolve.  This function allows one to avoid a redundant call
1905    to SNESComputeFunction in that case.
1906 
1907    Logically Collective on SNES
1908 
1909    Input Parameters:
1910 +  snes - the SNES context
1911 -  f - vector to store function value
1912 
1913    Notes:
1914    This should not be modified during the solution procedure.
1915 
1916    This is used extensively in the SNESFAS hierarchy and in nonlinear preconditioning.
1917 
1918    Level: developer
1919 
1920 .seealso: `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetInitialFunctionNorm()`
1921 @*/
1922 PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1923 {
1924   Vec            vec_func;
1925 
1926   PetscFunctionBegin;
1927   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1928   PetscValidHeaderSpecific(f,VEC_CLASSID,2);
1929   PetscCheckSameComm(snes,1,f,2);
1930   if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1931     snes->vec_func_init_set = PETSC_FALSE;
1932     PetscFunctionReturn(0);
1933   }
1934   PetscCall(SNESGetFunction(snes,&vec_func,NULL,NULL));
1935   PetscCall(VecCopy(f,vec_func));
1936 
1937   snes->vec_func_init_set = PETSC_TRUE;
1938   PetscFunctionReturn(0);
1939 }
1940 
1941 /*@
1942    SNESSetNormSchedule - Sets the SNESNormSchedule used in convergence and monitoring
1943    of the SNES method.
1944 
1945    Logically Collective on SNES
1946 
1947    Input Parameters:
1948 +  snes - the SNES context
1949 -  normschedule - the frequency of norm computation
1950 
1951    Options Database Key:
1952 .  -snes_norm_schedule <none, always, initialonly, finalonly, initialfinalonly> - set the schedule
1953 
1954    Notes:
1955    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
1956    of the nonlinear function and the taking of its norm at every iteration to
1957    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
1958    (SNESNGS) and the like do not require the norm of the function to be computed, and therefore
1959    may either be monitored for convergence or not.  As these are often used as nonlinear
1960    preconditioners, monitoring the norm of their error is not a useful enterprise within
1961    their solution.
1962 
1963    Level: developer
1964 
1965 .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
1966 @*/
1967 PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1968 {
1969   PetscFunctionBegin;
1970   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1971   snes->normschedule = normschedule;
1972   PetscFunctionReturn(0);
1973 }
1974 
1975 /*@
1976    SNESGetNormSchedule - Gets the SNESNormSchedule used in convergence and monitoring
1977    of the SNES method.
1978 
1979    Logically Collective on SNES
1980 
1981    Input Parameters:
1982 +  snes - the SNES context
1983 -  normschedule - the type of the norm used
1984 
1985    Level: advanced
1986 
1987 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
1988 @*/
1989 PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1990 {
1991   PetscFunctionBegin;
1992   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
1993   *normschedule = snes->normschedule;
1994   PetscFunctionReturn(0);
1995 }
1996 
1997 /*@
1998   SNESSetFunctionNorm - Sets the last computed residual norm.
1999 
2000   Logically Collective on SNES
2001 
2002   Input Parameters:
2003 + snes - the SNES context
2004 
2005 - normschedule - the frequency of norm computation
2006 
2007   Level: developer
2008 
2009 .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2010 @*/
2011 PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
2012 {
2013   PetscFunctionBegin;
2014   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2015   snes->norm = norm;
2016   PetscFunctionReturn(0);
2017 }
2018 
2019 /*@
2020   SNESGetFunctionNorm - Gets the last computed norm of the residual
2021 
2022   Not Collective
2023 
2024   Input Parameter:
2025 . snes - the SNES context
2026 
2027   Output Parameter:
2028 . norm - the last computed residual norm
2029 
2030   Level: developer
2031 
2032 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2033 @*/
2034 PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2035 {
2036   PetscFunctionBegin;
2037   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2038   PetscValidRealPointer(norm, 2);
2039   *norm = snes->norm;
2040   PetscFunctionReturn(0);
2041 }
2042 
2043 /*@
2044   SNESGetUpdateNorm - Gets the last computed norm of the Newton update
2045 
2046   Not Collective
2047 
2048   Input Parameter:
2049 . snes - the SNES context
2050 
2051   Output Parameter:
2052 . ynorm - the last computed update norm
2053 
2054   Level: developer
2055 
2056 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`
2057 @*/
2058 PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2059 {
2060   PetscFunctionBegin;
2061   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2062   PetscValidRealPointer(ynorm, 2);
2063   *ynorm = snes->ynorm;
2064   PetscFunctionReturn(0);
2065 }
2066 
2067 /*@
2068   SNESGetSolutionNorm - Gets the last computed norm of the solution
2069 
2070   Not Collective
2071 
2072   Input Parameter:
2073 . snes - the SNES context
2074 
2075   Output Parameter:
2076 . xnorm - the last computed solution norm
2077 
2078   Level: developer
2079 
2080 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `SNESGetFunctionNorm()`, `SNESGetUpdateNorm()`
2081 @*/
2082 PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2083 {
2084   PetscFunctionBegin;
2085   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2086   PetscValidRealPointer(xnorm, 2);
2087   *xnorm = snes->xnorm;
2088   PetscFunctionReturn(0);
2089 }
2090 
2091 /*@C
2092    SNESSetFunctionType - Sets the SNESNormSchedule used in convergence and monitoring
2093    of the SNES method.
2094 
2095    Logically Collective on SNES
2096 
2097    Input Parameters:
2098 +  snes - the SNES context
2099 -  normschedule - the frequency of norm computation
2100 
2101    Notes:
2102    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
2103    of the nonlinear function and the taking of its norm at every iteration to
2104    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
2105    (SNESNGS) and the like do not require the norm of the function to be computed, and therefore
2106    may either be monitored for convergence or not.  As these are often used as nonlinear
2107    preconditioners, monitoring the norm of their error is not a useful enterprise within
2108    their solution.
2109 
2110    Level: developer
2111 
2112 .seealso: `SNESGetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2113 @*/
2114 PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
2115 {
2116   PetscFunctionBegin;
2117   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2118   snes->functype = type;
2119   PetscFunctionReturn(0);
2120 }
2121 
2122 /*@C
2123    SNESGetFunctionType - Gets the SNESNormSchedule used in convergence and monitoring
2124    of the SNES method.
2125 
2126    Logically Collective on SNES
2127 
2128    Input Parameters:
2129 +  snes - the SNES context
2130 -  normschedule - the type of the norm used
2131 
2132    Level: advanced
2133 
2134 .seealso: `SNESSetNormSchedule()`, `SNESComputeFunction()`, `VecNorm()`, `SNESSetFunction()`, `SNESSetInitialFunction()`, `SNESNormSchedule`
2135 @*/
2136 PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2137 {
2138   PetscFunctionBegin;
2139   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2140   *type = snes->functype;
2141   PetscFunctionReturn(0);
2142 }
2143 
2144 /*MC
2145     SNESNGSFunction - function used to convey a Gauss-Seidel sweep on the nonlinear function
2146 
2147      Synopsis:
2148      #include <petscsnes.h>
2149 $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);
2150 
2151      Collective on snes
2152 
2153      Input Parameters:
2154 +  X   - solution vector
2155 .  B   - RHS vector
2156 -  ctx - optional user-defined Gauss-Seidel context
2157 
2158      Output Parameter:
2159 .  X   - solution vector
2160 
2161    Level: intermediate
2162 
2163 .seealso: `SNESSetNGS()`, `SNESGetNGS()`
2164 M*/
2165 
2166 /*@C
2167    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2168    use with composed nonlinear solvers.
2169 
2170    Input Parameters:
2171 +  snes   - the SNES context
2172 .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
2173 -  ctx    - [optional] user-defined context for private data for the
2174             smoother evaluation routine (may be NULL)
2175 
2176    Notes:
2177    The NGS routines are used by the composed nonlinear solver to generate
2178     a problem appropriate update to the solution, particularly FAS.
2179 
2180    Level: intermediate
2181 
2182 .seealso: `SNESGetFunction()`, `SNESComputeNGS()`
2183 @*/
2184 PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
2185 {
2186   DM             dm;
2187 
2188   PetscFunctionBegin;
2189   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2190   PetscCall(SNESGetDM(snes,&dm));
2191   PetscCall(DMSNESSetNGS(dm,f,ctx));
2192   PetscFunctionReturn(0);
2193 }
2194 
2195 /*
2196      This is used for -snes_mf_operator; it uses a duplicate of snes->jacobian_pre because snes->jacobian_pre cannot be
2197    changed during the KSPSolve()
2198 */
2199 PetscErrorCode SNESPicardComputeMFFunction(SNES snes,Vec x,Vec f,void *ctx)
2200 {
2201   DM             dm;
2202   DMSNES         sdm;
2203 
2204   PetscFunctionBegin;
2205   PetscCall(SNESGetDM(snes,&dm));
2206   PetscCall(DMGetDMSNES(dm,&sdm));
2207   PetscCheck(sdm->ops->computepjacobian,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2208   /*  A(x)*x - b(x) */
2209   if (sdm->ops->computepfunction) {
2210     PetscCallBack("SNES Picard callback function",(*sdm->ops->computepfunction)(snes,x,f,sdm->pctx));
2211     PetscCall(VecScale(f,-1.0));
2212     /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2213     if (!snes->picard) PetscCall(MatDuplicate(snes->jacobian_pre,MAT_DO_NOT_COPY_VALUES,&snes->picard));
2214     PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx));
2215     PetscCall(MatMultAdd(snes->picard,x,f,f));
2216   } else {
2217     PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx));
2218     PetscCall(MatMult(snes->picard,x,f));
2219   }
2220   PetscFunctionReturn(0);
2221 }
2222 
2223 PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
2224 {
2225   DM             dm;
2226   DMSNES         sdm;
2227 
2228   PetscFunctionBegin;
2229   PetscCall(SNESGetDM(snes,&dm));
2230   PetscCall(DMGetDMSNES(dm,&sdm));
2231   PetscCheck(sdm->ops->computepjacobian,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2232   /*  A(x)*x - b(x) */
2233   if (sdm->ops->computepfunction) {
2234     PetscCallBack("SNES Picard callback function",(*sdm->ops->computepfunction)(snes,x,f,sdm->pctx));
2235     PetscCall(VecScale(f,-1.0));
2236     PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx));
2237     PetscCall(MatMultAdd(snes->jacobian_pre,x,f,f));
2238   } else {
2239     PetscCallBack("SNES Picard callback Jacobian",(*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx));
2240     PetscCall(MatMult(snes->jacobian_pre,x,f));
2241   }
2242   PetscFunctionReturn(0);
2243 }
2244 
2245 PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
2246 {
2247   PetscFunctionBegin;
2248   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2249   /* must assembly if matrix-free to get the last SNES solution */
2250   PetscCall(MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY));
2251   PetscCall(MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY));
2252   PetscFunctionReturn(0);
2253 }
2254 
2255 /*@C
2256    SNESSetPicard - Use SNES to solve the system A(x) x = bp(x) + b via a Picard type iteration (Picard linearization)
2257 
2258    Logically Collective on SNES
2259 
2260    Input Parameters:
2261 +  snes - the SNES context
2262 .  r - vector to store function values, may be NULL
2263 .  bp - function evaluation routine, may be NULL
2264 .  Amat - matrix with which A(x) x - bp(x) - b is to be computed
2265 .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2266 .  J  - function to compute matrix values, see SNESJacobianFunction() for details on its calling sequence
2267 -  ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)
2268 
2269    Notes:
2270     It is often better to provide the nonlinear function F() and some approximation to its Jacobian directly and use
2271     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.
2272 
2273     One can call SNESSetPicard() or SNESSetFunction() (and possibly SNESSetJacobian()) but cannot call both
2274 
2275 $     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}
2276 $     Note that when an exact solver is used this corresponds to the "classic" Picard A(x^{n}) x^{n+1} = bp(x^{n}) + b iteration.
2277 
2278      Run with -snes_mf_operator to solve the system with Newton's method using A(x^{n}) to construct the preconditioner.
2279 
2280    We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
2281    the direct Picard iteration A(x^n) x^{n+1} = bp(x^n) + b
2282 
2283    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
2284    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
2285    different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument :-).
2286 
2287    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.
2288 
2289    When used with -snes_fd this will compute the true Jacobian (very slowly one column at at time) and thus represent Newton's method.
2290 
2291    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
2292    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
2293    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.
2294    See the commment in src/snes/tutorials/ex15.c.
2295 
2296    Level: intermediate
2297 
2298 .seealso: `SNESGetFunction()`, `SNESSetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESGetPicard()`, `SNESLineSearchPreCheckPicard()`, `SNESJacobianFunction`
2299 @*/
2300 PetscErrorCode  SNESSetPicard(SNES snes,Vec r,PetscErrorCode (*bp)(SNES,Vec,Vec,void*),Mat Amat, Mat Pmat, PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2301 {
2302   DM             dm;
2303 
2304   PetscFunctionBegin;
2305   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2306   PetscCall(SNESGetDM(snes, &dm));
2307   PetscCall(DMSNESSetPicard(dm,bp,J,ctx));
2308   PetscCall(DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx));
2309   PetscCall(SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx));
2310   PetscCall(SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx));
2311   PetscFunctionReturn(0);
2312 }
2313 
2314 /*@C
2315    SNESGetPicard - Returns the context for the Picard iteration
2316 
2317    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
2318 
2319    Input Parameter:
2320 .  snes - the SNES context
2321 
2322    Output Parameters:
2323 +  r - the function (or NULL)
2324 .  f - the function (or NULL); see SNESFunction for calling sequence details
2325 .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2326 .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2327 .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2328 -  ctx - the function context (or NULL)
2329 
2330    Level: advanced
2331 
2332 .seealso: `SNESSetPicard()`, `SNESGetFunction()`, `SNESGetJacobian()`, `SNESGetDM()`, `SNESFunction`, `SNESJacobianFunction`
2333 @*/
2334 PetscErrorCode  SNESGetPicard(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),Mat *Amat, Mat *Pmat, PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2335 {
2336   DM             dm;
2337 
2338   PetscFunctionBegin;
2339   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2340   PetscCall(SNESGetFunction(snes,r,NULL,NULL));
2341   PetscCall(SNESGetJacobian(snes,Amat,Pmat,NULL,NULL));
2342   PetscCall(SNESGetDM(snes,&dm));
2343   PetscCall(DMSNESGetPicard(dm,f,J,ctx));
2344   PetscFunctionReturn(0);
2345 }
2346 
2347 /*@C
2348    SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the problem
2349 
2350    Logically Collective on SNES
2351 
2352    Input Parameters:
2353 +  snes - the SNES context
2354 .  func - function evaluation routine
2355 -  ctx - [optional] user-defined context for private data for the
2356          function evaluation routine (may be NULL)
2357 
2358    Calling sequence of func:
2359 $    func (SNES snes,Vec x,void *ctx);
2360 
2361 .  f - function vector
2362 -  ctx - optional user-defined function context
2363 
2364    Level: intermediate
2365 
2366 .seealso: `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`
2367 @*/
2368 PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2369 {
2370   PetscFunctionBegin;
2371   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2372   if (func) snes->ops->computeinitialguess = func;
2373   if (ctx)  snes->initialguessP            = ctx;
2374   PetscFunctionReturn(0);
2375 }
2376 
2377 /* --------------------------------------------------------------- */
2378 /*@C
2379    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2380    it assumes a zero right hand side.
2381 
2382    Logically Collective on SNES
2383 
2384    Input Parameter:
2385 .  snes - the SNES context
2386 
2387    Output Parameter:
2388 .  rhs - the right hand side vector or NULL if the right hand side vector is null
2389 
2390    Level: intermediate
2391 
2392 .seealso: `SNESGetSolution()`, `SNESGetFunction()`, `SNESComputeFunction()`, `SNESSetJacobian()`, `SNESSetFunction()`
2393 @*/
2394 PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2395 {
2396   PetscFunctionBegin;
2397   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2398   PetscValidPointer(rhs,2);
2399   *rhs = snes->vec_rhs;
2400   PetscFunctionReturn(0);
2401 }
2402 
2403 /*@
2404    SNESComputeFunction - Calls the function that has been set with SNESSetFunction().
2405 
2406    Collective on SNES
2407 
2408    Input Parameters:
2409 +  snes - the SNES context
2410 -  x - input vector
2411 
2412    Output Parameter:
2413 .  y - function vector, as set by SNESSetFunction()
2414 
2415    Notes:
2416    SNESComputeFunction() is typically used within nonlinear solvers
2417    implementations, so users would not generally call this routine themselves.
2418 
2419    Level: developer
2420 
2421 .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeMFFunction()`
2422 @*/
2423 PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2424 {
2425   DM             dm;
2426   DMSNES         sdm;
2427 
2428   PetscFunctionBegin;
2429   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2430   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2431   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2432   PetscCheckSameComm(snes,1,x,2);
2433   PetscCheckSameComm(snes,1,y,3);
2434   PetscCall(VecValidValues(x,2,PETSC_TRUE));
2435 
2436   PetscCall(SNESGetDM(snes,&dm));
2437   PetscCall(DMGetDMSNES(dm,&sdm));
2438   if (sdm->ops->computefunction) {
2439     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2440       PetscCall(PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0));
2441     }
2442     PetscCall(VecLockReadPush(x));
2443     /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2444     snes->domainerror = PETSC_FALSE;
2445     {
2446       void *ctx;
2447       PetscErrorCode (*computefunction)(SNES,Vec,Vec,void*);
2448       PetscCall(DMSNESGetFunction(dm,&computefunction,&ctx));
2449       PetscCallBack("SNES callback function",(*computefunction)(snes,x,y,ctx));
2450     }
2451     PetscCall(VecLockReadPop(x));
2452     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2453       PetscCall(PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0));
2454     }
2455   } else if (snes->vec_rhs) {
2456     PetscCall(MatMult(snes->jacobian, x, y));
2457   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2458   if (snes->vec_rhs) PetscCall(VecAXPY(y,-1.0,snes->vec_rhs));
2459   snes->nfuncs++;
2460   /*
2461      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2462      propagate the value to all processes
2463   */
2464   if (snes->domainerror) PetscCall(VecSetInf(y));
2465   PetscFunctionReturn(0);
2466 }
2467 
2468 /*@
2469    SNESComputeMFFunction - Calls the function that has been set with SNESSetMFFunction().
2470 
2471    Collective on SNES
2472 
2473    Input Parameters:
2474 +  snes - the SNES context
2475 -  x - input vector
2476 
2477    Output Parameter:
2478 .  y - function vector, as set by SNESSetMFFunction()
2479 
2480    Notes:
2481        SNESComputeMFFunction() is used within the matrix vector products called by the matrix created with MatCreateSNESMF()
2482    so users would not generally call this routine themselves.
2483 
2484        Since this function is intended for use with finite differencing it does not subtract the right hand side vector provided with SNESSolve()
2485     while SNESComputeFunction() does. As such, this routine cannot be used with  MatMFFDSetBase() with a provided F function value even if it applies the
2486     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.
2487 
2488    Level: developer
2489 
2490 .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESComputeFunction()`, `MatCreateSNESMF`
2491 @*/
2492 PetscErrorCode  SNESComputeMFFunction(SNES snes,Vec x,Vec y)
2493 {
2494   DM             dm;
2495   DMSNES         sdm;
2496 
2497   PetscFunctionBegin;
2498   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2499   PetscValidHeaderSpecific(x,VEC_CLASSID,2);
2500   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
2501   PetscCheckSameComm(snes,1,x,2);
2502   PetscCheckSameComm(snes,1,y,3);
2503   PetscCall(VecValidValues(x,2,PETSC_TRUE));
2504 
2505   PetscCall(SNESGetDM(snes,&dm));
2506   PetscCall(DMGetDMSNES(dm,&sdm));
2507   PetscCall(PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0));
2508   PetscCall(VecLockReadPush(x));
2509   /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2510   snes->domainerror = PETSC_FALSE;
2511   PetscCallBack("SNES callback function",(*sdm->ops->computemffunction)(snes,x,y,sdm->mffunctionctx));
2512   PetscCall(VecLockReadPop(x));
2513   PetscCall(PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0));
2514   snes->nfuncs++;
2515   /*
2516      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2517      propagate the value to all processes
2518   */
2519   if (snes->domainerror) PetscCall(VecSetInf(y));
2520   PetscFunctionReturn(0);
2521 }
2522 
2523 /*@
2524    SNESComputeNGS - Calls the Gauss-Seidel function that has been set with  SNESSetNGS().
2525 
2526    Collective on SNES
2527 
2528    Input Parameters:
2529 +  snes - the SNES context
2530 .  x - input vector
2531 -  b - rhs vector
2532 
2533    Output Parameter:
2534 .  x - new solution vector
2535 
2536    Notes:
2537    SNESComputeNGS() is typically used within composed nonlinear solver
2538    implementations, so most users would not generally call this routine
2539    themselves.
2540 
2541    Level: developer
2542 
2543 .seealso: `SNESSetNGS()`, `SNESComputeFunction()`
2544 @*/
2545 PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2546 {
2547   DM             dm;
2548   DMSNES         sdm;
2549 
2550   PetscFunctionBegin;
2551   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2552   PetscValidHeaderSpecific(x,VEC_CLASSID,3);
2553   if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2);
2554   PetscCheckSameComm(snes,1,x,3);
2555   if (b) PetscCheckSameComm(snes,1,b,2);
2556   if (b) PetscCall(VecValidValues(b,2,PETSC_TRUE));
2557   PetscCall(PetscLogEventBegin(SNES_NGSEval,snes,x,b,0));
2558   PetscCall(SNESGetDM(snes,&dm));
2559   PetscCall(DMGetDMSNES(dm,&sdm));
2560   if (sdm->ops->computegs) {
2561     if (b) PetscCall(VecLockReadPush(b));
2562     PetscCallBack("SNES callback NGS",(*sdm->ops->computegs)(snes,x,b,sdm->gsctx));
2563     if (b) PetscCall(VecLockReadPop(b));
2564   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2565   PetscCall(PetscLogEventEnd(SNES_NGSEval,snes,x,b,0));
2566   PetscFunctionReturn(0);
2567 }
2568 
2569 PetscErrorCode SNESTestJacobian(SNES snes)
2570 {
2571   Mat               A,B,C,D,jacobian;
2572   Vec               x = snes->vec_sol,f = snes->vec_func;
2573   PetscReal         nrm,gnorm;
2574   PetscReal         threshold = 1.e-5;
2575   MatType           mattype;
2576   PetscInt          m,n,M,N;
2577   void              *functx;
2578   PetscBool         complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg,istranspose;
2579   PetscViewer       viewer,mviewer;
2580   MPI_Comm          comm;
2581   PetscInt          tabs;
2582   static PetscBool  directionsprinted = PETSC_FALSE;
2583   PetscViewerFormat format;
2584 
2585   PetscFunctionBegin;
2586   PetscObjectOptionsBegin((PetscObject)snes);
2587   PetscCall(PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test));
2588   PetscCall(PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL));
2589   PetscCall(PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print));
2590   if (!complete_print) {
2591     PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display","-snes_test_jacobian_view","3.13",NULL));
2592     PetscCall(PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print));
2593   }
2594   /* for compatibility with PETSc 3.9 and older. */
2595   PetscCall(PetscOptionsDeprecated("-snes_test_jacobian_display_threshold","-snes_test_jacobian","3.13","-snes_test_jacobian accepts an optional threshold (since v3.10)"));
2596   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));
2597   PetscOptionsEnd();
2598   if (!test) PetscFunctionReturn(0);
2599 
2600   PetscCall(PetscObjectGetComm((PetscObject)snes,&comm));
2601   PetscCall(PetscViewerASCIIGetStdout(comm,&viewer));
2602   PetscCall(PetscViewerASCIIGetTab(viewer, &tabs));
2603   PetscCall(PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel));
2604   PetscCall(PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n"));
2605   if (!complete_print && !directionsprinted) {
2606     PetscCall(PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n"));
2607     PetscCall(PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n"));
2608   }
2609   if (!directionsprinted) {
2610     PetscCall(PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n"));
2611     PetscCall(PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n"));
2612     directionsprinted = PETSC_TRUE;
2613   }
2614   if (complete_print) PetscCall(PetscViewerPushFormat(mviewer,format));
2615 
2616   PetscCall(PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg));
2617   if (!flg) jacobian = snes->jacobian;
2618   else jacobian = snes->jacobian_pre;
2619 
2620   if (!x) {
2621     PetscCall(MatCreateVecs(jacobian, &x, NULL));
2622   } else {
2623     PetscCall(PetscObjectReference((PetscObject) x));
2624   }
2625   if (!f) {
2626     PetscCall(VecDuplicate(x, &f));
2627   } else {
2628     PetscCall(PetscObjectReference((PetscObject) f));
2629   }
2630   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2631   PetscCall(SNESComputeFunction(snes,x,f));
2632   PetscCall(VecDestroy(&f));
2633   PetscCall(PetscObjectTypeCompare((PetscObject)snes,SNESKSPTRANSPOSEONLY,&istranspose));
2634   while (jacobian) {
2635     Mat JT = NULL, Jsave = NULL;
2636 
2637     if (istranspose) {
2638       PetscCall(MatCreateTranspose(jacobian,&JT));
2639       Jsave = jacobian;
2640       jacobian = JT;
2641     }
2642     PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPISBAIJ,""));
2643     if (flg) {
2644       A    = jacobian;
2645       PetscCall(PetscObjectReference((PetscObject)A));
2646     } else {
2647       PetscCall(MatComputeOperator(jacobian,MATAIJ,&A));
2648     }
2649 
2650     PetscCall(MatGetType(A,&mattype));
2651     PetscCall(MatGetSize(A,&M,&N));
2652     PetscCall(MatGetLocalSize(A,&m,&n));
2653     PetscCall(MatCreate(PetscObjectComm((PetscObject)A),&B));
2654     PetscCall(MatSetType(B,mattype));
2655     PetscCall(MatSetSizes(B,m,n,M,N));
2656     PetscCall(MatSetBlockSizesFromMats(B,A,A));
2657     PetscCall(MatSetUp(B));
2658     PetscCall(MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE));
2659 
2660     PetscCall(SNESGetFunction(snes,NULL,NULL,&functx));
2661     PetscCall(SNESComputeJacobianDefault(snes,x,B,B,functx));
2662 
2663     PetscCall(MatDuplicate(B,MAT_COPY_VALUES,&D));
2664     PetscCall(MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN));
2665     PetscCall(MatNorm(D,NORM_FROBENIUS,&nrm));
2666     PetscCall(MatNorm(A,NORM_FROBENIUS,&gnorm));
2667     PetscCall(MatDestroy(&D));
2668     if (!gnorm) gnorm = 1; /* just in case */
2669     PetscCall(PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm));
2670 
2671     if (complete_print) {
2672       PetscCall(PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n"));
2673       PetscCall(MatView(A,mviewer));
2674       PetscCall(PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n"));
2675       PetscCall(MatView(B,mviewer));
2676     }
2677 
2678     if (threshold_print || complete_print) {
2679       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2680       PetscScalar       *cvals;
2681       const PetscInt    *bcols;
2682       const PetscScalar *bvals;
2683 
2684       PetscCall(MatCreate(PetscObjectComm((PetscObject)A),&C));
2685       PetscCall(MatSetType(C,mattype));
2686       PetscCall(MatSetSizes(C,m,n,M,N));
2687       PetscCall(MatSetBlockSizesFromMats(C,A,A));
2688       PetscCall(MatSetUp(C));
2689       PetscCall(MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE));
2690 
2691       PetscCall(MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN));
2692       PetscCall(MatGetOwnershipRange(B,&Istart,&Iend));
2693 
2694       for (row = Istart; row < Iend; row++) {
2695         PetscCall(MatGetRow(B,row,&bncols,&bcols,&bvals));
2696         PetscCall(PetscMalloc2(bncols,&ccols,bncols,&cvals));
2697         for (j = 0, cncols = 0; j < bncols; j++) {
2698           if (PetscAbsScalar(bvals[j]) > threshold) {
2699             ccols[cncols] = bcols[j];
2700             cvals[cncols] = bvals[j];
2701             cncols += 1;
2702           }
2703         }
2704         if (cncols) {
2705           PetscCall(MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES));
2706         }
2707         PetscCall(MatRestoreRow(B,row,&bncols,&bcols,&bvals));
2708         PetscCall(PetscFree2(ccols,cvals));
2709       }
2710       PetscCall(MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY));
2711       PetscCall(MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY));
2712       PetscCall(PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold));
2713       PetscCall(MatView(C,complete_print ? mviewer : viewer));
2714       PetscCall(MatDestroy(&C));
2715     }
2716     PetscCall(MatDestroy(&A));
2717     PetscCall(MatDestroy(&B));
2718     PetscCall(MatDestroy(&JT));
2719     if (Jsave) jacobian = Jsave;
2720     if (jacobian != snes->jacobian_pre) {
2721       jacobian = snes->jacobian_pre;
2722       PetscCall(PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n"));
2723     }
2724     else jacobian = NULL;
2725   }
2726   PetscCall(VecDestroy(&x));
2727   if (complete_print) PetscCall(PetscViewerPopFormat(mviewer));
2728   if (mviewer) PetscCall(PetscViewerDestroy(&mviewer));
2729   PetscCall(PetscViewerASCIISetTab(viewer,tabs));
2730   PetscFunctionReturn(0);
2731 }
2732 
2733 /*@
2734    SNESComputeJacobian - Computes the Jacobian matrix that has been set with SNESSetJacobian().
2735 
2736    Collective on SNES
2737 
2738    Input Parameters:
2739 +  snes - the SNES context
2740 -  x - input vector
2741 
2742    Output Parameters:
2743 +  A - Jacobian matrix
2744 -  B - optional preconditioning matrix
2745 
2746   Options Database Keys:
2747 +    -snes_lag_preconditioner <lag> - how often to rebuild preconditioner
2748 .    -snes_lag_jacobian <lag> - how often to rebuild Jacobian
2749 .    -snes_test_jacobian <optional 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.
2750 .    -snes_test_jacobian_view - 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
2751 .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2752 .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2753 .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2754 .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2755 .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2756 .    -snes_compare_coloring_display - Compute the finite difference Jacobian using coloring and display verbose differences
2757 .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2758 .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2759 .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2760 .    -snes_compare_coloring_draw - Compute the finite difference Jacobian using coloring and draw differences
2761 -    -snes_compare_coloring_draw_contour - Compute the finite difference Jacobian using coloring and show contours of matrices and differences
2762 
2763    Notes:
2764    Most users should not need to explicitly call this routine, as it
2765    is used internally within the nonlinear solvers.
2766 
2767    Developer Notes:
2768     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
2769       for with the SNESType of test that has been removed.
2770 
2771    Level: developer
2772 
2773 .seealso: `SNESSetJacobian()`, `KSPSetOperators()`, `MatStructure`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobian()`
2774 @*/
2775 PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2776 {
2777   PetscBool      flag;
2778   DM             dm;
2779   DMSNES         sdm;
2780   KSP            ksp;
2781 
2782   PetscFunctionBegin;
2783   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
2784   PetscValidHeaderSpecific(X,VEC_CLASSID,2);
2785   PetscCheckSameComm(snes,1,X,2);
2786   PetscCall(VecValidValues(X,2,PETSC_TRUE));
2787   PetscCall(SNESGetDM(snes,&dm));
2788   PetscCall(DMGetDMSNES(dm,&sdm));
2789 
2790   PetscCheck(sdm->ops->computejacobian,PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Must call SNESSetJacobian(), DMSNESSetJacobian(), DMDASNESSetJacobianLocal(), etc");
2791 
2792   /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix free */
2793 
2794   if (snes->lagjacobian == -2) {
2795     snes->lagjacobian = -1;
2796 
2797     PetscCall(PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n"));
2798   } else if (snes->lagjacobian == -1) {
2799     PetscCall(PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n"));
2800     PetscCall(PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag));
2801     if (flag) {
2802       PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
2803       PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2804     }
2805     PetscFunctionReturn(0);
2806   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2807     PetscCall(PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n",snes->lagjacobian,snes->iter));
2808     PetscCall(PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag));
2809     if (flag) {
2810       PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
2811       PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2812     }
2813     PetscFunctionReturn(0);
2814   }
2815   if (snes->npc && snes->npcside == PC_LEFT) {
2816     PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
2817     PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
2818     PetscFunctionReturn(0);
2819   }
2820 
2821   PetscCall(PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B));
2822   PetscCall(VecLockReadPush(X));
2823   {
2824     void *ctx;
2825     PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*);
2826     PetscCall(DMSNESGetJacobian(dm,&J,&ctx));
2827     PetscCallBack("SNES callback Jacobian",(*J)(snes,X,A,B,ctx));
2828   }
2829   PetscCall(VecLockReadPop(X));
2830   PetscCall(PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B));
2831 
2832   /* attach latest linearization point to the preconditioning matrix */
2833   PetscCall(PetscObjectCompose((PetscObject)B,"__SNES_latest_X",(PetscObject)X));
2834 
2835   /* the next line ensures that snes->ksp exists */
2836   PetscCall(SNESGetKSP(snes,&ksp));
2837   if (snes->lagpreconditioner == -2) {
2838     PetscCall(PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n"));
2839     PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE));
2840     snes->lagpreconditioner = -1;
2841   } else if (snes->lagpreconditioner == -1) {
2842     PetscCall(PetscInfo(snes,"Reusing preconditioner because lag is -1\n"));
2843     PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE));
2844   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2845     PetscCall(PetscInfo(snes,"Reusing preconditioner because lag is %" PetscInt_FMT " and SNES iteration is %" PetscInt_FMT "\n",snes->lagpreconditioner,snes->iter));
2846     PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE));
2847   } else {
2848     PetscCall(PetscInfo(snes,"Rebuilding preconditioner\n"));
2849     PetscCall(KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE));
2850   }
2851 
2852   PetscCall(SNESTestJacobian(snes));
2853   /* make sure user returned a correct Jacobian and preconditioner */
2854   /* PetscValidHeaderSpecific(A,MAT_CLASSID,3);
2855     PetscValidHeaderSpecific(B,MAT_CLASSID,4);   */
2856   {
2857     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2858     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag));
2859     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw));
2860     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour));
2861     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator));
2862     if (flag || flag_draw || flag_contour) {
2863       Mat          Bexp_mine = NULL,Bexp,FDexp;
2864       PetscViewer  vdraw,vstdout;
2865       PetscBool    flg;
2866       if (flag_operator) {
2867         PetscCall(MatComputeOperator(A,MATAIJ,&Bexp_mine));
2868         Bexp = Bexp_mine;
2869       } else {
2870         /* See if the preconditioning matrix can be viewed and added directly */
2871         PetscCall(PetscObjectBaseTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,""));
2872         if (flg) Bexp = B;
2873         else {
2874           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2875           PetscCall(MatComputeOperator(B,MATAIJ,&Bexp_mine));
2876           Bexp = Bexp_mine;
2877         }
2878       }
2879       PetscCall(MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp));
2880       PetscCall(SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL));
2881       PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout));
2882       if (flag_draw || flag_contour) {
2883         PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw));
2884         if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
2885       } else vdraw = NULL;
2886       PetscCall(PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian"));
2887       if (flag) PetscCall(MatView(Bexp,vstdout));
2888       if (vdraw) PetscCall(MatView(Bexp,vdraw));
2889       PetscCall(PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n"));
2890       if (flag) PetscCall(MatView(FDexp,vstdout));
2891       if (vdraw) PetscCall(MatView(FDexp,vdraw));
2892       PetscCall(MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN));
2893       PetscCall(PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n"));
2894       if (flag) PetscCall(MatView(FDexp,vstdout));
2895       if (vdraw) {              /* Always use contour for the difference */
2896         PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
2897         PetscCall(MatView(FDexp,vdraw));
2898         PetscCall(PetscViewerPopFormat(vdraw));
2899       }
2900       if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
2901       PetscCall(PetscViewerDestroy(&vdraw));
2902       PetscCall(MatDestroy(&Bexp_mine));
2903       PetscCall(MatDestroy(&FDexp));
2904     }
2905   }
2906   {
2907     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2908     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2909     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag));
2910     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display));
2911     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw));
2912     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour));
2913     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold));
2914     if (flag_threshold) {
2915       PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL));
2916       PetscCall(PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL));
2917     }
2918     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2919       Mat            Bfd;
2920       PetscViewer    vdraw,vstdout;
2921       MatColoring    coloring;
2922       ISColoring     iscoloring;
2923       MatFDColoring  matfdcoloring;
2924       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2925       void           *funcctx;
2926       PetscReal      norm1,norm2,normmax;
2927 
2928       PetscCall(MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd));
2929       PetscCall(MatColoringCreate(Bfd,&coloring));
2930       PetscCall(MatColoringSetType(coloring,MATCOLORINGSL));
2931       PetscCall(MatColoringSetFromOptions(coloring));
2932       PetscCall(MatColoringApply(coloring,&iscoloring));
2933       PetscCall(MatColoringDestroy(&coloring));
2934       PetscCall(MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring));
2935       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
2936       PetscCall(MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring));
2937       PetscCall(ISColoringDestroy(&iscoloring));
2938 
2939       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2940       PetscCall(SNESGetFunction(snes,NULL,&func,&funcctx));
2941       PetscCall(MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx));
2942       PetscCall(PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix));
2943       PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_"));
2944       PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
2945       PetscCall(MatFDColoringApply(Bfd,matfdcoloring,X,snes));
2946       PetscCall(MatFDColoringDestroy(&matfdcoloring));
2947 
2948       PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout));
2949       if (flag_draw || flag_contour) {
2950         PetscCall(PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw));
2951         if (flag_contour) PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
2952       } else vdraw = NULL;
2953       PetscCall(PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n"));
2954       if (flag_display) PetscCall(MatView(B,vstdout));
2955       if (vdraw) PetscCall(MatView(B,vdraw));
2956       PetscCall(PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n"));
2957       if (flag_display) PetscCall(MatView(Bfd,vstdout));
2958       if (vdraw) PetscCall(MatView(Bfd,vdraw));
2959       PetscCall(MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN));
2960       PetscCall(MatNorm(Bfd,NORM_1,&norm1));
2961       PetscCall(MatNorm(Bfd,NORM_FROBENIUS,&norm2));
2962       PetscCall(MatNorm(Bfd,NORM_MAX,&normmax));
2963       PetscCall(PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax));
2964       if (flag_display) PetscCall(MatView(Bfd,vstdout));
2965       if (vdraw) {              /* Always use contour for the difference */
2966         PetscCall(PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR));
2967         PetscCall(MatView(Bfd,vdraw));
2968         PetscCall(PetscViewerPopFormat(vdraw));
2969       }
2970       if (flag_contour) PetscCall(PetscViewerPopFormat(vdraw));
2971 
2972       if (flag_threshold) {
2973         PetscInt bs,rstart,rend,i;
2974         PetscCall(MatGetBlockSize(B,&bs));
2975         PetscCall(MatGetOwnershipRange(B,&rstart,&rend));
2976         for (i=rstart; i<rend; i++) {
2977           const PetscScalar *ba,*ca;
2978           const PetscInt    *bj,*cj;
2979           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2980           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2981           PetscCall(MatGetRow(B,i,&bn,&bj,&ba));
2982           PetscCall(MatGetRow(Bfd,i,&cn,&cj,&ca));
2983           PetscCheck(bn == cn,((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2984           for (j=0; j<bn; j++) {
2985             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2986             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2987               maxentrycol = bj[j];
2988               maxentry    = PetscRealPart(ba[j]);
2989             }
2990             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2991               maxdiffcol = bj[j];
2992               maxdiff    = PetscRealPart(ca[j]);
2993             }
2994             if (rdiff > maxrdiff) {
2995               maxrdiffcol = bj[j];
2996               maxrdiff    = rdiff;
2997             }
2998           }
2999           if (maxrdiff > 1) {
3000             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));
3001             for (j=0; j<bn; j++) {
3002               PetscReal rdiff;
3003               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
3004               if (rdiff > 1) {
3005                 PetscCall(PetscViewerASCIIPrintf(vstdout," (%" PetscInt_FMT ",%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j])));
3006               }
3007             }
3008             PetscCall(PetscViewerASCIIPrintf(vstdout,"\n"));
3009           }
3010           PetscCall(MatRestoreRow(B,i,&bn,&bj,&ba));
3011           PetscCall(MatRestoreRow(Bfd,i,&cn,&cj,&ca));
3012         }
3013       }
3014       PetscCall(PetscViewerDestroy(&vdraw));
3015       PetscCall(MatDestroy(&Bfd));
3016     }
3017   }
3018   PetscFunctionReturn(0);
3019 }
3020 
3021 /*MC
3022     SNESJacobianFunction - Function used to convey the nonlinear Jacobian of the function to be solved by SNES
3023 
3024      Synopsis:
3025      #include "petscsnes.h"
3026      PetscErrorCode SNESJacobianFunction(SNES snes,Vec x,Mat Amat,Mat Pmat,void *ctx);
3027 
3028      Collective on snes
3029 
3030     Input Parameters:
3031 +  x - input vector, the Jacobian is to be computed at this value
3032 -  ctx - [optional] user-defined Jacobian context
3033 
3034     Output Parameters:
3035 +  Amat - the matrix that defines the (approximate) Jacobian
3036 -  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
3037 
3038    Level: intermediate
3039 
3040 .seealso: `SNESSetFunction()`, `SNESGetFunction()`, `SNESSetJacobian()`, `SNESGetJacobian()`
3041 M*/
3042 
3043 /*@C
3044    SNESSetJacobian - Sets the function to compute Jacobian as well as the
3045    location to store the matrix.
3046 
3047    Logically Collective on SNES
3048 
3049    Input Parameters:
3050 +  snes - the SNES context
3051 .  Amat - the matrix that defines the (approximate) Jacobian
3052 .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
3053 .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
3054 -  ctx - [optional] user-defined context for private data for the
3055          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)
3056 
3057    Notes:
3058    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
3059    each matrix.
3060 
3061    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
3062    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
3063 
3064    If using SNESComputeJacobianDefaultColor() to assemble a Jacobian, the ctx argument
3065    must be a MatFDColoring.
3066 
3067    Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian.  One common
3068    example is to use the "Picard linearization" which only differentiates through the highest order parts of each term.
3069 
3070    Level: beginner
3071 
3072 .seealso: `KSPSetOperators()`, `SNESSetFunction()`, `MatMFFDComputeJacobian()`, `SNESComputeJacobianDefaultColor()`, `MatStructure`, `J`,
3073           `SNESSetPicard()`, `SNESJacobianFunction`
3074 @*/
3075 PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
3076 {
3077   DM             dm;
3078 
3079   PetscFunctionBegin;
3080   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3081   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
3082   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
3083   if (Amat) PetscCheckSameComm(snes,1,Amat,2);
3084   if (Pmat) PetscCheckSameComm(snes,1,Pmat,3);
3085   PetscCall(SNESGetDM(snes,&dm));
3086   PetscCall(DMSNESSetJacobian(dm,J,ctx));
3087   if (Amat) {
3088     PetscCall(PetscObjectReference((PetscObject)Amat));
3089     PetscCall(MatDestroy(&snes->jacobian));
3090 
3091     snes->jacobian = Amat;
3092   }
3093   if (Pmat) {
3094     PetscCall(PetscObjectReference((PetscObject)Pmat));
3095     PetscCall(MatDestroy(&snes->jacobian_pre));
3096 
3097     snes->jacobian_pre = Pmat;
3098   }
3099   PetscFunctionReturn(0);
3100 }
3101 
3102 /*@C
3103    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3104    provided context for evaluating the Jacobian.
3105 
3106    Not Collective, but Mat object will be parallel if SNES object is
3107 
3108    Input Parameter:
3109 .  snes - the nonlinear solver context
3110 
3111    Output Parameters:
3112 +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
3113 .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
3114 .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
3115 -  ctx - location to stash Jacobian ctx (or NULL)
3116 
3117    Level: advanced
3118 
3119 .seealso: `SNESSetJacobian()`, `SNESComputeJacobian()`, `SNESJacobianFunction`, `SNESGetFunction()`
3120 @*/
3121 PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
3122 {
3123   DM             dm;
3124 
3125   PetscFunctionBegin;
3126   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3127   if (Amat) *Amat = snes->jacobian;
3128   if (Pmat) *Pmat = snes->jacobian_pre;
3129   PetscCall(SNESGetDM(snes,&dm));
3130   PetscCall(DMSNESGetJacobian(dm,J,ctx));
3131   PetscFunctionReturn(0);
3132 }
3133 
3134 static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3135 {
3136   DM             dm;
3137   DMSNES         sdm;
3138 
3139   PetscFunctionBegin;
3140   PetscCall(SNESGetDM(snes,&dm));
3141   PetscCall(DMGetDMSNES(dm,&sdm));
3142   if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3143     DM        dm;
3144     PetscBool isdense,ismf;
3145 
3146     PetscCall(SNESGetDM(snes,&dm));
3147     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&isdense,MATSEQDENSE,MATMPIDENSE,MATDENSE,NULL));
3148     PetscCall(PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&ismf,MATMFFD,MATSHELL,NULL));
3149     if (isdense) {
3150       PetscCall(DMSNESSetJacobian(dm,SNESComputeJacobianDefault,NULL));
3151     } else if (!ismf) {
3152       PetscCall(DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL));
3153     }
3154   }
3155   PetscFunctionReturn(0);
3156 }
3157 
3158 /*@
3159    SNESSetUp - Sets up the internal data structures for the later use
3160    of a nonlinear solver.
3161 
3162    Collective on SNES
3163 
3164    Input Parameters:
3165 .  snes - the SNES context
3166 
3167    Notes:
3168    For basic use of the SNES solvers the user need not explicitly call
3169    SNESSetUp(), since these actions will automatically occur during
3170    the call to SNESSolve().  However, if one wishes to control this
3171    phase separately, SNESSetUp() should be called after SNESCreate()
3172    and optional routines of the form SNESSetXXX(), but before SNESSolve().
3173 
3174    Level: advanced
3175 
3176 .seealso: `SNESCreate()`, `SNESSolve()`, `SNESDestroy()`
3177 @*/
3178 PetscErrorCode  SNESSetUp(SNES snes)
3179 {
3180   DM             dm;
3181   DMSNES         sdm;
3182   SNESLineSearch linesearch, pclinesearch;
3183   void           *lsprectx,*lspostctx;
3184   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
3185   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
3186   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
3187   Vec            f,fpc;
3188   void           *funcctx;
3189   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
3190   void           *jacctx,*appctx;
3191   Mat            j,jpre;
3192 
3193   PetscFunctionBegin;
3194   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3195   if (snes->setupcalled) PetscFunctionReturn(0);
3196   PetscCall(PetscLogEventBegin(SNES_Setup,snes,0,0,0));
3197 
3198   if (!((PetscObject)snes)->type_name) {
3199     PetscCall(SNESSetType(snes,SNESNEWTONLS));
3200   }
3201 
3202   PetscCall(SNESGetFunction(snes,&snes->vec_func,NULL,NULL));
3203 
3204   PetscCall(SNESGetDM(snes,&dm));
3205   PetscCall(DMGetDMSNES(dm,&sdm));
3206   PetscCheck(sdm->ops->computefunction,PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
3207   PetscCall(SNESSetDefaultComputeJacobian(snes));
3208 
3209   if (!snes->vec_func) {
3210     PetscCall(DMCreateGlobalVector(dm,&snes->vec_func));
3211   }
3212 
3213   if (!snes->ksp) {
3214     PetscCall(SNESGetKSP(snes, &snes->ksp));
3215   }
3216 
3217   if (snes->linesearch) {
3218     PetscCall(SNESGetLineSearch(snes, &snes->linesearch));
3219     PetscCall(SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction));
3220   }
3221 
3222   if (snes->npc && snes->npcside == PC_LEFT) {
3223     snes->mf          = PETSC_TRUE;
3224     snes->mf_operator = PETSC_FALSE;
3225   }
3226 
3227   if (snes->npc) {
3228     /* copy the DM over */
3229     PetscCall(SNESGetDM(snes,&dm));
3230     PetscCall(SNESSetDM(snes->npc,dm));
3231 
3232     PetscCall(SNESGetFunction(snes,&f,&func,&funcctx));
3233     PetscCall(VecDuplicate(f,&fpc));
3234     PetscCall(SNESSetFunction(snes->npc,fpc,func,funcctx));
3235     PetscCall(SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx));
3236     PetscCall(SNESSetJacobian(snes->npc,j,jpre,jac,jacctx));
3237     PetscCall(SNESGetApplicationContext(snes,&appctx));
3238     PetscCall(SNESSetApplicationContext(snes->npc,appctx));
3239     PetscCall(VecDestroy(&fpc));
3240 
3241     /* copy the function pointers over */
3242     PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)snes,(PetscObject)snes->npc));
3243 
3244     /* default to 1 iteration */
3245     PetscCall(SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs));
3246     if (snes->npcside == PC_RIGHT) {
3247       PetscCall(SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY));
3248     } else {
3249       PetscCall(SNESSetNormSchedule(snes->npc,SNES_NORM_NONE));
3250     }
3251     PetscCall(SNESSetFromOptions(snes->npc));
3252 
3253     /* copy the line search context over */
3254     if (snes->linesearch && snes->npc->linesearch) {
3255       PetscCall(SNESGetLineSearch(snes,&linesearch));
3256       PetscCall(SNESGetLineSearch(snes->npc,&pclinesearch));
3257       PetscCall(SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx));
3258       PetscCall(SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx));
3259       PetscCall(SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx));
3260       PetscCall(SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx));
3261       PetscCall(PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch));
3262     }
3263   }
3264   if (snes->mf) PetscCall(SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version));
3265   if (snes->ops->usercompute && !snes->user) {
3266     PetscCall((*snes->ops->usercompute)(snes,(void**)&snes->user));
3267   }
3268 
3269   snes->jac_iter = 0;
3270   snes->pre_iter = 0;
3271 
3272   if (snes->ops->setup) PetscCall((*snes->ops->setup)(snes));
3273 
3274   PetscCall(SNESSetDefaultComputeJacobian(snes));
3275 
3276   if (snes->npc && snes->npcside == PC_LEFT) {
3277     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3278       if (snes->linesearch) {
3279         PetscCall(SNESGetLineSearch(snes,&linesearch));
3280         PetscCall(SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC));
3281       }
3282     }
3283   }
3284   PetscCall(PetscLogEventEnd(SNES_Setup,snes,0,0,0));
3285   snes->setupcalled = PETSC_TRUE;
3286   PetscFunctionReturn(0);
3287 }
3288 
3289 /*@
3290    SNESReset - Resets a SNES context to the snessetupcalled = 0 state and removes any allocated Vecs and Mats
3291 
3292    Collective on SNES
3293 
3294    Input Parameter:
3295 .  snes - iterative context obtained from SNESCreate()
3296 
3297    Level: intermediate
3298 
3299    Notes:
3300     Also calls the application context destroy routine set with SNESSetComputeApplicationContext()
3301 
3302 .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESSolve()`
3303 @*/
3304 PetscErrorCode  SNESReset(SNES snes)
3305 {
3306   PetscFunctionBegin;
3307   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3308   if (snes->ops->userdestroy && snes->user) {
3309     PetscCall((*snes->ops->userdestroy)((void**)&snes->user));
3310     snes->user = NULL;
3311   }
3312   if (snes->npc) PetscCall(SNESReset(snes->npc));
3313 
3314   if (snes->ops->reset) PetscCall((*snes->ops->reset)(snes));
3315   if (snes->ksp) PetscCall(KSPReset(snes->ksp));
3316 
3317   if (snes->linesearch) PetscCall(SNESLineSearchReset(snes->linesearch));
3318 
3319   PetscCall(VecDestroy(&snes->vec_rhs));
3320   PetscCall(VecDestroy(&snes->vec_sol));
3321   PetscCall(VecDestroy(&snes->vec_sol_update));
3322   PetscCall(VecDestroy(&snes->vec_func));
3323   PetscCall(MatDestroy(&snes->jacobian));
3324   PetscCall(MatDestroy(&snes->jacobian_pre));
3325   PetscCall(MatDestroy(&snes->picard));
3326   PetscCall(VecDestroyVecs(snes->nwork,&snes->work));
3327   PetscCall(VecDestroyVecs(snes->nvwork,&snes->vwork));
3328 
3329   snes->alwayscomputesfinalresidual = PETSC_FALSE;
3330 
3331   snes->nwork       = snes->nvwork = 0;
3332   snes->setupcalled = PETSC_FALSE;
3333   PetscFunctionReturn(0);
3334 }
3335 
3336 /*@
3337    SNESConvergedReasonViewCancel - Clears all the reasonview functions for a SNES object.
3338 
3339    Collective on SNES
3340 
3341    Input Parameter:
3342 .  snes - iterative context obtained from SNESCreate()
3343 
3344    Level: intermediate
3345 
3346 .seealso: `SNESCreate()`, `SNESDestroy()`, `SNESReset()`
3347 @*/
3348 PetscErrorCode  SNESConvergedReasonViewCancel(SNES snes)
3349 {
3350   PetscInt       i;
3351 
3352   PetscFunctionBegin;
3353   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3354   for (i=0; i<snes->numberreasonviews; i++) {
3355     if (snes->reasonviewdestroy[i]) {
3356       PetscCall((*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]));
3357     }
3358   }
3359   snes->numberreasonviews = 0;
3360   PetscFunctionReturn(0);
3361 }
3362 
3363 /*@C
3364    SNESDestroy - Destroys the nonlinear solver context that was created
3365    with SNESCreate().
3366 
3367    Collective on SNES
3368 
3369    Input Parameter:
3370 .  snes - the SNES context
3371 
3372    Level: beginner
3373 
3374 .seealso: `SNESCreate()`, `SNESSolve()`
3375 @*/
3376 PetscErrorCode  SNESDestroy(SNES *snes)
3377 {
3378   PetscFunctionBegin;
3379   if (!*snes) PetscFunctionReturn(0);
3380   PetscValidHeaderSpecific((*snes),SNES_CLASSID,1);
3381   if (--((PetscObject)(*snes))->refct > 0) {*snes = NULL; PetscFunctionReturn(0);}
3382 
3383   PetscCall(SNESReset((*snes)));
3384   PetscCall(SNESDestroy(&(*snes)->npc));
3385 
3386   /* if memory was published with SAWs then destroy it */
3387   PetscCall(PetscObjectSAWsViewOff((PetscObject)*snes));
3388   if ((*snes)->ops->destroy) PetscCall((*((*snes))->ops->destroy)((*snes)));
3389 
3390   if ((*snes)->dm) PetscCall(DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes));
3391   PetscCall(DMDestroy(&(*snes)->dm));
3392   PetscCall(KSPDestroy(&(*snes)->ksp));
3393   PetscCall(SNESLineSearchDestroy(&(*snes)->linesearch));
3394 
3395   PetscCall(PetscFree((*snes)->kspconvctx));
3396   if ((*snes)->ops->convergeddestroy) {
3397     PetscCall((*(*snes)->ops->convergeddestroy)((*snes)->cnvP));
3398   }
3399   if ((*snes)->conv_hist_alloc) {
3400     PetscCall(PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its));
3401   }
3402   PetscCall(SNESMonitorCancel((*snes)));
3403   PetscCall(SNESConvergedReasonViewCancel((*snes)));
3404   PetscCall(PetscHeaderDestroy(snes));
3405   PetscFunctionReturn(0);
3406 }
3407 
3408 /* ----------- Routines to set solver parameters ---------- */
3409 
3410 /*@
3411    SNESSetLagPreconditioner - Determines when the preconditioner is rebuilt in the nonlinear solve.
3412 
3413    Logically Collective on SNES
3414 
3415    Input Parameters:
3416 +  snes - the SNES context
3417 -  lag - 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3418          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3419 
3420    Options Database Keys:
3421 +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3422 .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3423 .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3424 -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3425 
3426    Notes:
3427    The default is 1
3428    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagPreconditionerPersists() was called
3429 
3430    SNESSetLagPreconditionerPersists() allows using the same uniform lagging (for example every second solve) across multiple solves.
3431 
3432    Level: intermediate
3433 
3434 .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetLagPreconditionerPersists()`,
3435           `SNESSetLagJacobianPersists()`
3436 
3437 @*/
3438 PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3439 {
3440   PetscFunctionBegin;
3441   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3442   PetscCheck(lag >= -2,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3443   PetscCheck(lag,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3444   PetscValidLogicalCollectiveInt(snes,lag,2);
3445   snes->lagpreconditioner = lag;
3446   PetscFunctionReturn(0);
3447 }
3448 
3449 /*@
3450    SNESSetGridSequence - sets the number of steps of grid sequencing that SNES does
3451 
3452    Logically Collective on SNES
3453 
3454    Input Parameters:
3455 +  snes - the SNES context
3456 -  steps - the number of refinements to do, defaults to 0
3457 
3458    Options Database Keys:
3459 .    -snes_grid_sequence <steps> - Use grid sequencing to generate initial guess
3460 
3461    Level: intermediate
3462 
3463    Notes:
3464    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3465 
3466 .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetGridSequence()`
3467 
3468 @*/
3469 PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3470 {
3471   PetscFunctionBegin;
3472   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3473   PetscValidLogicalCollectiveInt(snes,steps,2);
3474   snes->gridsequence = steps;
3475   PetscFunctionReturn(0);
3476 }
3477 
3478 /*@
3479    SNESGetGridSequence - gets the number of steps of grid sequencing that SNES does
3480 
3481    Logically Collective on SNES
3482 
3483    Input Parameter:
3484 .  snes - the SNES context
3485 
3486    Output Parameter:
3487 .  steps - the number of refinements to do, defaults to 0
3488 
3489    Options Database Keys:
3490 .    -snes_grid_sequence <steps> - set number of refinements
3491 
3492    Level: intermediate
3493 
3494    Notes:
3495    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.
3496 
3497 .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESSetGridSequence()`
3498 
3499 @*/
3500 PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3501 {
3502   PetscFunctionBegin;
3503   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3504   *steps = snes->gridsequence;
3505   PetscFunctionReturn(0);
3506 }
3507 
3508 /*@
3509    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt
3510 
3511    Not Collective
3512 
3513    Input Parameter:
3514 .  snes - the SNES context
3515 
3516    Output Parameter:
3517 .   lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3518          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that
3519 
3520    Options Database Keys:
3521 +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3522 .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3523 .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3524 -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3525 
3526    Notes:
3527    The default is 1
3528    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3529 
3530    Level: intermediate
3531 
3532 .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3533 
3534 @*/
3535 PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3536 {
3537   PetscFunctionBegin;
3538   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3539   *lag = snes->lagpreconditioner;
3540   PetscFunctionReturn(0);
3541 }
3542 
3543 /*@
3544    SNESSetLagJacobian - Determines when the Jacobian is rebuilt in the nonlinear solve. See SNESSetLagPreconditioner() for determining how
3545      often the preconditioner is rebuilt.
3546 
3547    Logically Collective on SNES
3548 
3549    Input Parameters:
3550 +  snes - the SNES context
3551 -  lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3552          the Jacobian is built etc. -2 means rebuild at next chance but then never again
3553 
3554    Options Database Keys:
3555 +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3556 .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3557 .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3558 -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag.
3559 
3560    Notes:
3561    The default is 1
3562    The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3563    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
3564    at the next Newton step but never again (unless it is reset to another value)
3565 
3566    Level: intermediate
3567 
3568 .seealso: `SNESSetTrustRegionTolerance()`, `SNESGetLagPreconditioner()`, `SNESSetLagPreconditioner()`, `SNESGetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3569 
3570 @*/
3571 PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3572 {
3573   PetscFunctionBegin;
3574   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3575   PetscCheck(lag >= -2,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3576   PetscCheck(lag,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3577   PetscValidLogicalCollectiveInt(snes,lag,2);
3578   snes->lagjacobian = lag;
3579   PetscFunctionReturn(0);
3580 }
3581 
3582 /*@
3583    SNESGetLagJacobian - Indicates how often the Jacobian is rebuilt. See SNESGetLagPreconditioner() to determine when the preconditioner is rebuilt
3584 
3585    Not Collective
3586 
3587    Input Parameter:
3588 .  snes - the SNES context
3589 
3590    Output Parameter:
3591 .   lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3592          the Jacobian is built etc.
3593 
3594    Notes:
3595    The default is 1
3596    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagJacobianPersists() was called.
3597 
3598    Level: intermediate
3599 
3600 .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetLagJacobian()`, `SNESSetLagPreconditioner()`, `SNESGetLagPreconditioner()`, `SNESSetLagJacobianPersists()`, `SNESSetLagPreconditionerPersists()`
3601 
3602 @*/
3603 PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3604 {
3605   PetscFunctionBegin;
3606   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3607   *lag = snes->lagjacobian;
3608   PetscFunctionReturn(0);
3609 }
3610 
3611 /*@
3612    SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple solves
3613 
3614    Logically collective on SNES
3615 
3616    Input Parameters:
3617 +  snes - the SNES context
3618 -   flg - jacobian lagging persists if true
3619 
3620    Options Database Keys:
3621 +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3622 .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3623 .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3624 -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3625 
3626    Notes:
3627     This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
3628    several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
3629    timesteps may present huge efficiency gains.
3630 
3631    Level: developer
3632 
3633 .seealso: `SNESSetLagPreconditionerPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagJacobianPersists()`
3634 
3635 @*/
3636 PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3637 {
3638   PetscFunctionBegin;
3639   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3640   PetscValidLogicalCollectiveBool(snes,flg,2);
3641   snes->lagjac_persist = flg;
3642   PetscFunctionReturn(0);
3643 }
3644 
3645 /*@
3646    SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves
3647 
3648    Logically Collective on SNES
3649 
3650    Input Parameters:
3651 +  snes - the SNES context
3652 -   flg - preconditioner lagging persists if true
3653 
3654    Options Database Keys:
3655 +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3656 .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3657 .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3658 -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag
3659 
3660    Notes:
3661     This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
3662    by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
3663    several timesteps may present huge efficiency gains.
3664 
3665    Level: developer
3666 
3667 .seealso: `SNESSetLagJacobianPersists()`, `SNESSetLagJacobian()`, `SNESGetLagJacobian()`, `SNESGetNPC()`, `SNESSetLagPreconditioner()`
3668 
3669 @*/
3670 PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3671 {
3672   PetscFunctionBegin;
3673   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3674   PetscValidLogicalCollectiveBool(snes,flg,2);
3675   snes->lagpre_persist = flg;
3676   PetscFunctionReturn(0);
3677 }
3678 
3679 /*@
3680    SNESSetForceIteration - force SNESSolve() to take at least one iteration regardless of the initial residual norm
3681 
3682    Logically Collective on SNES
3683 
3684    Input Parameters:
3685 +  snes - the SNES context
3686 -  force - PETSC_TRUE require at least one iteration
3687 
3688    Options Database Keys:
3689 .    -snes_force_iteration <force> - Sets forcing an iteration
3690 
3691    Notes:
3692    This is used sometimes with TS to prevent TS from detecting a false steady state solution
3693 
3694    Level: intermediate
3695 
3696 .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()`
3697 @*/
3698 PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3699 {
3700   PetscFunctionBegin;
3701   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3702   snes->forceiteration = force;
3703   PetscFunctionReturn(0);
3704 }
3705 
3706 /*@
3707    SNESGetForceIteration - Whether or not to force SNESSolve() take at least one iteration regardless of the initial residual norm
3708 
3709    Logically Collective on SNES
3710 
3711    Input Parameters:
3712 .  snes - the SNES context
3713 
3714    Output Parameter:
3715 .  force - PETSC_TRUE requires at least one iteration.
3716 
3717    Level: intermediate
3718 
3719 .seealso: `SNESSetForceIteration()`, `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()`
3720 @*/
3721 PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
3722 {
3723   PetscFunctionBegin;
3724   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3725   *force = snes->forceiteration;
3726   PetscFunctionReturn(0);
3727 }
3728 
3729 /*@
3730    SNESSetTolerances - Sets various parameters used in convergence tests.
3731 
3732    Logically Collective on SNES
3733 
3734    Input Parameters:
3735 +  snes - the SNES context
3736 .  abstol - absolute convergence tolerance
3737 .  rtol - relative convergence tolerance
3738 .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3739 .  maxit - maximum number of iterations
3740 -  maxf - maximum number of function evaluations (-1 indicates no limit)
3741 
3742    Options Database Keys:
3743 +    -snes_atol <abstol> - Sets abstol
3744 .    -snes_rtol <rtol> - Sets rtol
3745 .    -snes_stol <stol> - Sets stol
3746 .    -snes_max_it <maxit> - Sets maxit
3747 -    -snes_max_funcs <maxf> - Sets maxf
3748 
3749    Notes:
3750    The default maximum number of iterations is 50.
3751    The default maximum number of function evaluations is 1000.
3752 
3753    Level: intermediate
3754 
3755 .seealso: `SNESSetTrustRegionTolerance()`, `SNESSetDivergenceTolerance()`, `SNESSetForceIteration()`
3756 @*/
3757 PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3758 {
3759   PetscFunctionBegin;
3760   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3761   PetscValidLogicalCollectiveReal(snes,abstol,2);
3762   PetscValidLogicalCollectiveReal(snes,rtol,3);
3763   PetscValidLogicalCollectiveReal(snes,stol,4);
3764   PetscValidLogicalCollectiveInt(snes,maxit,5);
3765   PetscValidLogicalCollectiveInt(snes,maxf,6);
3766 
3767   if (abstol != PETSC_DEFAULT) {
3768     PetscCheck(abstol >= 0.0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3769     snes->abstol = abstol;
3770   }
3771   if (rtol != PETSC_DEFAULT) {
3772     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);
3773     snes->rtol = rtol;
3774   }
3775   if (stol != PETSC_DEFAULT) {
3776     PetscCheck(stol >= 0.0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3777     snes->stol = stol;
3778   }
3779   if (maxit != PETSC_DEFAULT) {
3780     PetscCheck(maxit >= 0,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %" PetscInt_FMT " must be non-negative",maxit);
3781     snes->max_its = maxit;
3782   }
3783   if (maxf != PETSC_DEFAULT) {
3784     PetscCheck(maxf >= -1,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %" PetscInt_FMT " must be -1 or nonnegative",maxf);
3785     snes->max_funcs = maxf;
3786   }
3787   snes->tolerancesset = PETSC_TRUE;
3788   PetscFunctionReturn(0);
3789 }
3790 
3791 /*@
3792    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.
3793 
3794    Logically Collective on SNES
3795 
3796    Input Parameters:
3797 +  snes - the SNES context
3798 -  divtol - the divergence tolerance. Use -1 to deactivate the test.
3799 
3800    Options Database Keys:
3801 .    -snes_divergence_tolerance <divtol> - Sets divtol
3802 
3803    Notes:
3804    The default divergence tolerance is 1e4.
3805 
3806    Level: intermediate
3807 
3808 .seealso: `SNESSetTolerances()`, `SNESGetDivergenceTolerance`
3809 @*/
3810 PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3811 {
3812   PetscFunctionBegin;
3813   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3814   PetscValidLogicalCollectiveReal(snes,divtol,2);
3815 
3816   if (divtol != PETSC_DEFAULT) {
3817     snes->divtol = divtol;
3818   }
3819   else {
3820     snes->divtol = 1.0e4;
3821   }
3822   PetscFunctionReturn(0);
3823 }
3824 
3825 /*@
3826    SNESGetTolerances - Gets various parameters used in convergence tests.
3827 
3828    Not Collective
3829 
3830    Input Parameters:
3831 +  snes - the SNES context
3832 .  atol - absolute convergence tolerance
3833 .  rtol - relative convergence tolerance
3834 .  stol -  convergence tolerance in terms of the norm
3835            of the change in the solution between steps
3836 .  maxit - maximum number of iterations
3837 -  maxf - maximum number of function evaluations
3838 
3839    Notes:
3840    The user can specify NULL for any parameter that is not needed.
3841 
3842    Level: intermediate
3843 
3844 .seealso: `SNESSetTolerances()`
3845 @*/
3846 PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3847 {
3848   PetscFunctionBegin;
3849   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3850   if (atol)  *atol  = snes->abstol;
3851   if (rtol)  *rtol  = snes->rtol;
3852   if (stol)  *stol  = snes->stol;
3853   if (maxit) *maxit = snes->max_its;
3854   if (maxf)  *maxf  = snes->max_funcs;
3855   PetscFunctionReturn(0);
3856 }
3857 
3858 /*@
3859    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.
3860 
3861    Not Collective
3862 
3863    Input Parameters:
3864 +  snes - the SNES context
3865 -  divtol - divergence tolerance
3866 
3867    Level: intermediate
3868 
3869 .seealso: `SNESSetDivergenceTolerance()`
3870 @*/
3871 PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3872 {
3873   PetscFunctionBegin;
3874   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3875   if (divtol) *divtol = snes->divtol;
3876   PetscFunctionReturn(0);
3877 }
3878 
3879 /*@
3880    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.
3881 
3882    Logically Collective on SNES
3883 
3884    Input Parameters:
3885 +  snes - the SNES context
3886 -  tol - tolerance
3887 
3888    Options Database Key:
3889 .  -snes_trtol <tol> - Sets tol
3890 
3891    Level: intermediate
3892 
3893 .seealso: `SNESSetTolerances()`
3894 @*/
3895 PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3896 {
3897   PetscFunctionBegin;
3898   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3899   PetscValidLogicalCollectiveReal(snes,tol,2);
3900   snes->deltatol = tol;
3901   PetscFunctionReturn(0);
3902 }
3903 
3904 PETSC_INTERN PetscErrorCode  SNESMonitorRange_Private(SNES,PetscInt,PetscReal*);
3905 
3906 PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3907 {
3908   PetscDrawLG      lg;
3909   PetscReal        x,y,per;
3910   PetscViewer      v = (PetscViewer)monctx;
3911   static PetscReal prev; /* should be in the context */
3912   PetscDraw        draw;
3913 
3914   PetscFunctionBegin;
3915   PetscValidHeaderSpecific(v,PETSC_VIEWER_CLASSID,4);
3916   PetscCall(PetscViewerDrawGetDrawLG(v,0,&lg));
3917   if (!n) PetscCall(PetscDrawLGReset(lg));
3918   PetscCall(PetscDrawLGGetDraw(lg,&draw));
3919   PetscCall(PetscDrawSetTitle(draw,"Residual norm"));
3920   x    = (PetscReal)n;
3921   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3922   else y = -15.0;
3923   PetscCall(PetscDrawLGAddPoint(lg,&x,&y));
3924   if (n < 20 || !(n % 5) || snes->reason) {
3925     PetscCall(PetscDrawLGDraw(lg));
3926     PetscCall(PetscDrawLGSave(lg));
3927   }
3928 
3929   PetscCall(PetscViewerDrawGetDrawLG(v,1,&lg));
3930   if (!n) PetscCall(PetscDrawLGReset(lg));
3931   PetscCall(PetscDrawLGGetDraw(lg,&draw));
3932   PetscCall(PetscDrawSetTitle(draw,"% elemts > .2*max elemt"));
3933   PetscCall(SNESMonitorRange_Private(snes,n,&per));
3934   x    = (PetscReal)n;
3935   y    = 100.0*per;
3936   PetscCall(PetscDrawLGAddPoint(lg,&x,&y));
3937   if (n < 20 || !(n % 5) || snes->reason) {
3938     PetscCall(PetscDrawLGDraw(lg));
3939     PetscCall(PetscDrawLGSave(lg));
3940   }
3941 
3942   PetscCall(PetscViewerDrawGetDrawLG(v,2,&lg));
3943   if (!n) {prev = rnorm;PetscCall(PetscDrawLGReset(lg));}
3944   PetscCall(PetscDrawLGGetDraw(lg,&draw));
3945   PetscCall(PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm"));
3946   x    = (PetscReal)n;
3947   y    = (prev - rnorm)/prev;
3948   PetscCall(PetscDrawLGAddPoint(lg,&x,&y));
3949   if (n < 20 || !(n % 5) || snes->reason) {
3950     PetscCall(PetscDrawLGDraw(lg));
3951     PetscCall(PetscDrawLGSave(lg));
3952   }
3953 
3954   PetscCall(PetscViewerDrawGetDrawLG(v,3,&lg));
3955   if (!n) PetscCall(PetscDrawLGReset(lg));
3956   PetscCall(PetscDrawLGGetDraw(lg,&draw));
3957   PetscCall(PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)"));
3958   x    = (PetscReal)n;
3959   y    = (prev - rnorm)/(prev*per);
3960   if (n > 2) { /*skip initial crazy value */
3961     PetscCall(PetscDrawLGAddPoint(lg,&x,&y));
3962   }
3963   if (n < 20 || !(n % 5) || snes->reason) {
3964     PetscCall(PetscDrawLGDraw(lg));
3965     PetscCall(PetscDrawLGSave(lg));
3966   }
3967   prev = rnorm;
3968   PetscFunctionReturn(0);
3969 }
3970 
3971 /*@
3972    SNESMonitor - runs the user provided monitor routines, if they exist
3973 
3974    Collective on SNES
3975 
3976    Input Parameters:
3977 +  snes - nonlinear solver context obtained from SNESCreate()
3978 .  iter - iteration number
3979 -  rnorm - relative norm of the residual
3980 
3981    Notes:
3982    This routine is called by the SNES implementations.
3983    It does not typically need to be called by the user.
3984 
3985    Level: developer
3986 
3987 .seealso: `SNESMonitorSet()`
3988 @*/
3989 PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3990 {
3991   PetscInt       i,n = snes->numbermonitors;
3992 
3993   PetscFunctionBegin;
3994   PetscCall(VecLockReadPush(snes->vec_sol));
3995   for (i=0; i<n; i++) {
3996     PetscCall((*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]));
3997   }
3998   PetscCall(VecLockReadPop(snes->vec_sol));
3999   PetscFunctionReturn(0);
4000 }
4001 
4002 /* ------------ Routines to set performance monitoring options ----------- */
4003 
4004 /*MC
4005     SNESMonitorFunction - functional form passed to SNESMonitorSet() to monitor convergence of nonlinear solver
4006 
4007      Synopsis:
4008      #include <petscsnes.h>
4009 $    PetscErrorCode SNESMonitorFunction(SNES snes,PetscInt its, PetscReal norm,void *mctx)
4010 
4011      Collective on snes
4012 
4013     Input Parameters:
4014 +    snes - the SNES context
4015 .    its - iteration number
4016 .    norm - 2-norm function value (may be estimated)
4017 -    mctx - [optional] monitoring context
4018 
4019    Level: advanced
4020 
4021 .seealso: `SNESMonitorSet()`, `SNESMonitorGet()`
4022 M*/
4023 
4024 /*@C
4025    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
4026    iteration of the nonlinear solver to display the iteration's
4027    progress.
4028 
4029    Logically Collective on SNES
4030 
4031    Input Parameters:
4032 +  snes - the SNES context
4033 .  f - the monitor function, see SNESMonitorFunction for the calling sequence
4034 .  mctx - [optional] user-defined context for private data for the
4035           monitor routine (use NULL if no context is desired)
4036 -  monitordestroy - [optional] routine that frees monitor context
4037           (may be NULL)
4038 
4039    Options Database Keys:
4040 +    -snes_monitor        - sets SNESMonitorDefault()
4041 .    -snes_monitor draw::draw_lg - sets line graph monitor,
4042 -    -snes_monitor_cancel - cancels all monitors that have
4043                             been hardwired into a code by
4044                             calls to SNESMonitorSet(), but
4045                             does not cancel those set via
4046                             the options database.
4047 
4048    Notes:
4049    Several different monitoring routines may be set by calling
4050    SNESMonitorSet() multiple times; all will be called in the
4051    order in which they were set.
4052 
4053    Fortran Notes:
4054     Only a single monitor function can be set for each SNES object
4055 
4056    Level: intermediate
4057 
4058 .seealso: `SNESMonitorDefault()`, `SNESMonitorCancel()`, `SNESMonitorFunction`
4059 @*/
4060 PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
4061 {
4062   PetscInt       i;
4063   PetscBool      identical;
4064 
4065   PetscFunctionBegin;
4066   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4067   for (i=0; i<snes->numbermonitors;i++) {
4068     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical));
4069     if (identical) PetscFunctionReturn(0);
4070   }
4071   PetscCheck(snes->numbermonitors < MAXSNESMONITORS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
4072   snes->monitor[snes->numbermonitors]          = f;
4073   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
4074   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
4075   PetscFunctionReturn(0);
4076 }
4077 
4078 /*@
4079    SNESMonitorCancel - Clears all the monitor functions for a SNES object.
4080 
4081    Logically Collective on SNES
4082 
4083    Input Parameters:
4084 .  snes - the SNES context
4085 
4086    Options Database Key:
4087 .  -snes_monitor_cancel - cancels all monitors that have been hardwired
4088     into a code by calls to SNESMonitorSet(), but does not cancel those
4089     set via the options database
4090 
4091    Notes:
4092    There is no way to clear one specific monitor from a SNES object.
4093 
4094    Level: intermediate
4095 
4096 .seealso: `SNESMonitorDefault()`, `SNESMonitorSet()`
4097 @*/
4098 PetscErrorCode  SNESMonitorCancel(SNES snes)
4099 {
4100   PetscInt       i;
4101 
4102   PetscFunctionBegin;
4103   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4104   for (i=0; i<snes->numbermonitors; i++) {
4105     if (snes->monitordestroy[i]) {
4106       PetscCall((*snes->monitordestroy[i])(&snes->monitorcontext[i]));
4107     }
4108   }
4109   snes->numbermonitors = 0;
4110   PetscFunctionReturn(0);
4111 }
4112 
4113 /*MC
4114     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver
4115 
4116      Synopsis:
4117      #include <petscsnes.h>
4118 $     PetscErrorCode SNESConvergenceTest(SNES snes,PetscInt it,PetscReal xnorm,PetscReal gnorm,PetscReal f,SNESConvergedReason *reason,void *cctx)
4119 
4120      Collective on snes
4121 
4122     Input Parameters:
4123 +    snes - the SNES context
4124 .    it - current iteration (0 is the first and is before any Newton step)
4125 .    xnorm - 2-norm of current iterate
4126 .    gnorm - 2-norm of current step
4127 .    f - 2-norm of function
4128 -    cctx - [optional] convergence context
4129 
4130     Output Parameter:
4131 .    reason - reason for convergence/divergence, only needs to be set when convergence or divergence is detected
4132 
4133    Level: intermediate
4134 
4135 .seealso: `SNESSetConvergenceTest()`, `SNESGetConvergenceTest()`
4136 M*/
4137 
4138 /*@C
4139    SNESSetConvergenceTest - Sets the function that is to be used
4140    to test for convergence of the nonlinear iterative solution.
4141 
4142    Logically Collective on SNES
4143 
4144    Input Parameters:
4145 +  snes - the SNES context
4146 .  SNESConvergenceTestFunction - routine to test for convergence
4147 .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
4148 -  destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)
4149 
4150    Level: advanced
4151 
4152 .seealso: `SNESConvergedDefault()`, `SNESConvergedSkip()`, `SNESConvergenceTestFunction`
4153 @*/
4154 PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
4155 {
4156   PetscFunctionBegin;
4157   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4158   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
4159   if (snes->ops->convergeddestroy) PetscCall((*snes->ops->convergeddestroy)(snes->cnvP));
4160   snes->ops->converged        = SNESConvergenceTestFunction;
4161   snes->ops->convergeddestroy = destroy;
4162   snes->cnvP                  = cctx;
4163   PetscFunctionReturn(0);
4164 }
4165 
4166 /*@
4167    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.
4168 
4169    Not Collective
4170 
4171    Input Parameter:
4172 .  snes - the SNES context
4173 
4174    Output Parameter:
4175 .  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4176             manual pages for the individual convergence tests for complete lists
4177 
4178    Options Database:
4179 .   -snes_converged_reason - prints the reason to standard out
4180 
4181    Level: intermediate
4182 
4183    Notes:
4184     Should only be called after the call the SNESSolve() is complete, if it is called earlier it returns the value SNES__CONVERGED_ITERATING.
4185 
4186 .seealso: `SNESSetConvergenceTest()`, `SNESSetConvergedReason()`, `SNESConvergedReason`
4187 @*/
4188 PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4189 {
4190   PetscFunctionBegin;
4191   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4192   PetscValidPointer(reason,2);
4193   *reason = snes->reason;
4194   PetscFunctionReturn(0);
4195 }
4196 
4197 /*@C
4198    SNESGetConvergedReasonString - Return a human readable string for snes converged reason
4199 
4200    Not Collective
4201 
4202    Input Parameter:
4203 .  snes - the SNES context
4204 
4205    Output Parameter:
4206 .  strreason - a human readable string that describes SNES converged reason
4207 
4208    Level: beginner
4209 
4210 .seealso: `SNESGetConvergedReason()`
4211 @*/
4212 PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char** strreason)
4213 {
4214   PetscFunctionBegin;
4215   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4216   PetscValidPointer(strreason,2);
4217   *strreason = SNESConvergedReasons[snes->reason];
4218   PetscFunctionReturn(0);
4219 }
4220 
4221 /*@
4222    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.
4223 
4224    Not Collective
4225 
4226    Input Parameters:
4227 +  snes - the SNES context
4228 -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4229             manual pages for the individual convergence tests for complete lists
4230 
4231    Level: intermediate
4232 
4233 .seealso: `SNESGetConvergedReason()`, `SNESSetConvergenceTest()`, `SNESConvergedReason`
4234 @*/
4235 PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
4236 {
4237   PetscFunctionBegin;
4238   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4239   snes->reason = reason;
4240   PetscFunctionReturn(0);
4241 }
4242 
4243 /*@
4244    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.
4245 
4246    Logically Collective on SNES
4247 
4248    Input Parameters:
4249 +  snes - iterative context obtained from SNESCreate()
4250 .  a   - array to hold history, this array will contain the function norms computed at each step
4251 .  its - integer array holds the number of linear iterations for each solve.
4252 .  na  - size of a and its
4253 -  reset - PETSC_TRUE indicates each new nonlinear solve resets the history counter to zero,
4254            else it continues storing new values for new nonlinear solves after the old ones
4255 
4256    Notes:
4257    If 'a' and 'its' are NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
4258    default array of length 10000 is allocated.
4259 
4260    This routine is useful, e.g., when running a code for purposes
4261    of accurate performance monitoring, when no I/O should be done
4262    during the section of code that is being timed.
4263 
4264    Level: intermediate
4265 
4266 .seealso: `SNESGetConvergenceHistory()`
4267 
4268 @*/
4269 PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4270 {
4271   PetscFunctionBegin;
4272   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4273   if (a) PetscValidRealPointer(a,2);
4274   if (its) PetscValidIntPointer(its,3);
4275   if (!a) {
4276     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
4277     PetscCall(PetscCalloc2(na,&a,na,&its));
4278     snes->conv_hist_alloc = PETSC_TRUE;
4279   }
4280   snes->conv_hist       = a;
4281   snes->conv_hist_its   = its;
4282   snes->conv_hist_max   = (size_t)na;
4283   snes->conv_hist_len   = 0;
4284   snes->conv_hist_reset = reset;
4285   PetscFunctionReturn(0);
4286 }
4287 
4288 #if defined(PETSC_HAVE_MATLAB_ENGINE)
4289 #include <engine.h>   /* MATLAB include file */
4290 #include <mex.h>      /* MATLAB include file */
4291 
4292 PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4293 {
4294   mxArray   *mat;
4295   PetscInt  i;
4296   PetscReal *ar;
4297 
4298   PetscFunctionBegin;
4299   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4300   ar  = (PetscReal*) mxGetData(mat);
4301   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4302   PetscFunctionReturn(mat);
4303 }
4304 #endif
4305 
4306 /*@C
4307    SNESGetConvergenceHistory - Gets the array used to hold the convergence history.
4308 
4309    Not Collective
4310 
4311    Input Parameter:
4312 .  snes - iterative context obtained from SNESCreate()
4313 
4314    Output Parameters:
4315 +  a   - array to hold history
4316 .  its - integer array holds the number of linear iterations (or
4317          negative if not converged) for each solve.
4318 -  na  - size of a and its
4319 
4320    Notes:
4321     The calling sequence for this routine in Fortran is
4322 $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)
4323 
4324    This routine is useful, e.g., when running a code for purposes
4325    of accurate performance monitoring, when no I/O should be done
4326    during the section of code that is being timed.
4327 
4328    Level: intermediate
4329 
4330 .seealso: `SNESSetConvergenceHistory()`
4331 
4332 @*/
4333 PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4334 {
4335   PetscFunctionBegin;
4336   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4337   if (a)   *a   = snes->conv_hist;
4338   if (its) *its = snes->conv_hist_its;
4339   if (na)  *na  = (PetscInt) snes->conv_hist_len;
4340   PetscFunctionReturn(0);
4341 }
4342 
4343 /*@C
4344   SNESSetUpdate - Sets the general-purpose update function called
4345   at the beginning of every iteration of the nonlinear solve. Specifically
4346   it is called just before the Jacobian is "evaluated".
4347 
4348   Logically Collective on SNES
4349 
4350   Input Parameters:
4351 + snes - The nonlinear solver context
4352 - func - The function
4353 
4354   Calling sequence of func:
4355 $ func (SNES snes, PetscInt step);
4356 
4357 . step - The current step of the iteration
4358 
4359   Level: advanced
4360 
4361   Note:
4362      This is NOT what one uses to update the ghost points before a function evaluation, that should be done at the beginning of your FormFunction()
4363      This is not used by most users.
4364 
4365      There are a varity of function hooks one many set that are called at different stages of the nonlinear solution process, see the functions listed below.
4366 
4367 .seealso `SNESSetJacobian()`, `SNESSolve()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchSetPostCheck()`, `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRSetPostCheck()`,
4368          `SNESMonitorSet()`, `SNESSetDivergenceTest()`
4369 @*/
4370 PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4371 {
4372   PetscFunctionBegin;
4373   PetscValidHeaderSpecific(snes, SNES_CLASSID,1);
4374   snes->ops->update = func;
4375   PetscFunctionReturn(0);
4376 }
4377 
4378 /*
4379    SNESScaleStep_Private - Scales a step so that its length is less than the
4380    positive parameter delta.
4381 
4382     Input Parameters:
4383 +   snes - the SNES context
4384 .   y - approximate solution of linear system
4385 .   fnorm - 2-norm of current function
4386 -   delta - trust region size
4387 
4388     Output Parameters:
4389 +   gpnorm - predicted function norm at the new point, assuming local
4390     linearization.  The value is zero if the step lies within the trust
4391     region, and exceeds zero otherwise.
4392 -   ynorm - 2-norm of the step
4393 
4394     Note:
4395     For non-trust region methods such as SNESNEWTONLS, the parameter delta
4396     is set to be the maximum allowable step size.
4397 
4398 */
4399 PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4400 {
4401   PetscReal      nrm;
4402   PetscScalar    cnorm;
4403 
4404   PetscFunctionBegin;
4405   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4406   PetscValidHeaderSpecific(y,VEC_CLASSID,2);
4407   PetscCheckSameComm(snes,1,y,2);
4408 
4409   PetscCall(VecNorm(y,NORM_2,&nrm));
4410   if (nrm > *delta) {
4411     nrm     = *delta/nrm;
4412     *gpnorm = (1.0 - nrm)*(*fnorm);
4413     cnorm   = nrm;
4414     PetscCall(VecScale(y,cnorm));
4415     *ynorm  = *delta;
4416   } else {
4417     *gpnorm = 0.0;
4418     *ynorm  = nrm;
4419   }
4420   PetscFunctionReturn(0);
4421 }
4422 
4423 /*@C
4424    SNESConvergedReasonView - Displays the reason a SNES solve converged or diverged to a viewer
4425 
4426    Collective on SNES
4427 
4428    Parameter:
4429 +  snes - iterative context obtained from SNESCreate()
4430 -  viewer - the viewer to display the reason
4431 
4432    Options Database Keys:
4433 +  -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4434 -  -snes_converged_reason ::failed - only print reason and number of iterations when diverged
4435 
4436   Notes:
4437      To change the format of the output call PetscViewerPushFormat(viewer,format) before this call. Use PETSC_VIEWER_DEFAULT for the default,
4438      use PETSC_VIEWER_FAILED to only display a reason if it fails.
4439 
4440    Level: beginner
4441 
4442 .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonViewFromOptions()`,
4443           `PetscViewerPushFormat()`, `PetscViewerPopFormat()`
4444 
4445 @*/
4446 PetscErrorCode  SNESConvergedReasonView(SNES snes,PetscViewer viewer)
4447 {
4448   PetscViewerFormat format;
4449   PetscBool         isAscii;
4450 
4451   PetscFunctionBegin;
4452   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4453   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii));
4454   if (isAscii) {
4455     PetscCall(PetscViewerGetFormat(viewer, &format));
4456     PetscCall(PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel));
4457     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4458       DM              dm;
4459       Vec             u;
4460       PetscDS         prob;
4461       PetscInt        Nf, f;
4462       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4463       void            **exactCtx;
4464       PetscReal       error;
4465 
4466       PetscCall(SNESGetDM(snes, &dm));
4467       PetscCall(SNESGetSolution(snes, &u));
4468       PetscCall(DMGetDS(dm, &prob));
4469       PetscCall(PetscDSGetNumFields(prob, &Nf));
4470       PetscCall(PetscMalloc2(Nf, &exactSol, Nf, &exactCtx));
4471       for (f = 0; f < Nf; ++f) PetscCall(PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]));
4472       PetscCall(DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error));
4473       PetscCall(PetscFree2(exactSol, exactCtx));
4474       if (error < 1.0e-11) PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n"));
4475       else                 PetscCall(PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", (double)error));
4476     }
4477     if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4478       if (((PetscObject) snes)->prefix) {
4479         PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %" PetscInt_FMT "\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter));
4480       } else {
4481         PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %" PetscInt_FMT "\n",SNESConvergedReasons[snes->reason],snes->iter));
4482       }
4483     } else if (snes->reason <= 0) {
4484       if (((PetscObject) snes)->prefix) {
4485         PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %" PetscInt_FMT "\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter));
4486       } else {
4487         PetscCall(PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %" PetscInt_FMT "\n",SNESConvergedReasons[snes->reason],snes->iter));
4488       }
4489     }
4490     PetscCall(PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel));
4491   }
4492   PetscFunctionReturn(0);
4493 }
4494 
4495 /*@C
4496    SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4497     end of the nonlinear solver to display the conver reason of the nonlinear solver.
4498 
4499    Logically Collective on SNES
4500 
4501    Input Parameters:
4502 +  snes - the SNES context
4503 .  f - the snes converged reason view function
4504 .  vctx - [optional] user-defined context for private data for the
4505           snes converged reason view routine (use NULL if no context is desired)
4506 -  reasonviewdestroy - [optional] routine that frees reasonview context
4507           (may be NULL)
4508 
4509    Options Database Keys:
4510 +    -snes_converged_reason        - sets a default SNESConvergedReasonView()
4511 -    -snes_converged_reason_view_cancel - cancels all converged reason viewers that have
4512                             been hardwired into a code by
4513                             calls to SNESConvergedReasonViewSet(), but
4514                             does not cancel those set via
4515                             the options database.
4516 
4517    Notes:
4518    Several different converged reason view routines may be set by calling
4519    SNESConvergedReasonViewSet() multiple times; all will be called in the
4520    order in which they were set.
4521 
4522    Level: intermediate
4523 
4524 .seealso: `SNESConvergedReasonView()`, `SNESConvergedReasonViewCancel()`
4525 @*/
4526 PetscErrorCode  SNESConvergedReasonViewSet(SNES snes,PetscErrorCode (*f)(SNES,void*),void *vctx,PetscErrorCode (*reasonviewdestroy)(void**))
4527 {
4528   PetscInt       i;
4529   PetscBool      identical;
4530 
4531   PetscFunctionBegin;
4532   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4533   for (i=0; i<snes->numberreasonviews;i++) {
4534     PetscCall(PetscMonitorCompare((PetscErrorCode (*)(void))f,vctx,reasonviewdestroy,(PetscErrorCode (*)(void))snes->reasonview[i],snes->reasonviewcontext[i],snes->reasonviewdestroy[i],&identical));
4535     if (identical) PetscFunctionReturn(0);
4536   }
4537   PetscCheck(snes->numberreasonviews < MAXSNESREASONVIEWS,PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many SNES reasonview set");
4538   snes->reasonview[snes->numberreasonviews]          = f;
4539   snes->reasonviewdestroy[snes->numberreasonviews]   = reasonviewdestroy;
4540   snes->reasonviewcontext[snes->numberreasonviews++] = (void*)vctx;
4541   PetscFunctionReturn(0);
4542 }
4543 
4544 /*@
4545   SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed.
4546                                        All the user-provided convergedReasonView routines will be involved as well, if they exist.
4547 
4548   Collective on SNES
4549 
4550   Input Parameters:
4551 . snes   - the SNES object
4552 
4553   Level: intermediate
4554 
4555 .seealso: `SNESCreate()`, `SNESSetUp()`, `SNESDestroy()`, `SNESSetTolerances()`, `SNESConvergedDefault()`, `SNESGetConvergedReason()`, `SNESConvergedReasonView()`
4556 
4557 @*/
4558 PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4559 {
4560   PetscViewer       viewer;
4561   PetscBool         flg;
4562   static PetscBool  incall = PETSC_FALSE;
4563   PetscViewerFormat format;
4564   PetscInt          i;
4565 
4566   PetscFunctionBegin;
4567   if (incall) PetscFunctionReturn(0);
4568   incall = PETSC_TRUE;
4569 
4570   /* All user-provided viewers are called first, if they exist. */
4571   for (i=0; i<snes->numberreasonviews; i++) {
4572     PetscCall((*snes->reasonview[i])(snes,snes->reasonviewcontext[i]));
4573   }
4574 
4575   /* Call PETSc default routine if users ask for it */
4576   PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg));
4577   if (flg) {
4578     PetscCall(PetscViewerPushFormat(viewer,format));
4579     PetscCall(SNESConvergedReasonView(snes,viewer));
4580     PetscCall(PetscViewerPopFormat(viewer));
4581     PetscCall(PetscViewerDestroy(&viewer));
4582   }
4583   incall = PETSC_FALSE;
4584   PetscFunctionReturn(0);
4585 }
4586 
4587 /*@
4588    SNESSolve - Solves a nonlinear system F(x) = b.
4589    Call SNESSolve() after calling SNESCreate() and optional routines of the form SNESSetXXX().
4590 
4591    Collective on SNES
4592 
4593    Input Parameters:
4594 +  snes - the SNES context
4595 .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4596 -  x - the solution vector.
4597 
4598    Notes:
4599    The user should initialize the vector,x, with the initial guess
4600    for the nonlinear solve prior to calling SNESSolve().  In particular,
4601    to employ an initial guess of zero, the user should explicitly set
4602    this vector to zero by calling VecSet().
4603 
4604    Level: beginner
4605 
4606 .seealso: `SNESCreate()`, `SNESDestroy()`, `SNESSetFunction()`, `SNESSetJacobian()`, `SNESSetGridSequence()`, `SNESGetSolution()`,
4607           `SNESNewtonTRSetPreCheck()`, `SNESNewtonTRGetPreCheck()`, `SNESNewtonTRSetPostCheck()`, `SNESNewtonTRGetPostCheck()`,
4608           `SNESLineSearchSetPostCheck()`, `SNESLineSearchGetPostCheck()`, `SNESLineSearchSetPreCheck()`, `SNESLineSearchGetPreCheck()`
4609 @*/
4610 PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4611 {
4612   PetscBool         flg;
4613   PetscInt          grid;
4614   Vec               xcreated = NULL;
4615   DM                dm;
4616 
4617   PetscFunctionBegin;
4618   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4619   if (x) PetscValidHeaderSpecific(x,VEC_CLASSID,3);
4620   if (x) PetscCheckSameComm(snes,1,x,3);
4621   if (b) PetscValidHeaderSpecific(b,VEC_CLASSID,2);
4622   if (b) PetscCheckSameComm(snes,1,b,2);
4623 
4624   /* High level operations using the nonlinear solver */
4625   {
4626     PetscViewer       viewer;
4627     PetscViewerFormat format;
4628     PetscInt          num;
4629     PetscBool         flg;
4630     static PetscBool  incall = PETSC_FALSE;
4631 
4632     if (!incall) {
4633       /* Estimate the convergence rate of the discretization */
4634       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg));
4635       if (flg) {
4636         PetscConvEst conv;
4637         DM           dm;
4638         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4639         PetscInt     Nf;
4640 
4641         incall = PETSC_TRUE;
4642         PetscCall(SNESGetDM(snes, &dm));
4643         PetscCall(DMGetNumFields(dm, &Nf));
4644         PetscCall(PetscCalloc1(Nf, &alpha));
4645         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv));
4646         PetscCall(PetscConvEstSetSolver(conv, (PetscObject) snes));
4647         PetscCall(PetscConvEstSetFromOptions(conv));
4648         PetscCall(PetscConvEstSetUp(conv));
4649         PetscCall(PetscConvEstGetConvRate(conv, alpha));
4650         PetscCall(PetscViewerPushFormat(viewer, format));
4651         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
4652         PetscCall(PetscViewerPopFormat(viewer));
4653         PetscCall(PetscViewerDestroy(&viewer));
4654         PetscCall(PetscConvEstDestroy(&conv));
4655         PetscCall(PetscFree(alpha));
4656         incall = PETSC_FALSE;
4657       }
4658       /* Adaptively refine the initial grid */
4659       num  = 1;
4660       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg));
4661       if (flg) {
4662         DMAdaptor adaptor;
4663 
4664         incall = PETSC_TRUE;
4665         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4666         PetscCall(DMAdaptorSetSolver(adaptor, snes));
4667         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4668         PetscCall(DMAdaptorSetFromOptions(adaptor));
4669         PetscCall(DMAdaptorSetUp(adaptor));
4670         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x));
4671         PetscCall(DMAdaptorDestroy(&adaptor));
4672         incall = PETSC_FALSE;
4673       }
4674       /* Use grid sequencing to adapt */
4675       num  = 0;
4676       PetscCall(PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL));
4677       if (num) {
4678         DMAdaptor adaptor;
4679 
4680         incall = PETSC_TRUE;
4681         PetscCall(DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor));
4682         PetscCall(DMAdaptorSetSolver(adaptor, snes));
4683         PetscCall(DMAdaptorSetSequenceLength(adaptor, num));
4684         PetscCall(DMAdaptorSetFromOptions(adaptor));
4685         PetscCall(DMAdaptorSetUp(adaptor));
4686         PetscCall(DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x));
4687         PetscCall(DMAdaptorDestroy(&adaptor));
4688         incall = PETSC_FALSE;
4689       }
4690     }
4691   }
4692   if (!x) { x = snes->vec_sol; }
4693   if (!x) {
4694     PetscCall(SNESGetDM(snes,&dm));
4695     PetscCall(DMCreateGlobalVector(dm,&xcreated));
4696     x    = xcreated;
4697   }
4698   PetscCall(SNESViewFromOptions(snes,NULL,"-snes_view_pre"));
4699 
4700   for (grid=0; grid<snes->gridsequence; grid++) PetscCall(PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4701   for (grid=0; grid<snes->gridsequence+1; grid++) {
4702 
4703     /* set solution vector */
4704     if (!grid) PetscCall(PetscObjectReference((PetscObject)x));
4705     PetscCall(VecDestroy(&snes->vec_sol));
4706     snes->vec_sol = x;
4707     PetscCall(SNESGetDM(snes,&dm));
4708 
4709     /* set affine vector if provided */
4710     if (b) PetscCall(PetscObjectReference((PetscObject)b));
4711     PetscCall(VecDestroy(&snes->vec_rhs));
4712     snes->vec_rhs = b;
4713 
4714     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");
4715     PetscCheck(snes->vec_func != snes->vec_sol,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4716     PetscCheck(snes->vec_rhs  != snes->vec_sol,PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4717     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4718       PetscCall(VecDuplicate(snes->vec_sol,&snes->vec_sol_update));
4719       PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update));
4720     }
4721     PetscCall(DMShellSetGlobalVector(dm,snes->vec_sol));
4722     PetscCall(SNESSetUp(snes));
4723 
4724     if (!grid) {
4725       if (snes->ops->computeinitialguess) PetscCallBack("SNES callback initial guess",(*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP));
4726     }
4727 
4728     if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4729     if (snes->counters_reset) {snes->nfuncs = 0; snes->linear_its = 0; snes->numFailures = 0;}
4730 
4731     PetscCall(PetscLogEventBegin(SNES_Solve,snes,0,0,0));
4732     PetscCall((*snes->ops->solve)(snes));
4733     PetscCall(PetscLogEventEnd(SNES_Solve,snes,0,0,0));
4734     PetscCheck(snes->reason,PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
4735     snes->domainerror = PETSC_FALSE; /* clear the flag if it has been set */
4736 
4737     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4738     if (snes->lagpre_persist) snes->pre_iter += snes->iter;
4739 
4740     PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg));
4741     if (flg && !PetscPreLoadingOn) PetscCall(SNESTestLocalMin(snes));
4742     /* Call converged reason views. This may involve user-provided viewers as well */
4743     PetscCall(SNESConvergedReasonViewFromOptions(snes));
4744 
4745     if (snes->errorifnotconverged) PetscCheck(snes->reason >= 0,PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4746     if (snes->reason < 0) break;
4747     if (grid < snes->gridsequence) {
4748       DM  fine;
4749       Vec xnew;
4750       Mat interp;
4751 
4752       PetscCall(DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine));
4753       PetscCheck(fine,PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4754       PetscCall(DMCreateInterpolation(snes->dm,fine,&interp,NULL));
4755       PetscCall(DMCreateGlobalVector(fine,&xnew));
4756       PetscCall(MatInterpolate(interp,x,xnew));
4757       PetscCall(DMInterpolate(snes->dm,interp,fine));
4758       PetscCall(MatDestroy(&interp));
4759       x    = xnew;
4760 
4761       PetscCall(SNESReset(snes));
4762       PetscCall(SNESSetDM(snes,fine));
4763       PetscCall(SNESResetFromOptions(snes));
4764       PetscCall(DMDestroy(&fine));
4765       PetscCall(PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes))));
4766     }
4767   }
4768   PetscCall(SNESViewFromOptions(snes,NULL,"-snes_view"));
4769   PetscCall(VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution"));
4770   PetscCall(DMMonitor(snes->dm));
4771   PetscCall(SNESMonitorPauseFinal_Internal(snes));
4772 
4773   PetscCall(VecDestroy(&xcreated));
4774   PetscCall(PetscObjectSAWsBlock((PetscObject)snes));
4775   PetscFunctionReturn(0);
4776 }
4777 
4778 /* --------- Internal routines for SNES Package --------- */
4779 
4780 /*@C
4781    SNESSetType - Sets the method for the nonlinear solver.
4782 
4783    Collective on SNES
4784 
4785    Input Parameters:
4786 +  snes - the SNES context
4787 -  type - a known method
4788 
4789    Options Database Key:
4790 .  -snes_type <type> - Sets the method; use -help for a list
4791    of available methods (for instance, newtonls or newtontr)
4792 
4793    Notes:
4794    See "petsc/include/petscsnes.h" for available methods (for instance)
4795 +    SNESNEWTONLS - Newton's method with line search
4796      (systems of nonlinear equations)
4797 -    SNESNEWTONTR - Newton's method with trust region
4798      (systems of nonlinear equations)
4799 
4800   Normally, it is best to use the SNESSetFromOptions() command and then
4801   set the SNES solver type from the options database rather than by using
4802   this routine.  Using the options database provides the user with
4803   maximum flexibility in evaluating the many nonlinear solvers.
4804   The SNESSetType() routine is provided for those situations where it
4805   is necessary to set the nonlinear solver independently of the command
4806   line or options database.  This might be the case, for example, when
4807   the choice of solver changes during the execution of the program,
4808   and the user's application is taking responsibility for choosing the
4809   appropriate method.
4810 
4811     Developer Notes:
4812     SNESRegister() adds a constructor for a new SNESType to SNESList, SNESSetType() locates
4813     the constructor in that list and calls it to create the spexific object.
4814 
4815   Level: intermediate
4816 
4817 .seealso: `SNESType`, `SNESCreate()`, `SNESDestroy()`, `SNESGetType()`, `SNESSetFromOptions()`
4818 
4819 @*/
4820 PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4821 {
4822   PetscBool      match;
4823   PetscErrorCode (*r)(SNES);
4824 
4825   PetscFunctionBegin;
4826   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4827   PetscValidCharPointer(type,2);
4828 
4829   PetscCall(PetscObjectTypeCompare((PetscObject)snes,type,&match));
4830   if (match) PetscFunctionReturn(0);
4831 
4832   PetscCall(PetscFunctionListFind(SNESList,type,&r));
4833   PetscCheck(r,PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4834   /* Destroy the previous private SNES context */
4835   if (snes->ops->destroy) PetscCall((*snes->ops->destroy)(snes));
4836   /* Reinitialize function pointers in SNESOps structure */
4837   snes->ops->setup          = NULL;
4838   snes->ops->solve          = NULL;
4839   snes->ops->view           = NULL;
4840   snes->ops->setfromoptions = NULL;
4841   snes->ops->destroy        = NULL;
4842 
4843   /* It may happen the user has customized the line search before calling SNESSetType */
4844   if (((PetscObject)snes)->type_name) PetscCall(SNESLineSearchDestroy(&snes->linesearch));
4845 
4846   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4847   snes->setupcalled = PETSC_FALSE;
4848 
4849   PetscCall(PetscObjectChangeTypeName((PetscObject)snes,type));
4850   PetscCall((*r)(snes));
4851   PetscFunctionReturn(0);
4852 }
4853 
4854 /*@C
4855    SNESGetType - Gets the SNES method type and name (as a string).
4856 
4857    Not Collective
4858 
4859    Input Parameter:
4860 .  snes - nonlinear solver context
4861 
4862    Output Parameter:
4863 .  type - SNES method (a character string)
4864 
4865    Level: intermediate
4866 
4867 @*/
4868 PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4869 {
4870   PetscFunctionBegin;
4871   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4872   PetscValidPointer(type,2);
4873   *type = ((PetscObject)snes)->type_name;
4874   PetscFunctionReturn(0);
4875 }
4876 
4877 /*@
4878   SNESSetSolution - Sets the solution vector for use by the SNES routines.
4879 
4880   Logically Collective on SNES
4881 
4882   Input Parameters:
4883 + snes - the SNES context obtained from SNESCreate()
4884 - u    - the solution vector
4885 
4886   Level: beginner
4887 
4888 @*/
4889 PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4890 {
4891   DM             dm;
4892 
4893   PetscFunctionBegin;
4894   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
4895   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
4896   PetscCall(PetscObjectReference((PetscObject) u));
4897   PetscCall(VecDestroy(&snes->vec_sol));
4898 
4899   snes->vec_sol = u;
4900 
4901   PetscCall(SNESGetDM(snes, &dm));
4902   PetscCall(DMShellSetGlobalVector(dm, u));
4903   PetscFunctionReturn(0);
4904 }
4905 
4906 /*@
4907    SNESGetSolution - Returns the vector where the approximate solution is
4908    stored. This is the fine grid solution when using SNESSetGridSequence().
4909 
4910    Not Collective, but Vec is parallel if SNES is parallel
4911 
4912    Input Parameter:
4913 .  snes - the SNES context
4914 
4915    Output Parameter:
4916 .  x - the solution
4917 
4918    Level: intermediate
4919 
4920 .seealso: `SNESGetSolutionUpdate()`, `SNESGetFunction()`
4921 @*/
4922 PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4923 {
4924   PetscFunctionBegin;
4925   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4926   PetscValidPointer(x,2);
4927   *x = snes->vec_sol;
4928   PetscFunctionReturn(0);
4929 }
4930 
4931 /*@
4932    SNESGetSolutionUpdate - Returns the vector where the solution update is
4933    stored.
4934 
4935    Not Collective, but Vec is parallel if SNES is parallel
4936 
4937    Input Parameter:
4938 .  snes - the SNES context
4939 
4940    Output Parameter:
4941 .  x - the solution update
4942 
4943    Level: advanced
4944 
4945 .seealso: `SNESGetSolution()`, `SNESGetFunction()`
4946 @*/
4947 PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4948 {
4949   PetscFunctionBegin;
4950   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4951   PetscValidPointer(x,2);
4952   *x = snes->vec_sol_update;
4953   PetscFunctionReturn(0);
4954 }
4955 
4956 /*@C
4957    SNESGetFunction - Returns the vector where the function is stored.
4958 
4959    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.
4960 
4961    Input Parameter:
4962 .  snes - the SNES context
4963 
4964    Output Parameters:
4965 +  r - the vector that is used to store residuals (or NULL if you don't want it)
4966 .  f - the function (or NULL if you don't want it); see SNESFunction for calling sequence details
4967 -  ctx - the function context (or NULL if you don't want it)
4968 
4969    Level: advanced
4970 
4971     Notes: The vector r DOES NOT, in general contain the current value of the SNES nonlinear function
4972 
4973 .seealso: `SNESSetFunction()`, `SNESGetSolution()`, `SNESFunction`
4974 @*/
4975 PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4976 {
4977   DM             dm;
4978 
4979   PetscFunctionBegin;
4980   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4981   if (r) {
4982     if (!snes->vec_func) {
4983       if (snes->vec_rhs) {
4984         PetscCall(VecDuplicate(snes->vec_rhs,&snes->vec_func));
4985       } else if (snes->vec_sol) {
4986         PetscCall(VecDuplicate(snes->vec_sol,&snes->vec_func));
4987       } else if (snes->dm) {
4988         PetscCall(DMCreateGlobalVector(snes->dm,&snes->vec_func));
4989       }
4990     }
4991     *r = snes->vec_func;
4992   }
4993   PetscCall(SNESGetDM(snes,&dm));
4994   PetscCall(DMSNESGetFunction(dm,f,ctx));
4995   PetscFunctionReturn(0);
4996 }
4997 
4998 /*@C
4999    SNESGetNGS - Returns the NGS function and context.
5000 
5001    Input Parameter:
5002 .  snes - the SNES context
5003 
5004    Output Parameters:
5005 +  f - the function (or NULL) see SNESNGSFunction for details
5006 -  ctx    - the function context (or NULL)
5007 
5008    Level: advanced
5009 
5010 .seealso: `SNESSetNGS()`, `SNESGetFunction()`
5011 @*/
5012 
5013 PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
5014 {
5015   DM             dm;
5016 
5017   PetscFunctionBegin;
5018   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5019   PetscCall(SNESGetDM(snes,&dm));
5020   PetscCall(DMSNESGetNGS(dm,f,ctx));
5021   PetscFunctionReturn(0);
5022 }
5023 
5024 /*@C
5025    SNESSetOptionsPrefix - Sets the prefix used for searching for all
5026    SNES options in the database.
5027 
5028    Logically Collective on SNES
5029 
5030    Input Parameters:
5031 +  snes - the SNES context
5032 -  prefix - the prefix to prepend to all option names
5033 
5034    Notes:
5035    A hyphen (-) must NOT be given at the beginning of the prefix name.
5036    The first character of all runtime options is AUTOMATICALLY the hyphen.
5037 
5038    Level: advanced
5039 
5040 .seealso: `SNESSetFromOptions()`
5041 @*/
5042 PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
5043 {
5044   PetscFunctionBegin;
5045   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5046   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes,prefix));
5047   if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp));
5048   if (snes->linesearch) {
5049     PetscCall(SNESGetLineSearch(snes,&snes->linesearch));
5050     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix));
5051   }
5052   PetscCall(KSPSetOptionsPrefix(snes->ksp,prefix));
5053   PetscFunctionReturn(0);
5054 }
5055 
5056 /*@C
5057    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5058    SNES options in the database.
5059 
5060    Logically Collective on SNES
5061 
5062    Input Parameters:
5063 +  snes - the SNES context
5064 -  prefix - the prefix to prepend to all option names
5065 
5066    Notes:
5067    A hyphen (-) must NOT be given at the beginning of the prefix name.
5068    The first character of all runtime options is AUTOMATICALLY the hyphen.
5069 
5070    Level: advanced
5071 
5072 .seealso: `SNESGetOptionsPrefix()`
5073 @*/
5074 PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
5075 {
5076   PetscFunctionBegin;
5077   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5078   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix));
5079   if (!snes->ksp) PetscCall(SNESGetKSP(snes,&snes->ksp));
5080   if (snes->linesearch) {
5081     PetscCall(SNESGetLineSearch(snes,&snes->linesearch));
5082     PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix));
5083   }
5084   PetscCall(KSPAppendOptionsPrefix(snes->ksp,prefix));
5085   PetscFunctionReturn(0);
5086 }
5087 
5088 /*@C
5089    SNESGetOptionsPrefix - Sets the prefix used for searching for all
5090    SNES options in the database.
5091 
5092    Not Collective
5093 
5094    Input Parameter:
5095 .  snes - the SNES context
5096 
5097    Output Parameter:
5098 .  prefix - pointer to the prefix string used
5099 
5100    Notes:
5101     On the fortran side, the user should pass in a string 'prefix' of
5102    sufficient length to hold the prefix.
5103 
5104    Level: advanced
5105 
5106 .seealso: `SNESAppendOptionsPrefix()`
5107 @*/
5108 PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
5109 {
5110   PetscFunctionBegin;
5111   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5112   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)snes,prefix));
5113   PetscFunctionReturn(0);
5114 }
5115 
5116 /*@C
5117   SNESRegister - Adds a method to the nonlinear solver package.
5118 
5119    Not collective
5120 
5121    Input Parameters:
5122 +  name_solver - name of a new user-defined solver
5123 -  routine_create - routine to create method context
5124 
5125    Notes:
5126    SNESRegister() may be called multiple times to add several user-defined solvers.
5127 
5128    Sample usage:
5129 .vb
5130    SNESRegister("my_solver",MySolverCreate);
5131 .ve
5132 
5133    Then, your solver can be chosen with the procedural interface via
5134 $     SNESSetType(snes,"my_solver")
5135    or at runtime via the option
5136 $     -snes_type my_solver
5137 
5138    Level: advanced
5139 
5140     Note: If your function is not being put into a shared library then use SNESRegister() instead
5141 
5142 .seealso: `SNESRegisterAll()`, `SNESRegisterDestroy()`
5143 
5144   Level: advanced
5145 @*/
5146 PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
5147 {
5148   PetscFunctionBegin;
5149   PetscCall(SNESInitializePackage());
5150   PetscCall(PetscFunctionListAdd(&SNESList,sname,function));
5151   PetscFunctionReturn(0);
5152 }
5153 
5154 PetscErrorCode  SNESTestLocalMin(SNES snes)
5155 {
5156   PetscInt       N,i,j;
5157   Vec            u,uh,fh;
5158   PetscScalar    value;
5159   PetscReal      norm;
5160 
5161   PetscFunctionBegin;
5162   PetscCall(SNESGetSolution(snes,&u));
5163   PetscCall(VecDuplicate(u,&uh));
5164   PetscCall(VecDuplicate(u,&fh));
5165 
5166   /* currently only works for sequential */
5167   PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes),"Testing FormFunction() for local min\n"));
5168   PetscCall(VecGetSize(u,&N));
5169   for (i=0; i<N; i++) {
5170     PetscCall(VecCopy(u,uh));
5171     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes),"i = %" PetscInt_FMT "\n",i));
5172     for (j=-10; j<11; j++) {
5173       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
5174       PetscCall(VecSetValue(uh,i,value,ADD_VALUES));
5175       PetscCall(SNESComputeFunction(snes,uh,fh));
5176       PetscCall(VecNorm(fh,NORM_2,&norm));
5177       PetscCall(PetscPrintf(PetscObjectComm((PetscObject)snes),"       j norm %" PetscInt_FMT " %18.16e\n",j,(double)norm));
5178       value = -value;
5179       PetscCall(VecSetValue(uh,i,value,ADD_VALUES));
5180     }
5181   }
5182   PetscCall(VecDestroy(&uh));
5183   PetscCall(VecDestroy(&fh));
5184   PetscFunctionReturn(0);
5185 }
5186 
5187 /*@
5188    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
5189    computing relative tolerance for linear solvers within an inexact
5190    Newton method.
5191 
5192    Logically Collective on SNES
5193 
5194    Input Parameters:
5195 +  snes - SNES context
5196 -  flag - PETSC_TRUE or PETSC_FALSE
5197 
5198     Options Database:
5199 +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
5200 .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
5201 .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
5202 .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
5203 .  -snes_ksp_ew_gamma <gamma> - Sets gamma
5204 .  -snes_ksp_ew_alpha <alpha> - Sets alpha
5205 .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
5206 -  -snes_ksp_ew_threshold <threshold> - Sets threshold
5207 
5208    Notes:
5209    Currently, the default is to use a constant relative tolerance for
5210    the inner linear solvers.  Alternatively, one can use the
5211    Eisenstat-Walker method, where the relative convergence tolerance
5212    is reset at each Newton iteration according progress of the nonlinear
5213    solver.
5214 
5215    Level: advanced
5216 
5217    Reference:
5218    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
5219    inexact Newton method", SISC 17 (1), pp.16-32, 1996.
5220 
5221 .seealso: `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5222 @*/
5223 PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
5224 {
5225   PetscFunctionBegin;
5226   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5227   PetscValidLogicalCollectiveBool(snes,flag,2);
5228   snes->ksp_ewconv = flag;
5229   PetscFunctionReturn(0);
5230 }
5231 
5232 /*@
5233    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
5234    for computing relative tolerance for linear solvers within an
5235    inexact Newton method.
5236 
5237    Not Collective
5238 
5239    Input Parameter:
5240 .  snes - SNES context
5241 
5242    Output Parameter:
5243 .  flag - PETSC_TRUE or PETSC_FALSE
5244 
5245    Notes:
5246    Currently, the default is to use a constant relative tolerance for
5247    the inner linear solvers.  Alternatively, one can use the
5248    Eisenstat-Walker method, where the relative convergence tolerance
5249    is reset at each Newton iteration according progress of the nonlinear
5250    solver.
5251 
5252    Level: advanced
5253 
5254    Reference:
5255    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
5256    inexact Newton method", SISC 17 (1), pp.16-32, 1996.
5257 
5258 .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetParametersEW()`, `SNESKSPSetParametersEW()`
5259 @*/
5260 PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
5261 {
5262   PetscFunctionBegin;
5263   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5264   PetscValidBoolPointer(flag,2);
5265   *flag = snes->ksp_ewconv;
5266   PetscFunctionReturn(0);
5267 }
5268 
5269 /*@
5270    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5271    convergence criteria for the linear solvers within an inexact
5272    Newton method.
5273 
5274    Logically Collective on SNES
5275 
5276    Input Parameters:
5277 +    snes - SNES context
5278 .    version - version 1, 2 (default is 2), 3 or 4
5279 .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5280 .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5281 .    gamma - multiplicative factor for version 2 rtol computation
5282              (0 <= gamma2 <= 1)
5283 .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5284 .    alpha2 - power for safeguard
5285 -    threshold - threshold for imposing safeguard (0 < threshold < 1)
5286 
5287    Note:
5288    Version 3 was contributed by Luis Chacon, June 2006.
5289 
5290    Use PETSC_DEFAULT to retain the default for any of the parameters.
5291 
5292    Level: advanced
5293 
5294    Reference:
5295    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
5296    inexact Newton method", Utah State University Math. Stat. Dept. Res.
5297    Report 6/94/75, June, 1994, to appear in SIAM J. Sci. Comput.
5298 
5299 .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPGetParametersEW()`
5300 @*/
5301 PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
5302 {
5303   SNESKSPEW *kctx;
5304 
5305   PetscFunctionBegin;
5306   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5307   kctx = (SNESKSPEW*)snes->kspconvctx;
5308   PetscCheck(kctx,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5309   PetscValidLogicalCollectiveInt(snes,version,2);
5310   PetscValidLogicalCollectiveReal(snes,rtol_0,3);
5311   PetscValidLogicalCollectiveReal(snes,rtol_max,4);
5312   PetscValidLogicalCollectiveReal(snes,gamma,5);
5313   PetscValidLogicalCollectiveReal(snes,alpha,6);
5314   PetscValidLogicalCollectiveReal(snes,alpha2,7);
5315   PetscValidLogicalCollectiveReal(snes,threshold,8);
5316 
5317   if (version != PETSC_DEFAULT)   kctx->version   = version;
5318   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
5319   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
5320   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
5321   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
5322   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
5323   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;
5324 
5325   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);
5326   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);
5327   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);
5328   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);
5329   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);
5330   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);
5331   PetscFunctionReturn(0);
5332 }
5333 
5334 /*@
5335    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5336    convergence criteria for the linear solvers within an inexact
5337    Newton method.
5338 
5339    Not Collective
5340 
5341    Input Parameter:
5342 .    snes - SNES context
5343 
5344    Output Parameters:
5345 +    version - version 1, 2 (default is 2), 3 or 4
5346 .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5347 .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5348 .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5349 .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5350 .    alpha2 - power for safeguard
5351 -    threshold - threshold for imposing safeguard (0 < threshold < 1)
5352 
5353    Level: advanced
5354 
5355 .seealso: `SNESKSPSetUseEW()`, `SNESKSPGetUseEW()`, `SNESKSPSetParametersEW()`
5356 @*/
5357 PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
5358 {
5359   SNESKSPEW *kctx;
5360 
5361   PetscFunctionBegin;
5362   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5363   kctx = (SNESKSPEW*)snes->kspconvctx;
5364   PetscCheck(kctx,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5365   if (version)   *version   = kctx->version;
5366   if (rtol_0)    *rtol_0    = kctx->rtol_0;
5367   if (rtol_max)  *rtol_max  = kctx->rtol_max;
5368   if (gamma)     *gamma     = kctx->gamma;
5369   if (alpha)     *alpha     = kctx->alpha;
5370   if (alpha2)    *alpha2    = kctx->alpha2;
5371   if (threshold) *threshold = kctx->threshold;
5372   PetscFunctionReturn(0);
5373 }
5374 
5375 PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5376 {
5377   SNESKSPEW *kctx = (SNESKSPEW*)snes->kspconvctx;
5378   PetscReal rtol  = PETSC_DEFAULT,stol;
5379 
5380   PetscFunctionBegin;
5381   if (!snes->ksp_ewconv) PetscFunctionReturn(0);
5382   if (!snes->iter) {
5383     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5384     PetscCall(VecNorm(snes->vec_func,NORM_2,&kctx->norm_first));
5385   } else {
5386     if (kctx->version == 1) {
5387       rtol = PetscAbsReal(snes->norm - kctx->lresid_last)/kctx->norm_last;
5388       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5389       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5390     } else if (kctx->version == 2) {
5391       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5392       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5393       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5394     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5395       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5396       /* safeguard: avoid sharp decrease of rtol */
5397       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5398       stol = PetscMax(rtol,stol);
5399       rtol = PetscMin(kctx->rtol_0,stol);
5400       /* safeguard: avoid oversolving */
5401       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5402       stol = PetscMax(rtol,stol);
5403       rtol = PetscMin(kctx->rtol_0,stol);
5404     } else if (kctx->version == 4) { /* H.-B. An et al. Journal of Computational and Applied Mathematics 200 (2007) 47-60 */
5405       PetscReal ared = PetscAbsReal(kctx->norm_last - snes->norm);
5406       PetscReal pred = PetscAbsReal(kctx->norm_last - kctx->lresid_last);
5407       PetscReal rk = ared / pred;
5408       if (rk < kctx->v4_p1) rtol = 1. - 2.*kctx->v4_p1;
5409       else if (rk < kctx->v4_p2) rtol = kctx->rtol_last;
5410       else if (rk < kctx->v4_p3) rtol = kctx->v4_m1 * kctx->rtol_last;
5411       else rtol = kctx->v4_m2 * kctx->rtol_last;
5412 
5413       if (kctx->rtol_last_2 > kctx->v4_m3 && kctx->rtol_last > kctx->v4_m3 &&
5414           kctx->rk_last_2 < kctx->v4_p1 && kctx->rk_last < kctx->v4_p1) {
5415         rtol = kctx->v4_m4 * kctx->rtol_last;
5416         //printf("iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g (rk %g ps %g %g %g) (AD)\n",snes->iter,kctx->version,(double)rtol,rk,kctx->v4_p1,kctx->v4_p2,kctx->v4_p3);
5417       } else {
5418         //printf("iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g (rk %g ps %g %g %g)\n",snes->iter,kctx->version,(double)rtol,rk,kctx->v4_p1,kctx->v4_p2,kctx->v4_p3);
5419       }
5420       kctx->rtol_last_2 = kctx->rtol_last;
5421       kctx->rk_last_2 = kctx->rk_last;
5422       kctx->rk_last = rk;
5423     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1-4 are supported: %" PetscInt_FMT,kctx->version);
5424   }
5425   /* safeguard: avoid rtol greater than rtol_max */
5426   rtol = PetscMin(rtol,kctx->rtol_max);
5427   PetscCall(KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT));
5428   PetscCall(PetscInfo(snes,"iter %" PetscInt_FMT ", Eisenstat-Walker (version %" PetscInt_FMT ") KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol));
5429   PetscFunctionReturn(0);
5430 }
5431 
5432 PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5433 {
5434   SNESKSPEW *kctx = (SNESKSPEW*)snes->kspconvctx;
5435   PCSide    pcside;
5436   Vec       lres;
5437 
5438   PetscFunctionBegin;
5439   if (!snes->ksp_ewconv) PetscFunctionReturn(0);
5440   PetscCall(KSPGetTolerances(ksp,&kctx->rtol_last,NULL,NULL,NULL));
5441   kctx->norm_last = snes->norm;
5442   if (kctx->version == 1 || kctx->version == 4) {
5443     PC        pc;
5444     PetscBool getRes;
5445 
5446     PetscCall(KSPGetPC(ksp,&pc));
5447     PetscCall(PetscObjectTypeCompare((PetscObject)pc,PCNONE,&getRes));
5448     if (!getRes) {
5449       KSPNormType normtype;
5450 
5451       PetscCall(KSPGetNormType(ksp,&normtype));
5452       getRes = (PetscBool)(normtype == KSP_NORM_UNPRECONDITIONED);
5453     }
5454     PetscCall(KSPGetPCSide(ksp,&pcside));
5455     if (pcside == PC_RIGHT || getRes) { /* KSP residual is true linear residual */
5456       PetscCall(KSPGetResidualNorm(ksp,&kctx->lresid_last));
5457     } else {
5458       /* KSP residual is preconditioned residual */
5459       /* compute true linear residual norm */
5460       Mat J;
5461       PetscCall(KSPGetOperators(ksp,&J,NULL));
5462       PetscCall(VecDuplicate(b,&lres));
5463       PetscCall(MatMult(J,x,lres));
5464       PetscCall(VecAYPX(lres,-1.0,b));
5465       PetscCall(VecNorm(lres,NORM_2,&kctx->lresid_last));
5466       PetscCall(VecDestroy(&lres));
5467     }
5468   }
5469   PetscFunctionReturn(0);
5470 }
5471 
5472 /*@
5473    SNESGetKSP - Returns the KSP context for a SNES solver.
5474 
5475    Not Collective, but if SNES object is parallel, then KSP object is parallel
5476 
5477    Input Parameter:
5478 .  snes - the SNES context
5479 
5480    Output Parameter:
5481 .  ksp - the KSP context
5482 
5483    Notes:
5484    The user can then directly manipulate the KSP context to set various
5485    options, etc.  Likewise, the user can then extract and manipulate the
5486    PC contexts as well.
5487 
5488    Level: beginner
5489 
5490 .seealso: `KSPGetPC()`, `SNESCreate()`, `KSPCreate()`, `SNESSetKSP()`
5491 @*/
5492 PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
5493 {
5494   PetscFunctionBegin;
5495   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5496   PetscValidPointer(ksp,2);
5497 
5498   if (!snes->ksp) {
5499     PetscCall(KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp));
5500     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1));
5501     PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp));
5502 
5503     PetscCall(KSPSetPreSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPreSolve_SNESEW,snes));
5504     PetscCall(KSPSetPostSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPostSolve_SNESEW,snes));
5505 
5506     PetscCall(KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes));
5507     PetscCall(PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options));
5508   }
5509   *ksp = snes->ksp;
5510   PetscFunctionReturn(0);
5511 }
5512 
5513 #include <petsc/private/dmimpl.h>
5514 /*@
5515    SNESSetDM - Sets the DM that may be used by some nonlinear solvers or their underlying preconditioners
5516 
5517    Logically Collective on SNES
5518 
5519    Input Parameters:
5520 +  snes - the nonlinear solver context
5521 -  dm - the dm, cannot be NULL
5522 
5523    Notes:
5524    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
5525    even when not using interfaces like DMSNESSetFunction().  Use DMClone() to get a distinct DM when solving different
5526    problems using the same function space.
5527 
5528    Level: intermediate
5529 
5530 .seealso: `SNESGetDM()`, `KSPSetDM()`, `KSPGetDM()`
5531 @*/
5532 PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5533 {
5534   KSP            ksp;
5535   DMSNES         sdm;
5536 
5537   PetscFunctionBegin;
5538   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5539   PetscValidHeaderSpecific(dm,DM_CLASSID,2);
5540   PetscCall(PetscObjectReference((PetscObject)dm));
5541   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5542     if (snes->dm->dmsnes && !dm->dmsnes) {
5543       PetscCall(DMCopyDMSNES(snes->dm,dm));
5544       PetscCall(DMGetDMSNES(snes->dm,&sdm));
5545       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5546     }
5547     PetscCall(DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes));
5548     PetscCall(DMDestroy(&snes->dm));
5549   }
5550   snes->dm     = dm;
5551   snes->dmAuto = PETSC_FALSE;
5552 
5553   PetscCall(SNESGetKSP(snes,&ksp));
5554   PetscCall(KSPSetDM(ksp,dm));
5555   PetscCall(KSPSetDMActive(ksp,PETSC_FALSE));
5556   if (snes->npc) {
5557     PetscCall(SNESSetDM(snes->npc,snes->dm));
5558     PetscCall(SNESSetNPCSide(snes,snes->npcside));
5559   }
5560   PetscFunctionReturn(0);
5561 }
5562 
5563 /*@
5564    SNESGetDM - Gets the DM that may be used by some preconditioners
5565 
5566    Not Collective but DM obtained is parallel on SNES
5567 
5568    Input Parameter:
5569 . snes - the preconditioner context
5570 
5571    Output Parameter:
5572 .  dm - the dm
5573 
5574    Level: intermediate
5575 
5576 .seealso: `SNESSetDM()`, `KSPSetDM()`, `KSPGetDM()`
5577 @*/
5578 PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5579 {
5580   PetscFunctionBegin;
5581   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5582   if (!snes->dm) {
5583     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm));
5584     snes->dmAuto = PETSC_TRUE;
5585   }
5586   *dm = snes->dm;
5587   PetscFunctionReturn(0);
5588 }
5589 
5590 /*@
5591   SNESSetNPC - Sets the nonlinear preconditioner to be used.
5592 
5593   Collective on SNES
5594 
5595   Input Parameters:
5596 + snes - iterative context obtained from SNESCreate()
5597 - pc   - the preconditioner object
5598 
5599   Notes:
5600   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5601   to configure it using the API).
5602 
5603   Level: developer
5604 
5605 .seealso: `SNESGetNPC()`, `SNESHasNPC()`
5606 @*/
5607 PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5608 {
5609   PetscFunctionBegin;
5610   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5611   PetscValidHeaderSpecific(pc, SNES_CLASSID, 2);
5612   PetscCheckSameComm(snes, 1, pc, 2);
5613   PetscCall(PetscObjectReference((PetscObject) pc));
5614   PetscCall(SNESDestroy(&snes->npc));
5615   snes->npc = pc;
5616   PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc));
5617   PetscFunctionReturn(0);
5618 }
5619 
5620 /*@
5621   SNESGetNPC - Creates a nonlinear preconditioning solver (SNES) to be used to precondition the nonlinear solver.
5622 
5623   Not Collective; but any changes to the obtained SNES object must be applied collectively
5624 
5625   Input Parameter:
5626 . snes - iterative context obtained from SNESCreate()
5627 
5628   Output Parameter:
5629 . pc - preconditioner context
5630 
5631   Options Database:
5632 . -npc_snes_type <type> - set the type of the SNES to use as the nonlinear preconditioner
5633 
5634   Notes:
5635     If a SNES was previously set with SNESSetNPC() then that SNES is returned, otherwise a new SNES object is created.
5636 
5637     The (preconditioner) SNES returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5638     SNES during SNESSetUp()
5639 
5640   Level: developer
5641 
5642 .seealso: `SNESSetNPC()`, `SNESHasNPC()`, `SNES`, `SNESCreate()`
5643 @*/
5644 PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5645 {
5646   const char     *optionsprefix;
5647 
5648   PetscFunctionBegin;
5649   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5650   PetscValidPointer(pc, 2);
5651   if (!snes->npc) {
5652     PetscCall(SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc));
5653     PetscCall(PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1));
5654     PetscCall(PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc));
5655     PetscCall(SNESGetOptionsPrefix(snes,&optionsprefix));
5656     PetscCall(SNESSetOptionsPrefix(snes->npc,optionsprefix));
5657     PetscCall(SNESAppendOptionsPrefix(snes->npc,"npc_"));
5658     PetscCall(SNESSetCountersReset(snes->npc,PETSC_FALSE));
5659   }
5660   *pc = snes->npc;
5661   PetscFunctionReturn(0);
5662 }
5663 
5664 /*@
5665   SNESHasNPC - Returns whether a nonlinear preconditioner exists
5666 
5667   Not Collective
5668 
5669   Input Parameter:
5670 . snes - iterative context obtained from SNESCreate()
5671 
5672   Output Parameter:
5673 . has_npc - whether the SNES has an NPC or not
5674 
5675   Level: developer
5676 
5677 .seealso: `SNESSetNPC()`, `SNESGetNPC()`
5678 @*/
5679 PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5680 {
5681   PetscFunctionBegin;
5682   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5683   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5684   PetscFunctionReturn(0);
5685 }
5686 
5687 /*@
5688     SNESSetNPCSide - Sets the preconditioning side.
5689 
5690     Logically Collective on SNES
5691 
5692     Input Parameter:
5693 .   snes - iterative context obtained from SNESCreate()
5694 
5695     Output Parameter:
5696 .   side - the preconditioning side, where side is one of
5697 .vb
5698       PC_LEFT - left preconditioning
5699       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5700 .ve
5701 
5702     Options Database Keys:
5703 .   -snes_npc_side <right,left> - nonlinear preconditioner side
5704 
5705     Notes:
5706     SNESNRICHARDSON and SNESNCG only support left preconditioning.
5707 
5708     Level: intermediate
5709 
5710 .seealso: `SNESGetNPCSide()`, `KSPSetPCSide()`
5711 @*/
5712 PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5713 {
5714   PetscFunctionBegin;
5715   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5716   PetscValidLogicalCollectiveEnum(snes,side,2);
5717   if (side == PC_SIDE_DEFAULT) side = PC_RIGHT;
5718   PetscCheck((side == PC_LEFT) || (side == PC_RIGHT),PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Only PC_LEFT and PC_RIGHT are supported");
5719   snes->npcside = side;
5720   PetscFunctionReturn(0);
5721 }
5722 
5723 /*@
5724     SNESGetNPCSide - Gets the preconditioning side.
5725 
5726     Not Collective
5727 
5728     Input Parameter:
5729 .   snes - iterative context obtained from SNESCreate()
5730 
5731     Output Parameter:
5732 .   side - the preconditioning side, where side is one of
5733 .vb
5734       PC_LEFT - left preconditioning
5735       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5736 .ve
5737 
5738     Level: intermediate
5739 
5740 .seealso: `SNESSetNPCSide()`, `KSPGetPCSide()`
5741 @*/
5742 PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5743 {
5744   PetscFunctionBegin;
5745   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5746   PetscValidPointer(side,2);
5747   *side = snes->npcside;
5748   PetscFunctionReturn(0);
5749 }
5750 
5751 /*@
5752   SNESSetLineSearch - Sets the linesearch on the SNES instance.
5753 
5754   Collective on SNES
5755 
5756   Input Parameters:
5757 + snes - iterative context obtained from SNESCreate()
5758 - linesearch   - the linesearch object
5759 
5760   Notes:
5761   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5762   to configure it using the API).
5763 
5764   Level: developer
5765 
5766 .seealso: `SNESGetLineSearch()`
5767 @*/
5768 PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5769 {
5770   PetscFunctionBegin;
5771   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5772   PetscValidHeaderSpecific(linesearch, SNESLINESEARCH_CLASSID, 2);
5773   PetscCheckSameComm(snes, 1, linesearch, 2);
5774   PetscCall(PetscObjectReference((PetscObject) linesearch));
5775   PetscCall(SNESLineSearchDestroy(&snes->linesearch));
5776 
5777   snes->linesearch = linesearch;
5778 
5779   PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch));
5780   PetscFunctionReturn(0);
5781 }
5782 
5783 /*@
5784   SNESGetLineSearch - Returns a pointer to the line search context set with SNESSetLineSearch()
5785   or creates a default line search instance associated with the SNES and returns it.
5786 
5787   Not Collective
5788 
5789   Input Parameter:
5790 . snes - iterative context obtained from SNESCreate()
5791 
5792   Output Parameter:
5793 . linesearch - linesearch context
5794 
5795   Level: beginner
5796 
5797 .seealso: `SNESSetLineSearch()`, `SNESLineSearchCreate()`
5798 @*/
5799 PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5800 {
5801   const char     *optionsprefix;
5802 
5803   PetscFunctionBegin;
5804   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
5805   PetscValidPointer(linesearch, 2);
5806   if (!snes->linesearch) {
5807     PetscCall(SNESGetOptionsPrefix(snes, &optionsprefix));
5808     PetscCall(SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch));
5809     PetscCall(SNESLineSearchSetSNES(snes->linesearch, snes));
5810     PetscCall(SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix));
5811     PetscCall(PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1));
5812     PetscCall(PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch));
5813   }
5814   *linesearch = snes->linesearch;
5815   PetscFunctionReturn(0);
5816 }
5817