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