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