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