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