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