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