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