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