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