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