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