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