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