xref: /petsc/src/snes/interface/snes.c (revision fcca9d3d5c45103cafcd0f6bc9babe194d935ced)
1 /*$Id: snes.c,v 1.235 2001/08/21 21:03:49 bsmith Exp $*/
2 
3 #include "src/snes/snesimpl.h"      /*I "petscsnes.h"  I*/
4 
5 PetscTruth SNESRegisterAllCalled = PETSC_FALSE;
6 PetscFList SNESList              = PETSC_NULL;
7 
8 /* Logging support */
9 int SNES_COOKIE = 0;
10 int SNES_Solve = 0, SNES_LineSearch = 0, SNES_FunctionEval = 0, SNES_JacobianEval = 0;
11 
12 #undef __FUNCT__
13 #define __FUNCT__ "SNESView"
14 /*@C
15    SNESView - Prints the SNES data structure.
16 
17    Collective on SNES
18 
19    Input Parameters:
20 +  SNES - the SNES context
21 -  viewer - visualization context
22 
23    Options Database Key:
24 .  -snes_view - Calls SNESView() at end of SNESSolve()
25 
26    Notes:
27    The available visualization contexts include
28 +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
29 -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
30          output where only the first processor opens
31          the file.  All other processors send their
32          data to the first processor to print.
33 
34    The user can open an alternative visualization context with
35    PetscViewerASCIIOpen() - output to a specified file.
36 
37    Level: beginner
38 
39 .keywords: SNES, view
40 
41 .seealso: PetscViewerASCIIOpen()
42 @*/
43 int SNESView(SNES snes,PetscViewer viewer)
44 {
45   SNES_KSP_EW_ConvCtx *kctx;
46   int                 ierr;
47   KSP                ksp;
48   char                *type;
49   PetscTruth          isascii,isstring;
50 
51   PetscFunctionBegin;
52   PetscValidHeaderSpecific(snes,SNES_COOKIE);
53   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(snes->comm);
54   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_COOKIE);
55   PetscCheckSameComm(snes,viewer);
56 
57   ierr = PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&isascii);CHKERRQ(ierr);
58   ierr = PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_STRING,&isstring);CHKERRQ(ierr);
59   if (isascii) {
60     if (snes->prefix) {
61       ierr = PetscViewerASCIIPrintf(viewer,"SNES Object:(%s)\n",snes->prefix);CHKERRQ(ierr);
62     } else {
63       ierr = PetscViewerASCIIPrintf(viewer,"SNES Object:\n");CHKERRQ(ierr);
64     }
65     ierr = SNESGetType(snes,&type);CHKERRQ(ierr);
66     if (type) {
67       ierr = PetscViewerASCIIPrintf(viewer,"  type: %s\n",type);CHKERRQ(ierr);
68     } else {
69       ierr = PetscViewerASCIIPrintf(viewer,"  type: not set yet\n");CHKERRQ(ierr);
70     }
71     if (snes->view) {
72       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
73       ierr = (*snes->view)(snes,viewer);CHKERRQ(ierr);
74       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
75     }
76     ierr = PetscViewerASCIIPrintf(viewer,"  maximum iterations=%d, maximum function evaluations=%d\n",snes->max_its,snes->max_funcs);CHKERRQ(ierr);
77     ierr = PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",
78                  snes->rtol,snes->atol,snes->xtol);CHKERRQ(ierr);
79     ierr = PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%d\n",snes->linear_its);CHKERRQ(ierr);
80     ierr = PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%d\n",snes->nfuncs);CHKERRQ(ierr);
81     if (snes->ksp_ewconv) {
82       kctx = (SNES_KSP_EW_ConvCtx *)snes->kspconvctx;
83       if (kctx) {
84         ierr = PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %d)\n",kctx->version);CHKERRQ(ierr);
85         ierr = PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",kctx->rtol_0,kctx->rtol_max,kctx->threshold);CHKERRQ(ierr);
86         ierr = PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",kctx->gamma,kctx->alpha,kctx->alpha2);CHKERRQ(ierr);
87       }
88     }
89   } else if (isstring) {
90     ierr = SNESGetType(snes,&type);CHKERRQ(ierr);
91     ierr = PetscViewerStringSPrintf(viewer," %-3.3s",type);CHKERRQ(ierr);
92   }
93   ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
94   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
95   ierr = KSPView(ksp,viewer);CHKERRQ(ierr);
96   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
97   PetscFunctionReturn(0);
98 }
99 
100 /*
101   We retain a list of functions that also take SNES command
102   line options. These are called at the end SNESSetFromOptions()
103 */
104 #define MAXSETFROMOPTIONS 5
105 static int numberofsetfromoptions;
106 static int (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);
107 
108 #undef __FUNCT__
109 #define __FUNCT__ "SNESAddOptionsChecker"
110 /*@C
111   SNESAddOptionsChecker - Adds an additional function to check for SNES options.
112 
113   Not Collective
114 
115   Input Parameter:
116 . snescheck - function that checks for options
117 
118   Level: developer
119 
120 .seealso: SNESSetFromOptions()
121 @*/
122 int SNESAddOptionsChecker(int (*snescheck)(SNES))
123 {
124   PetscFunctionBegin;
125   if (numberofsetfromoptions >= MAXSETFROMOPTIONS) {
126     SETERRQ1(PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %d allowed", MAXSETFROMOPTIONS);
127   }
128 
129   othersetfromoptions[numberofsetfromoptions++] = snescheck;
130   PetscFunctionReturn(0);
131 }
132 
133 #undef __FUNCT__
134 #define __FUNCT__ "SNESSetFromOptions"
135 /*@
136    SNESSetFromOptions - Sets various SNES and KSP parameters from user options.
137 
138    Collective on SNES
139 
140    Input Parameter:
141 .  snes - the SNES context
142 
143    Options Database Keys:
144 +  -snes_type <type> - ls, tr, umls, umtr, test
145 .  -snes_stol - convergence tolerance in terms of the norm
146                 of the change in the solution between steps
147 .  -snes_atol <atol> - absolute tolerance of residual norm
148 .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
149 .  -snes_max_it <max_it> - maximum number of iterations
150 .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
151 .  -snes_max_fail <max_fail> - maximum number of failures
152 .  -snes_trtol <trtol> - trust region tolerance
153 .  -snes_no_convergence_test - skip convergence test in nonlinear or minimization
154                                solver; hence iterations will continue until max_it
155                                or some other criterion is reached. Saves expense
156                                of convergence test
157 .  -snes_monitor - prints residual norm at each iteration
158 .  -snes_vecmonitor - plots solution at each iteration
159 .  -snes_vecmonitor_update - plots update to solution at each iteration
160 .  -snes_xmonitor - plots residual norm at each iteration
161 .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
162 -  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
163 
164     Options Database for Eisenstat-Walker method:
165 +  -snes_ksp_ew_conv - use Eisenstat-Walker method for determining linear system convergence
166 .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
167 .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
168 .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
169 .  -snes_ksp_ew_gamma <gamma> - Sets gamma
170 .  -snes_ksp_ew_alpha <alpha> - Sets alpha
171 .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
172 -  -snes_ksp_ew_threshold <threshold> - Sets threshold
173 
174    Notes:
175    To see all options, run your program with the -help option or consult
176    the users manual.
177 
178    Level: beginner
179 
180 .keywords: SNES, nonlinear, set, options, database
181 
182 .seealso: SNESSetOptionsPrefix()
183 @*/
184 int SNESSetFromOptions(SNES snes)
185 {
186   KSP                ksp;
187   SNES_KSP_EW_ConvCtx *kctx = (SNES_KSP_EW_ConvCtx *)snes->kspconvctx;
188   PetscTruth          flg;
189   int                 ierr, i;
190   const char          *deft;
191   char                type[256];
192 
193   PetscFunctionBegin;
194   PetscValidHeaderSpecific(snes,SNES_COOKIE);
195 
196   ierr = PetscOptionsBegin(snes->comm,snes->prefix,"Nonlinear solver (SNES) options","SNES");CHKERRQ(ierr);
197     if (snes->type_name) {
198       deft = snes->type_name;
199     } else {
200       deft = SNESLS;
201     }
202 
203     if (!SNESRegisterAllCalled) {ierr = SNESRegisterAll(PETSC_NULL);CHKERRQ(ierr);}
204     ierr = PetscOptionsList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg);CHKERRQ(ierr);
205     if (flg) {
206       ierr = SNESSetType(snes,type);CHKERRQ(ierr);
207     } else if (!snes->type_name) {
208       ierr = SNESSetType(snes,deft);CHKERRQ(ierr);
209     }
210     ierr = PetscOptionsName("-snes_view","Print detailed information on solver used","SNESView",0);CHKERRQ(ierr);
211 
212     ierr = PetscOptionsReal("-snes_stol","Stop if step length less then","SNESSetTolerances",snes->xtol,&snes->xtol,0);CHKERRQ(ierr);
213     ierr = PetscOptionsReal("-snes_atol","Stop if function norm less then","SNESSetTolerances",snes->atol,&snes->atol,0);CHKERRQ(ierr);
214 
215     ierr = PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less then","SNESSetTolerances",snes->rtol,&snes->rtol,0);CHKERRQ(ierr);
216     ierr = PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,PETSC_NULL);CHKERRQ(ierr);
217     ierr = PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,PETSC_NULL);CHKERRQ(ierr);
218     ierr = PetscOptionsInt("-snes_max_fail","Maximum failures","SNESSetTolerances",snes->maxFailures,&snes->maxFailures,PETSC_NULL);CHKERRQ(ierr);
219 
220     ierr = PetscOptionsName("-snes_ksp_ew_conv","Use Eisentat-Walker linear system convergence test","SNES_KSP_SetParametersEW",&snes->ksp_ewconv);CHKERRQ(ierr);
221 
222     ierr = PetscOptionsInt("-snes_ksp_ew_version","Version 1 or 2","SNES_KSP_SetParametersEW",kctx->version,&kctx->version,0);CHKERRQ(ierr);
223     ierr = PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNES_KSP_SetParametersEW",kctx->rtol_0,&kctx->rtol_0,0);CHKERRQ(ierr);
224     ierr = PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNES_KSP_SetParametersEW",kctx->rtol_max,&kctx->rtol_max,0);CHKERRQ(ierr);
225     ierr = PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNES_KSP_SetParametersEW",kctx->gamma,&kctx->gamma,0);CHKERRQ(ierr);
226     ierr = PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNES_KSP_SetParametersEW",kctx->alpha,&kctx->alpha,0);CHKERRQ(ierr);
227     ierr = PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNES_KSP_SetParametersEW",kctx->alpha2,&kctx->alpha2,0);CHKERRQ(ierr);
228     ierr = PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNES_KSP_SetParametersEW",kctx->threshold,&kctx->threshold,0);CHKERRQ(ierr);
229 
230     ierr = PetscOptionsName("-snes_no_convergence_test","Don't test for convergence","None",&flg);CHKERRQ(ierr);
231     if (flg) {snes->converged = 0;}
232     ierr = PetscOptionsName("-snes_cancelmonitors","Remove all monitors","SNESClearMonitor",&flg);CHKERRQ(ierr);
233     if (flg) {ierr = SNESClearMonitor(snes);CHKERRQ(ierr);}
234     ierr = PetscOptionsName("-snes_monitor","Monitor norm of function","SNESDefaultMonitor",&flg);CHKERRQ(ierr);
235     if (flg) {ierr = SNESSetMonitor(snes,SNESDefaultMonitor,0,0);CHKERRQ(ierr);}
236     ierr = PetscOptionsName("-snes_ratiomonitor","Monitor norm of function","SNESSetRatioMonitor",&flg);CHKERRQ(ierr);
237     if (flg) {ierr = SNESSetRatioMonitor(snes);CHKERRQ(ierr);}
238     ierr = PetscOptionsName("-snes_smonitor","Monitor norm of function (fewer digits)","SNESDefaultSMonitor",&flg);CHKERRQ(ierr);
239     if (flg) {ierr = SNESSetMonitor(snes,SNESDefaultSMonitor,0,0);CHKERRQ(ierr);}
240     ierr = PetscOptionsName("-snes_vecmonitor","Plot solution at each iteration","SNESVecViewMonitor",&flg);CHKERRQ(ierr);
241     if (flg) {ierr = SNESSetMonitor(snes,SNESVecViewMonitor,0,0);CHKERRQ(ierr);}
242     ierr = PetscOptionsName("-snes_vecmonitor_update","Plot correction at each iteration","SNESVecViewUpdateMonitor",&flg);CHKERRQ(ierr);
243     if (flg) {ierr = SNESSetMonitor(snes,SNESVecViewUpdateMonitor,0,0);CHKERRQ(ierr);}
244     ierr = PetscOptionsName("-snes_vecmonitor_residual","Plot residual at each iteration","SNESVecViewResidualMonitor",&flg);CHKERRQ(ierr);
245     if (flg) {ierr = SNESSetMonitor(snes,SNESVecViewResidualMonitor,0,0);CHKERRQ(ierr);}
246     ierr = PetscOptionsName("-snes_xmonitor","Plot function norm at each iteration","SNESLGMonitor",&flg);CHKERRQ(ierr);
247     if (flg) {ierr = SNESSetMonitor(snes,SNESLGMonitor,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr);}
248 
249     ierr = PetscOptionsName("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESDefaultComputeJacobian",&flg);CHKERRQ(ierr);
250     if (flg) {
251       ierr = SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESDefaultComputeJacobian,snes->funP);CHKERRQ(ierr);
252       PetscLogInfo(snes,"SNESSetFromOptions: Setting default finite difference Jacobian matrix\n");
253     }
254 
255     for(i = 0; i < numberofsetfromoptions; i++) {
256       ierr = (*othersetfromoptions[i])(snes);                                                             CHKERRQ(ierr);
257     }
258 
259     if (snes->setfromoptions) {
260       ierr = (*snes->setfromoptions)(snes);CHKERRQ(ierr);
261     }
262 
263   ierr = PetscOptionsEnd();CHKERRQ(ierr);
264 
265   ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
266   ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr);
267 
268   PetscFunctionReturn(0);
269 }
270 
271 
272 #undef __FUNCT__
273 #define __FUNCT__ "SNESSetApplicationContext"
274 /*@
275    SNESSetApplicationContext - Sets the optional user-defined context for
276    the nonlinear solvers.
277 
278    Collective on SNES
279 
280    Input Parameters:
281 +  snes - the SNES context
282 -  usrP - optional user context
283 
284    Level: intermediate
285 
286 .keywords: SNES, nonlinear, set, application, context
287 
288 .seealso: SNESGetApplicationContext()
289 @*/
290 int SNESSetApplicationContext(SNES snes,void *usrP)
291 {
292   PetscFunctionBegin;
293   PetscValidHeaderSpecific(snes,SNES_COOKIE);
294   snes->user		= usrP;
295   PetscFunctionReturn(0);
296 }
297 
298 #undef __FUNCT__
299 #define __FUNCT__ "SNESGetApplicationContext"
300 /*@C
301    SNESGetApplicationContext - Gets the user-defined context for the
302    nonlinear solvers.
303 
304    Not Collective
305 
306    Input Parameter:
307 .  snes - SNES context
308 
309    Output Parameter:
310 .  usrP - user context
311 
312    Level: intermediate
313 
314 .keywords: SNES, nonlinear, get, application, context
315 
316 .seealso: SNESSetApplicationContext()
317 @*/
318 int SNESGetApplicationContext(SNES snes,void **usrP)
319 {
320   PetscFunctionBegin;
321   PetscValidHeaderSpecific(snes,SNES_COOKIE);
322   *usrP = snes->user;
323   PetscFunctionReturn(0);
324 }
325 
326 #undef __FUNCT__
327 #define __FUNCT__ "SNESGetIterationNumber"
328 /*@
329    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
330    at this time.
331 
332    Not Collective
333 
334    Input Parameter:
335 .  snes - SNES context
336 
337    Output Parameter:
338 .  iter - iteration number
339 
340    Notes:
341    For example, during the computation of iteration 2 this would return 1.
342 
343    This is useful for using lagged Jacobians (where one does not recompute the
344    Jacobian at each SNES iteration). For example, the code
345 .vb
346       ierr = SNESGetIterationNumber(snes,&it);
347       if (!(it % 2)) {
348         [compute Jacobian here]
349       }
350 .ve
351    can be used in your ComputeJacobian() function to cause the Jacobian to be
352    recomputed every second SNES iteration.
353 
354    Level: intermediate
355 
356 .keywords: SNES, nonlinear, get, iteration, number
357 @*/
358 int SNESGetIterationNumber(SNES snes,int* iter)
359 {
360   PetscFunctionBegin;
361   PetscValidHeaderSpecific(snes,SNES_COOKIE);
362   PetscValidIntPointer(iter);
363   *iter = snes->iter;
364   PetscFunctionReturn(0);
365 }
366 
367 #undef __FUNCT__
368 #define __FUNCT__ "SNESGetFunctionNorm"
369 /*@
370    SNESGetFunctionNorm - Gets the norm of the current function that was set
371    with SNESSSetFunction().
372 
373    Collective on SNES
374 
375    Input Parameter:
376 .  snes - SNES context
377 
378    Output Parameter:
379 .  fnorm - 2-norm of function
380 
381    Level: intermediate
382 
383 .keywords: SNES, nonlinear, get, function, norm
384 
385 .seealso: SNESGetFunction()
386 @*/
387 int SNESGetFunctionNorm(SNES snes,PetscScalar *fnorm)
388 {
389   PetscFunctionBegin;
390   PetscValidHeaderSpecific(snes,SNES_COOKIE);
391   PetscValidScalarPointer(fnorm);
392   *fnorm = snes->norm;
393   PetscFunctionReturn(0);
394 }
395 
396 #undef __FUNCT__
397 #define __FUNCT__ "SNESGetNumberUnsuccessfulSteps"
398 /*@
399    SNESGetNumberUnsuccessfulSteps - Gets the number of unsuccessful steps
400    attempted by the nonlinear solver.
401 
402    Not Collective
403 
404    Input Parameter:
405 .  snes - SNES context
406 
407    Output Parameter:
408 .  nfails - number of unsuccessful steps attempted
409 
410    Notes:
411    This counter is reset to zero for each successive call to SNESSolve().
412 
413    Level: intermediate
414 
415 .keywords: SNES, nonlinear, get, number, unsuccessful, steps
416 @*/
417 int SNESGetNumberUnsuccessfulSteps(SNES snes,int* nfails)
418 {
419   PetscFunctionBegin;
420   PetscValidHeaderSpecific(snes,SNES_COOKIE);
421   PetscValidIntPointer(nfails);
422   *nfails = snes->numFailures;
423   PetscFunctionReturn(0);
424 }
425 
426 #undef __FUNCT__
427 #define __FUNCT__ "SNESSetMaximumUnsuccessfulSteps"
428 /*@
429    SNESSetMaximumUnsuccessfulSteps - Sets the maximum number of unsuccessful steps
430    attempted by the nonlinear solver before it gives up.
431 
432    Not Collective
433 
434    Input Parameters:
435 +  snes     - SNES context
436 -  maxFails - maximum of unsuccessful steps
437 
438    Level: intermediate
439 
440 .keywords: SNES, nonlinear, set, maximum, unsuccessful, steps
441 @*/
442 int SNESSetMaximumUnsuccessfulSteps(SNES snes, int maxFails)
443 {
444   PetscFunctionBegin;
445   PetscValidHeaderSpecific(snes,SNES_COOKIE);
446   snes->maxFailures = maxFails;
447   PetscFunctionReturn(0);
448 }
449 
450 #undef __FUNCT__
451 #define __FUNCT__ "SNESGetMaximumUnsuccessfulSteps"
452 /*@
453    SNESGetMaximumUnsuccessfulSteps - Gets the maximum number of unsuccessful steps
454    attempted by the nonlinear solver before it gives up.
455 
456    Not Collective
457 
458    Input Parameter:
459 .  snes     - SNES context
460 
461    Output Parameter:
462 .  maxFails - maximum of unsuccessful steps
463 
464    Level: intermediate
465 
466 .keywords: SNES, nonlinear, get, maximum, unsuccessful, steps
467 @*/
468 int SNESGetMaximumUnsuccessfulSteps(SNES snes, int *maxFails)
469 {
470   PetscFunctionBegin;
471   PetscValidHeaderSpecific(snes,SNES_COOKIE);
472   PetscValidIntPointer(maxFails);
473   *maxFails = snes->maxFailures;
474   PetscFunctionReturn(0);
475 }
476 
477 #undef __FUNCT__
478 #define __FUNCT__ "SNESGetNumberLinearIterations"
479 /*@
480    SNESGetNumberLinearIterations - Gets the total number of linear iterations
481    used by the nonlinear solver.
482 
483    Not Collective
484 
485    Input Parameter:
486 .  snes - SNES context
487 
488    Output Parameter:
489 .  lits - number of linear iterations
490 
491    Notes:
492    This counter is reset to zero for each successive call to SNESSolve().
493 
494    Level: intermediate
495 
496 .keywords: SNES, nonlinear, get, number, linear, iterations
497 @*/
498 int SNESGetNumberLinearIterations(SNES snes,int* lits)
499 {
500   PetscFunctionBegin;
501   PetscValidHeaderSpecific(snes,SNES_COOKIE);
502   PetscValidIntPointer(lits);
503   *lits = snes->linear_its;
504   PetscFunctionReturn(0);
505 }
506 
507 #undef __FUNCT__
508 #define __FUNCT__ "SNESGetKSP"
509 /*@C
510    SNESGetKSP - Returns the KSP context for a SNES solver.
511 
512    Not Collective, but if SNES object is parallel, then KSP object is parallel
513 
514    Input Parameter:
515 .  snes - the SNES context
516 
517    Output Parameter:
518 .  ksp - the KSP context
519 
520    Notes:
521    The user can then directly manipulate the KSP context to set various
522    options, etc.  Likewise, the user can then extract and manipulate the
523    KSP and PC contexts as well.
524 
525    Level: beginner
526 
527 .keywords: SNES, nonlinear, get, KSP, context
528 
529 .seealso: KSPGetPC()
530 @*/
531 int SNESGetKSP(SNES snes,KSP *ksp)
532 {
533   PetscFunctionBegin;
534   PetscValidHeaderSpecific(snes,SNES_COOKIE);
535   *ksp = snes->ksp;
536   PetscFunctionReturn(0);
537 }
538 
539 #undef __FUNCT__
540 #define __FUNCT__ "SNESPublish_Petsc"
541 static int SNESPublish_Petsc(PetscObject obj)
542 {
543 #if defined(PETSC_HAVE_AMS)
544   SNES          v = (SNES) obj;
545   int          ierr;
546 #endif
547 
548   PetscFunctionBegin;
549 
550 #if defined(PETSC_HAVE_AMS)
551   /* if it is already published then return */
552   if (v->amem >=0) PetscFunctionReturn(0);
553 
554   ierr = PetscObjectPublishBaseBegin(obj);CHKERRQ(ierr);
555   ierr = AMS_Memory_add_field((AMS_Memory)v->amem,"Iteration",&v->iter,1,AMS_INT,AMS_READ,
556                                 AMS_COMMON,AMS_REDUCT_UNDEF);CHKERRQ(ierr);
557   ierr = AMS_Memory_add_field((AMS_Memory)v->amem,"Residual",&v->norm,1,AMS_DOUBLE,AMS_READ,
558                                 AMS_COMMON,AMS_REDUCT_UNDEF);CHKERRQ(ierr);
559   ierr = PetscObjectPublishBaseEnd(obj);CHKERRQ(ierr);
560 #endif
561   PetscFunctionReturn(0);
562 }
563 
564 /* -----------------------------------------------------------*/
565 #undef __FUNCT__
566 #define __FUNCT__ "SNESCreate"
567 /*@C
568    SNESCreate - Creates a nonlinear solver context.
569 
570    Collective on MPI_Comm
571 
572    Input Parameters:
573 +  comm - MPI communicator
574 
575    Output Parameter:
576 .  outsnes - the new SNES context
577 
578    Options Database Keys:
579 +   -snes_mf - Activates default matrix-free Jacobian-vector products,
580                and no preconditioning matrix
581 .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
582                products, and a user-provided preconditioning matrix
583                as set by SNESSetJacobian()
584 -   -snes_fd - Uses (slow!) finite differences to compute Jacobian
585 
586    Level: beginner
587 
588 .keywords: SNES, nonlinear, create, context
589 
590 .seealso: SNESSolve(), SNESDestroy(), SNES
591 @*/
592 int SNESCreate(MPI_Comm comm,SNES *outsnes)
593 {
594   int                 ierr;
595   SNES                snes;
596   SNES_KSP_EW_ConvCtx *kctx;
597 
598   PetscFunctionBegin;
599   PetscValidPointer(outsnes);
600   *outsnes = PETSC_NULL;
601 #ifndef PETSC_USE_DYNAMIC_LIBRARIES
602   ierr = SNESInitializePackage(PETSC_NULL);                                                               CHKERRQ(ierr);
603 #endif
604 
605   PetscHeaderCreate(snes,_p_SNES,int,SNES_COOKIE,0,"SNES",comm,SNESDestroy,SNESView);
606   PetscLogObjectCreate(snes);
607   snes->bops->publish     = SNESPublish_Petsc;
608   snes->max_its           = 50;
609   snes->max_funcs	  = 10000;
610   snes->norm		  = 0.0;
611   snes->rtol		  = 1.e-8;
612   snes->ttol              = 0.0;
613   snes->atol		  = 1.e-50;
614   snes->xtol		  = 1.e-8;
615   snes->deltatol	  = 1.e-12;
616   snes->nfuncs            = 0;
617   snes->numFailures       = 0;
618   snes->maxFailures       = 1;
619   snes->linear_its        = 0;
620   snes->numbermonitors    = 0;
621   snes->data              = 0;
622   snes->view              = 0;
623   snes->setupcalled       = 0;
624   snes->ksp_ewconv        = PETSC_FALSE;
625   snes->vwork             = 0;
626   snes->nwork             = 0;
627   snes->conv_hist_len     = 0;
628   snes->conv_hist_max     = 0;
629   snes->conv_hist         = PETSC_NULL;
630   snes->conv_hist_its     = PETSC_NULL;
631   snes->conv_hist_reset   = PETSC_TRUE;
632   snes->reason            = SNES_CONVERGED_ITERATING;
633 
634   /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
635   ierr = PetscNew(SNES_KSP_EW_ConvCtx,&kctx);CHKERRQ(ierr);
636   PetscLogObjectMemory(snes,sizeof(SNES_KSP_EW_ConvCtx));
637   snes->kspconvctx  = (void*)kctx;
638   kctx->version     = 2;
639   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
640                              this was too large for some test cases */
641   kctx->rtol_last   = 0;
642   kctx->rtol_max    = .9;
643   kctx->gamma       = 1.0;
644   kctx->alpha2      = .5*(1.0 + sqrt(5.0));
645   kctx->alpha       = kctx->alpha2;
646   kctx->threshold   = .1;
647   kctx->lresid_last = 0;
648   kctx->norm_last   = 0;
649 
650   ierr = KSPCreate(comm,&snes->ksp);CHKERRQ(ierr);
651   PetscLogObjectParent(snes,snes->ksp)
652 
653   *outsnes = snes;
654   ierr = PetscPublishAll(snes);CHKERRQ(ierr);
655   PetscFunctionReturn(0);
656 }
657 
658 /* --------------------------------------------------------------- */
659 #undef __FUNCT__
660 #define __FUNCT__ "SNESSetFunction"
661 /*@C
662    SNESSetFunction - Sets the function evaluation routine and function
663    vector for use by the SNES routines in solving systems of nonlinear
664    equations.
665 
666    Collective on SNES
667 
668    Input Parameters:
669 +  snes - the SNES context
670 .  func - function evaluation routine
671 .  r - vector to store function value
672 -  ctx - [optional] user-defined context for private data for the
673          function evaluation routine (may be PETSC_NULL)
674 
675    Calling sequence of func:
676 $    func (SNES snes,Vec x,Vec f,void *ctx);
677 
678 .  f - function vector
679 -  ctx - optional user-defined function context
680 
681    Notes:
682    The Newton-like methods typically solve linear systems of the form
683 $      f'(x) x = -f(x),
684    where f'(x) denotes the Jacobian matrix and f(x) is the function.
685 
686    Level: beginner
687 
688 .keywords: SNES, nonlinear, set, function
689 
690 .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
691 @*/
692 int SNESSetFunction(SNES snes,Vec r,int (*func)(SNES,Vec,Vec,void*),void *ctx)
693 {
694   PetscFunctionBegin;
695   PetscValidHeaderSpecific(snes,SNES_COOKIE);
696   PetscValidHeaderSpecific(r,VEC_COOKIE);
697   PetscCheckSameComm(snes,r);
698 
699   snes->computefunction     = func;
700   snes->vec_func            = snes->vec_func_always = r;
701   snes->funP                = ctx;
702   PetscFunctionReturn(0);
703 }
704 
705 #undef __FUNCT__
706 #define __FUNCT__ "SNESComputeFunction"
707 /*@
708    SNESComputeFunction - Calls the function that has been set with
709                          SNESSetFunction().
710 
711    Collective on SNES
712 
713    Input Parameters:
714 +  snes - the SNES context
715 -  x - input vector
716 
717    Output Parameter:
718 .  y - function vector, as set by SNESSetFunction()
719 
720    Notes:
721    SNESComputeFunction() is typically used within nonlinear solvers
722    implementations, so most users would not generally call this routine
723    themselves.
724 
725    Level: developer
726 
727 .keywords: SNES, nonlinear, compute, function
728 
729 .seealso: SNESSetFunction(), SNESGetFunction()
730 @*/
731 int SNESComputeFunction(SNES snes,Vec x,Vec y)
732 {
733   int    ierr;
734 
735   PetscFunctionBegin;
736   PetscValidHeaderSpecific(snes,SNES_COOKIE);
737   PetscValidHeaderSpecific(x,VEC_COOKIE);
738   PetscValidHeaderSpecific(y,VEC_COOKIE);
739   PetscCheckSameComm(snes,x);
740   PetscCheckSameComm(snes,y);
741 
742   ierr = PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);CHKERRQ(ierr);
743   PetscStackPush("SNES user function");
744   ierr = (*snes->computefunction)(snes,x,y,snes->funP);CHKERRQ(ierr);
745   PetscStackPop;
746   snes->nfuncs++;
747   ierr = PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);CHKERRQ(ierr);
748   PetscFunctionReturn(0);
749 }
750 
751 #undef __FUNCT__
752 #define __FUNCT__ "SNESComputeJacobian"
753 /*@
754    SNESComputeJacobian - Computes the Jacobian matrix that has been
755    set with SNESSetJacobian().
756 
757    Collective on SNES and Mat
758 
759    Input Parameters:
760 +  snes - the SNES context
761 -  x - input vector
762 
763    Output Parameters:
764 +  A - Jacobian matrix
765 .  B - optional preconditioning matrix
766 -  flag - flag indicating matrix structure
767 
768    Notes:
769    Most users should not need to explicitly call this routine, as it
770    is used internally within the nonlinear solvers.
771 
772    See KSPSetOperators() for important information about setting the
773    flag parameter.
774 
775    Level: developer
776 
777 .keywords: SNES, compute, Jacobian, matrix
778 
779 .seealso:  SNESSetJacobian(), KSPSetOperators()
780 @*/
781 int SNESComputeJacobian(SNES snes,Vec X,Mat *A,Mat *B,MatStructure *flg)
782 {
783   int    ierr;
784 
785   PetscFunctionBegin;
786   PetscValidHeaderSpecific(snes,SNES_COOKIE);
787   PetscValidHeaderSpecific(X,VEC_COOKIE);
788   PetscCheckSameComm(snes,X);
789   if (!snes->computejacobian) PetscFunctionReturn(0);
790   ierr = PetscLogEventBegin(SNES_JacobianEval,snes,X,*A,*B);CHKERRQ(ierr);
791   *flg = DIFFERENT_NONZERO_PATTERN;
792   PetscStackPush("SNES user Jacobian function");
793   ierr = (*snes->computejacobian)(snes,X,A,B,flg,snes->jacP);CHKERRQ(ierr);
794   PetscStackPop;
795   ierr = PetscLogEventEnd(SNES_JacobianEval,snes,X,*A,*B);CHKERRQ(ierr);
796   /* make sure user returned a correct Jacobian and preconditioner */
797   PetscValidHeaderSpecific(*A,MAT_COOKIE);
798   PetscValidHeaderSpecific(*B,MAT_COOKIE);
799   PetscFunctionReturn(0);
800 }
801 
802 #undef __FUNCT__
803 #define __FUNCT__ "SNESSetJacobian"
804 /*@C
805    SNESSetJacobian - Sets the function to compute Jacobian as well as the
806    location to store the matrix.
807 
808    Collective on SNES and Mat
809 
810    Input Parameters:
811 +  snes - the SNES context
812 .  A - Jacobian matrix
813 .  B - preconditioner matrix (usually same as the Jacobian)
814 .  func - Jacobian evaluation routine
815 -  ctx - [optional] user-defined context for private data for the
816          Jacobian evaluation routine (may be PETSC_NULL)
817 
818    Calling sequence of func:
819 $     func (SNES snes,Vec x,Mat *A,Mat *B,int *flag,void *ctx);
820 
821 +  x - input vector
822 .  A - Jacobian matrix
823 .  B - preconditioner matrix, usually the same as A
824 .  flag - flag indicating information about the preconditioner matrix
825    structure (same as flag in KSPSetOperators())
826 -  ctx - [optional] user-defined Jacobian context
827 
828    Notes:
829    See KSPSetOperators() for important information about setting the flag
830    output parameter in the routine func().  Be sure to read this information!
831 
832    The routine func() takes Mat * as the matrix arguments rather than Mat.
833    This allows the Jacobian evaluation routine to replace A and/or B with a
834    completely new new matrix structure (not just different matrix elements)
835    when appropriate, for instance, if the nonzero structure is changing
836    throughout the global iterations.
837 
838    Level: beginner
839 
840 .keywords: SNES, nonlinear, set, Jacobian, matrix
841 
842 .seealso: KSPSetOperators(), SNESSetFunction()
843 @*/
844 int SNESSetJacobian(SNES snes,Mat A,Mat B,int (*func)(SNES,Vec,Mat*,Mat*,MatStructure*,void*),void *ctx)
845 {
846   int ierr;
847 
848   PetscFunctionBegin;
849   PetscValidHeaderSpecific(snes,SNES_COOKIE);
850   if (A) PetscValidHeaderSpecific(A,MAT_COOKIE);
851   if (B) PetscValidHeaderSpecific(B,MAT_COOKIE);
852   if (A) PetscCheckSameComm(snes,A);
853   if (B) PetscCheckSameComm(snes,B);
854   if (func) snes->computejacobian = func;
855   if (ctx)  snes->jacP            = ctx;
856   if (A) {
857     if (snes->jacobian) {ierr = MatDestroy(snes->jacobian);CHKERRQ(ierr);}
858     snes->jacobian = A;
859     ierr           = PetscObjectReference((PetscObject)A);CHKERRQ(ierr);
860   }
861   if (B) {
862     if (snes->jacobian_pre) {ierr = MatDestroy(snes->jacobian_pre);CHKERRQ(ierr);}
863     snes->jacobian_pre = B;
864     ierr               = PetscObjectReference((PetscObject)B);CHKERRQ(ierr);
865   }
866   PetscFunctionReturn(0);
867 }
868 
869 #undef __FUNCT__
870 #define __FUNCT__ "SNESGetJacobian"
871 /*@C
872    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
873    provided context for evaluating the Jacobian.
874 
875    Not Collective, but Mat object will be parallel if SNES object is
876 
877    Input Parameter:
878 .  snes - the nonlinear solver context
879 
880    Output Parameters:
881 +  A - location to stash Jacobian matrix (or PETSC_NULL)
882 .  B - location to stash preconditioner matrix (or PETSC_NULL)
883 .  ctx - location to stash Jacobian ctx (or PETSC_NULL)
884 -  func - location to put Jacobian function (or PETSC_NULL)
885 
886    Level: advanced
887 
888 .seealso: SNESSetJacobian(), SNESComputeJacobian()
889 @*/
890 int SNESGetJacobian(SNES snes,Mat *A,Mat *B,void **ctx,int (**func)(SNES,Vec,Mat*,Mat*,MatStructure*,void*))
891 {
892   PetscFunctionBegin;
893   PetscValidHeaderSpecific(snes,SNES_COOKIE);
894   if (A)    *A    = snes->jacobian;
895   if (B)    *B    = snes->jacobian_pre;
896   if (ctx)  *ctx  = snes->jacP;
897   if (func) *func = snes->computejacobian;
898   PetscFunctionReturn(0);
899 }
900 
901 /* ----- Routines to initialize and destroy a nonlinear solver ---- */
902 extern int SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*);
903 
904 #undef __FUNCT__
905 #define __FUNCT__ "SNESSetUp"
906 /*@
907    SNESSetUp - Sets up the internal data structures for the later use
908    of a nonlinear solver.
909 
910    Collective on SNES
911 
912    Input Parameters:
913 +  snes - the SNES context
914 -  x - the solution vector
915 
916    Notes:
917    For basic use of the SNES solvers the user need not explicitly call
918    SNESSetUp(), since these actions will automatically occur during
919    the call to SNESSolve().  However, if one wishes to control this
920    phase separately, SNESSetUp() should be called after SNESCreate()
921    and optional routines of the form SNESSetXXX(), but before SNESSolve().
922 
923    Level: advanced
924 
925 .keywords: SNES, nonlinear, setup
926 
927 .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
928 @*/
929 int SNESSetUp(SNES snes,Vec x)
930 {
931   int        ierr;
932   PetscTruth flg, iseqtr;
933 
934   PetscFunctionBegin;
935   PetscValidHeaderSpecific(snes,SNES_COOKIE);
936   PetscValidHeaderSpecific(x,VEC_COOKIE);
937   PetscCheckSameComm(snes,x);
938   snes->vec_sol = snes->vec_sol_always = x;
939 
940   ierr = PetscOptionsHasName(snes->prefix,"-snes_mf_operator",&flg);CHKERRQ(ierr);
941   /*
942       This version replaces the user provided Jacobian matrix with a
943       matrix-free version but still employs the user-provided preconditioner matrix
944   */
945   if (flg) {
946     Mat J;
947     ierr = MatCreateSNESMF(snes,snes->vec_sol,&J);CHKERRQ(ierr);
948     ierr = MatSNESMFSetFromOptions(J);CHKERRQ(ierr);
949     PetscLogInfo(snes,"SNESSetUp: Setting default matrix-free operator routines\n");
950     ierr = SNESSetJacobian(snes,J,0,0,0);CHKERRQ(ierr);
951     ierr = MatDestroy(J);CHKERRQ(ierr);
952   }
953 
954 #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_SINGLE)
955   ierr = PetscOptionsHasName(snes->prefix,"-snes_mf_operator2",&flg);CHKERRQ(ierr);
956   if (flg) {
957     Mat J;
958     ierr = SNESDefaultMatrixFreeCreate2(snes,snes->vec_sol,&J);CHKERRQ(ierr);
959     ierr = SNESSetJacobian(snes,J,0,0,0);CHKERRQ(ierr);
960     ierr = MatDestroy(J);CHKERRQ(ierr);
961   }
962 #endif
963 
964   ierr = PetscOptionsHasName(snes->prefix,"-snes_mf",&flg);CHKERRQ(ierr);
965   /*
966       This version replaces both the user-provided Jacobian and the user-
967       provided preconditioner matrix with the default matrix free version.
968    */
969   if (flg) {
970     Mat  J;
971     KSP ksp;
972     PC   pc;
973 
974     ierr = MatCreateSNESMF(snes,snes->vec_sol,&J);CHKERRQ(ierr);
975     ierr = MatSNESMFSetFromOptions(J);CHKERRQ(ierr);
976     PetscLogInfo(snes,"SNESSetUp: Setting default matrix-free operator and preconditioner routines\n");
977     ierr = SNESSetJacobian(snes,J,J,MatSNESMFComputeJacobian,snes->funP);CHKERRQ(ierr);
978     ierr = MatDestroy(J);CHKERRQ(ierr);
979 
980     /* force no preconditioner */
981     ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
982     ierr = KSPGetPC(ksp,&pc);CHKERRQ(ierr);
983     ierr = PetscTypeCompare((PetscObject)pc,PCSHELL,&flg);CHKERRQ(ierr);
984     if (!flg) {
985       ierr = PCSetType(pc,PCNONE);CHKERRQ(ierr);
986     }
987   }
988 
989   if (!snes->vec_func) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Must call SNESSetFunction() first");
990   if (!snes->computefunction) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Must call SNESSetFunction() first");
991   if (!snes->jacobian) SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Must call SNESSetJacobian() first \n or use -snes_mf option");
992   if (snes->vec_func == snes->vec_sol) {
993     SETERRQ(PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
994   }
995 
996   /* Set the KSP stopping criterion to use the Eisenstat-Walker method */
997   ierr = PetscTypeCompare((PetscObject)snes,SNESTR,&iseqtr);CHKERRQ(ierr);
998   if (snes->ksp_ewconv && !iseqtr) {
999     KSP ksp;
1000     ierr = SNESGetKSP(snes,&ksp);CHKERRQ(ierr);
1001     ierr = KSPSetConvergenceTest(ksp,SNES_KSP_EW_Converged_Private,snes);CHKERRQ(ierr);
1002   }
1003 
1004   if (snes->setup) {ierr = (*snes->setup)(snes);CHKERRQ(ierr);}
1005   snes->setupcalled = 1;
1006   PetscFunctionReturn(0);
1007 }
1008 
1009 #undef __FUNCT__
1010 #define __FUNCT__ "SNESDestroy"
1011 /*@C
1012    SNESDestroy - Destroys the nonlinear solver context that was created
1013    with SNESCreate().
1014 
1015    Collective on SNES
1016 
1017    Input Parameter:
1018 .  snes - the SNES context
1019 
1020    Level: beginner
1021 
1022 .keywords: SNES, nonlinear, destroy
1023 
1024 .seealso: SNESCreate(), SNESSolve()
1025 @*/
1026 int SNESDestroy(SNES snes)
1027 {
1028   int i,ierr;
1029 
1030   PetscFunctionBegin;
1031   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1032   if (--snes->refct > 0) PetscFunctionReturn(0);
1033 
1034   /* if memory was published with AMS then destroy it */
1035   ierr = PetscObjectDepublish(snes);CHKERRQ(ierr);
1036 
1037   if (snes->destroy) {ierr = (*(snes)->destroy)(snes);CHKERRQ(ierr);}
1038   if (snes->kspconvctx) {ierr = PetscFree(snes->kspconvctx);CHKERRQ(ierr);}
1039   if (snes->jacobian) {ierr = MatDestroy(snes->jacobian);CHKERRQ(ierr);}
1040   if (snes->jacobian_pre) {ierr = MatDestroy(snes->jacobian_pre);CHKERRQ(ierr);}
1041   ierr = KSPDestroy(snes->ksp);CHKERRQ(ierr);
1042   if (snes->vwork) {ierr = VecDestroyVecs(snes->vwork,snes->nvwork);CHKERRQ(ierr);}
1043   for (i=0; i<snes->numbermonitors; i++) {
1044     if (snes->monitordestroy[i]) {
1045       ierr = (*snes->monitordestroy[i])(snes->monitorcontext[i]);CHKERRQ(ierr);
1046     }
1047   }
1048   PetscLogObjectDestroy((PetscObject)snes);
1049   PetscHeaderDestroy((PetscObject)snes);
1050   PetscFunctionReturn(0);
1051 }
1052 
1053 /* ----------- Routines to set solver parameters ---------- */
1054 
1055 #undef __FUNCT__
1056 #define __FUNCT__ "SNESSetTolerances"
1057 /*@
1058    SNESSetTolerances - Sets various parameters used in convergence tests.
1059 
1060    Collective on SNES
1061 
1062    Input Parameters:
1063 +  snes - the SNES context
1064 .  atol - absolute convergence tolerance
1065 .  rtol - relative convergence tolerance
1066 .  stol -  convergence tolerance in terms of the norm
1067            of the change in the solution between steps
1068 .  maxit - maximum number of iterations
1069 -  maxf - maximum number of function evaluations
1070 
1071    Options Database Keys:
1072 +    -snes_atol <atol> - Sets atol
1073 .    -snes_rtol <rtol> - Sets rtol
1074 .    -snes_stol <stol> - Sets stol
1075 .    -snes_max_it <maxit> - Sets maxit
1076 -    -snes_max_funcs <maxf> - Sets maxf
1077 
1078    Notes:
1079    The default maximum number of iterations is 50.
1080    The default maximum number of function evaluations is 1000.
1081 
1082    Level: intermediate
1083 
1084 .keywords: SNES, nonlinear, set, convergence, tolerances
1085 
1086 .seealso: SNESSetTrustRegionTolerance(), SNESSetMinimizationFunctionTolerance()
1087 @*/
1088 int SNESSetTolerances(SNES snes,PetscReal atol,PetscReal rtol,PetscReal stol,int maxit,int maxf)
1089 {
1090   PetscFunctionBegin;
1091   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1092   if (atol != PETSC_DEFAULT)  snes->atol      = atol;
1093   if (rtol != PETSC_DEFAULT)  snes->rtol      = rtol;
1094   if (stol != PETSC_DEFAULT)  snes->xtol      = stol;
1095   if (maxit != PETSC_DEFAULT) snes->max_its   = maxit;
1096   if (maxf != PETSC_DEFAULT)  snes->max_funcs = maxf;
1097   PetscFunctionReturn(0);
1098 }
1099 
1100 #undef __FUNCT__
1101 #define __FUNCT__ "SNESGetTolerances"
1102 /*@
1103    SNESGetTolerances - Gets various parameters used in convergence tests.
1104 
1105    Not Collective
1106 
1107    Input Parameters:
1108 +  snes - the SNES context
1109 .  atol - absolute convergence tolerance
1110 .  rtol - relative convergence tolerance
1111 .  stol -  convergence tolerance in terms of the norm
1112            of the change in the solution between steps
1113 .  maxit - maximum number of iterations
1114 -  maxf - maximum number of function evaluations
1115 
1116    Notes:
1117    The user can specify PETSC_NULL for any parameter that is not needed.
1118 
1119    Level: intermediate
1120 
1121 .keywords: SNES, nonlinear, get, convergence, tolerances
1122 
1123 .seealso: SNESSetTolerances()
1124 @*/
1125 int SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,int *maxit,int *maxf)
1126 {
1127   PetscFunctionBegin;
1128   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1129   if (atol)  *atol  = snes->atol;
1130   if (rtol)  *rtol  = snes->rtol;
1131   if (stol)  *stol  = snes->xtol;
1132   if (maxit) *maxit = snes->max_its;
1133   if (maxf)  *maxf  = snes->max_funcs;
1134   PetscFunctionReturn(0);
1135 }
1136 
1137 #undef __FUNCT__
1138 #define __FUNCT__ "SNESSetTrustRegionTolerance"
1139 /*@
1140    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.
1141 
1142    Collective on SNES
1143 
1144    Input Parameters:
1145 +  snes - the SNES context
1146 -  tol - tolerance
1147 
1148    Options Database Key:
1149 .  -snes_trtol <tol> - Sets tol
1150 
1151    Level: intermediate
1152 
1153 .keywords: SNES, nonlinear, set, trust region, tolerance
1154 
1155 .seealso: SNESSetTolerances(), SNESSetMinimizationFunctionTolerance()
1156 @*/
1157 int SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
1158 {
1159   PetscFunctionBegin;
1160   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1161   snes->deltatol = tol;
1162   PetscFunctionReturn(0);
1163 }
1164 
1165 /*
1166    Duplicate the lg monitors for SNES from KSP; for some reason with
1167    dynamic libraries things don't work under Sun4 if we just use
1168    macros instead of functions
1169 */
1170 #undef __FUNCT__
1171 #define __FUNCT__ "SNESLGMonitor"
1172 int SNESLGMonitor(SNES snes,int it,PetscReal norm,void *ctx)
1173 {
1174   int ierr;
1175 
1176   PetscFunctionBegin;
1177   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1178   ierr = KSPLGMonitor((KSP)snes,it,norm,ctx);CHKERRQ(ierr);
1179   PetscFunctionReturn(0);
1180 }
1181 
1182 #undef __FUNCT__
1183 #define __FUNCT__ "SNESLGMonitorCreate"
1184 int SNESLGMonitorCreate(const char host[],const char label[],int x,int y,int m,int n,PetscDrawLG *draw)
1185 {
1186   int ierr;
1187 
1188   PetscFunctionBegin;
1189   ierr = KSPLGMonitorCreate(host,label,x,y,m,n,draw);CHKERRQ(ierr);
1190   PetscFunctionReturn(0);
1191 }
1192 
1193 #undef __FUNCT__
1194 #define __FUNCT__ "SNESLGMonitorDestroy"
1195 int SNESLGMonitorDestroy(PetscDrawLG draw)
1196 {
1197   int ierr;
1198 
1199   PetscFunctionBegin;
1200   ierr = KSPLGMonitorDestroy(draw);CHKERRQ(ierr);
1201   PetscFunctionReturn(0);
1202 }
1203 
1204 /* ------------ Routines to set performance monitoring options ----------- */
1205 
1206 #undef __FUNCT__
1207 #define __FUNCT__ "SNESSetMonitor"
1208 /*@C
1209    SNESSetMonitor - Sets an ADDITIONAL function that is to be used at every
1210    iteration of the nonlinear solver to display the iteration's
1211    progress.
1212 
1213    Collective on SNES
1214 
1215    Input Parameters:
1216 +  snes - the SNES context
1217 .  func - monitoring routine
1218 .  mctx - [optional] user-defined context for private data for the
1219           monitor routine (use PETSC_NULL if no context is desitre)
1220 -  monitordestroy - [optional] routine that frees monitor context
1221           (may be PETSC_NULL)
1222 
1223    Calling sequence of func:
1224 $     int func(SNES snes,int its, PetscReal norm,void *mctx)
1225 
1226 +    snes - the SNES context
1227 .    its - iteration number
1228 .    norm - 2-norm function value (may be estimated)
1229 -    mctx - [optional] monitoring context
1230 
1231    Options Database Keys:
1232 +    -snes_monitor        - sets SNESDefaultMonitor()
1233 .    -snes_xmonitor       - sets line graph monitor,
1234                             uses SNESLGMonitorCreate()
1235 _    -snes_cancelmonitors - cancels all monitors that have
1236                             been hardwired into a code by
1237                             calls to SNESSetMonitor(), but
1238                             does not cancel those set via
1239                             the options database.
1240 
1241    Notes:
1242    Several different monitoring routines may be set by calling
1243    SNESSetMonitor() multiple times; all will be called in the
1244    order in which they were set.
1245 
1246    Level: intermediate
1247 
1248 .keywords: SNES, nonlinear, set, monitor
1249 
1250 .seealso: SNESDefaultMonitor(), SNESClearMonitor()
1251 @*/
1252 int SNESSetMonitor(SNES snes,int (*func)(SNES,int,PetscReal,void*),void *mctx,int (*monitordestroy)(void *))
1253 {
1254   PetscFunctionBegin;
1255   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1256   if (snes->numbermonitors >= MAXSNESMONITORS) {
1257     SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
1258   }
1259 
1260   snes->monitor[snes->numbermonitors]           = func;
1261   snes->monitordestroy[snes->numbermonitors]    = monitordestroy;
1262   snes->monitorcontext[snes->numbermonitors++]  = (void*)mctx;
1263   PetscFunctionReturn(0);
1264 }
1265 
1266 #undef __FUNCT__
1267 #define __FUNCT__ "SNESClearMonitor"
1268 /*@C
1269    SNESClearMonitor - Clears all the monitor functions for a SNES object.
1270 
1271    Collective on SNES
1272 
1273    Input Parameters:
1274 .  snes - the SNES context
1275 
1276    Options Database Key:
1277 .  -snes_cancelmonitors - cancels all monitors that have been hardwired
1278     into a code by calls to SNESSetMonitor(), but does not cancel those
1279     set via the options database
1280 
1281    Notes:
1282    There is no way to clear one specific monitor from a SNES object.
1283 
1284    Level: intermediate
1285 
1286 .keywords: SNES, nonlinear, set, monitor
1287 
1288 .seealso: SNESDefaultMonitor(), SNESSetMonitor()
1289 @*/
1290 int SNESClearMonitor(SNES snes)
1291 {
1292   PetscFunctionBegin;
1293   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1294   snes->numbermonitors = 0;
1295   PetscFunctionReturn(0);
1296 }
1297 
1298 #undef __FUNCT__
1299 #define __FUNCT__ "SNESSetConvergenceTest"
1300 /*@C
1301    SNESSetConvergenceTest - Sets the function that is to be used
1302    to test for convergence of the nonlinear iterative solution.
1303 
1304    Collective on SNES
1305 
1306    Input Parameters:
1307 +  snes - the SNES context
1308 .  func - routine to test for convergence
1309 -  cctx - [optional] context for private data for the convergence routine
1310           (may be PETSC_NULL)
1311 
1312    Calling sequence of func:
1313 $     int func (SNES snes,PetscReal xnorm,PetscReal gnorm,PetscReal f,SNESConvergedReason *reason,void *cctx)
1314 
1315 +    snes - the SNES context
1316 .    cctx - [optional] convergence context
1317 .    reason - reason for convergence/divergence
1318 .    xnorm - 2-norm of current iterate
1319 .    gnorm - 2-norm of current step
1320 -    f - 2-norm of function
1321 
1322    Level: advanced
1323 
1324 .keywords: SNES, nonlinear, set, convergence, test
1325 
1326 .seealso: SNESConverged_LS(), SNESConverged_TR()
1327 @*/
1328 int SNESSetConvergenceTest(SNES snes,int (*func)(SNES,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx)
1329 {
1330   PetscFunctionBegin;
1331   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1332   (snes)->converged = func;
1333   (snes)->cnvP      = cctx;
1334   PetscFunctionReturn(0);
1335 }
1336 
1337 #undef __FUNCT__
1338 #define __FUNCT__ "SNESGetConvergedReason"
1339 /*@C
1340    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.
1341 
1342    Not Collective
1343 
1344    Input Parameter:
1345 .  snes - the SNES context
1346 
1347    Output Parameter:
1348 .  reason - negative value indicates diverged, positive value converged, see petscsnes.h or the
1349             manual pages for the individual convergence tests for complete lists
1350 
1351    Level: intermediate
1352 
1353    Notes: Can only be called after the call the SNESSolve() is complete.
1354 
1355 .keywords: SNES, nonlinear, set, convergence, test
1356 
1357 .seealso: SNESSetConvergenceTest(), SNESConverged_LS(), SNESConverged_TR(), SNESConvergedReason
1358 @*/
1359 int SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
1360 {
1361   PetscFunctionBegin;
1362   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1363   *reason = snes->reason;
1364   PetscFunctionReturn(0);
1365 }
1366 
1367 #undef __FUNCT__
1368 #define __FUNCT__ "SNESSetConvergenceHistory"
1369 /*@
1370    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.
1371 
1372    Collective on SNES
1373 
1374    Input Parameters:
1375 +  snes - iterative context obtained from SNESCreate()
1376 .  a   - array to hold history
1377 .  its - integer array holds the number of linear iterations for each solve.
1378 .  na  - size of a and its
1379 -  reset - PETSC_TRUE indicates each new nonlinear solve resets the history counter to zero,
1380            else it continues storing new values for new nonlinear solves after the old ones
1381 
1382    Notes:
1383    If set, this array will contain the function norms computed
1384    at each step.
1385 
1386    This routine is useful, e.g., when running a code for purposes
1387    of accurate performance monitoring, when no I/O should be done
1388    during the section of code that is being timed.
1389 
1390    Level: intermediate
1391 
1392 .keywords: SNES, set, convergence, history
1393 
1394 .seealso: SNESGetConvergenceHistory()
1395 
1396 @*/
1397 int SNESSetConvergenceHistory(SNES snes,PetscReal a[],int *its,int na,PetscTruth reset)
1398 {
1399   PetscFunctionBegin;
1400   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1401   if (na) PetscValidScalarPointer(a);
1402   snes->conv_hist       = a;
1403   snes->conv_hist_its   = its;
1404   snes->conv_hist_max   = na;
1405   snes->conv_hist_reset = reset;
1406   PetscFunctionReturn(0);
1407 }
1408 
1409 #undef __FUNCT__
1410 #define __FUNCT__ "SNESGetConvergenceHistory"
1411 /*@C
1412    SNESGetConvergenceHistory - Gets the array used to hold the convergence history.
1413 
1414    Collective on SNES
1415 
1416    Input Parameter:
1417 .  snes - iterative context obtained from SNESCreate()
1418 
1419    Output Parameters:
1420 .  a   - array to hold history
1421 .  its - integer array holds the number of linear iterations (or
1422          negative if not converged) for each solve.
1423 -  na  - size of a and its
1424 
1425    Notes:
1426     The calling sequence for this routine in Fortran is
1427 $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)
1428 
1429    This routine is useful, e.g., when running a code for purposes
1430    of accurate performance monitoring, when no I/O should be done
1431    during the section of code that is being timed.
1432 
1433    Level: intermediate
1434 
1435 .keywords: SNES, get, convergence, history
1436 
1437 .seealso: SNESSetConvergencHistory()
1438 
1439 @*/
1440 int SNESGetConvergenceHistory(SNES snes,PetscReal *a[],int *its[],int *na)
1441 {
1442   PetscFunctionBegin;
1443   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1444   if (a)   *a   = snes->conv_hist;
1445   if (its) *its = snes->conv_hist_its;
1446   if (na) *na   = snes->conv_hist_len;
1447   PetscFunctionReturn(0);
1448 }
1449 
1450 #undef __FUNCT__
1451 #define __FUNCT__ "SNESSetRhsBC"
1452 /*@C
1453   SNESSetRhsBC - Sets the function which applies boundary conditions
1454   to the Rhs of each system.
1455 
1456   Collective on SNES
1457 
1458   Input Parameters:
1459 . snes - The nonlinear solver context
1460 . func - The function
1461 
1462   Calling sequence of func:
1463 . func (SNES snes, Vec rhs, void *ctx);
1464 
1465 . rhs - The current rhs vector
1466 . ctx - The user-context
1467 
1468   Level: intermediate
1469 
1470 .keywords: SNES, Rhs, boundary conditions
1471 .seealso SNESDefaultRhsBC(), SNESSetSolutionBC(), SNESSetUpdate()
1472 @*/
1473 int SNESSetRhsBC(SNES snes, int (*func)(SNES, Vec, void *))
1474 {
1475   PetscFunctionBegin;
1476   PetscValidHeaderSpecific(snes, SNES_COOKIE);
1477   snes->applyrhsbc = func;
1478   PetscFunctionReturn(0);
1479 }
1480 
1481 #undef __FUNCT__
1482 #define __FUNCT__ "SNESDefaultRhsBC"
1483 /*@
1484   SNESDefaultRhsBC - The default boundary condition function which does nothing.
1485 
1486   Not collective
1487 
1488   Input Parameters:
1489 . snes - The nonlinear solver context
1490 . rhs  - The Rhs
1491 . ctx  - The user-context
1492 
1493   Level: beginner
1494 
1495 .keywords: SNES, Rhs, boundary conditions
1496 .seealso SNESSetRhsBC(), SNESDefaultSolutionBC(), SNESDefaultUpdate()
1497 @*/
1498 int SNESDefaultRhsBC(SNES snes, Vec rhs, void *ctx)
1499 {
1500   PetscFunctionBegin;
1501   PetscFunctionReturn(0);
1502 }
1503 
1504 #undef __FUNCT__
1505 #define __FUNCT__ "SNESSetSolutionBC"
1506 /*@C
1507   SNESSetSolutionBC - Sets the function which applies boundary conditions
1508   to the solution of each system.
1509 
1510   Collective on SNES
1511 
1512   Input Parameters:
1513 . snes - The nonlinear solver context
1514 . func - The function
1515 
1516   Calling sequence of func:
1517 . func (SNES snes, Vec rsol, void *ctx);
1518 
1519 . sol - The current solution vector
1520 . ctx - The user-context
1521 
1522   Level: intermediate
1523 
1524 .keywords: SNES, solution, boundary conditions
1525 .seealso SNESDefaultSolutionBC(), SNESSetRhsBC(), SNESSetUpdate()
1526 @*/
1527 int SNESSetSolutionBC(SNES snes, int (*func)(SNES, Vec, void *))
1528 {
1529   PetscFunctionBegin;
1530   PetscValidHeaderSpecific(snes, SNES_COOKIE);
1531   snes->applysolbc = func;
1532   PetscFunctionReturn(0);
1533 }
1534 
1535 #undef __FUNCT__
1536 #define __FUNCT__ "SNESDefaultSolutionBC"
1537 /*@
1538   SNESDefaultSolutionBC - The default boundary condition function which does nothing.
1539 
1540   Not collective
1541 
1542   Input Parameters:
1543 . snes - The nonlinear solver context
1544 . sol  - The solution
1545 . ctx  - The user-context
1546 
1547   Level: beginner
1548 
1549 .keywords: SNES, solution, boundary conditions
1550 .seealso SNESSetSolutionBC(), SNESDefaultRhsBC(), SNESDefaultUpdate()
1551 @*/
1552 int SNESDefaultSolutionBC(SNES snes, Vec sol, void *ctx)
1553 {
1554   PetscFunctionBegin;
1555   PetscFunctionReturn(0);
1556 }
1557 
1558 #undef __FUNCT__
1559 #define __FUNCT__ "SNESSetUpdate"
1560 /*@C
1561   SNESSetUpdate - Sets the general-purpose update function called
1562   at the beginning of every step of the iteration.
1563 
1564   Collective on SNES
1565 
1566   Input Parameters:
1567 . snes - The nonlinear solver context
1568 . func - The function
1569 
1570   Calling sequence of func:
1571 . func (TS ts, int step);
1572 
1573 . step - The current step of the iteration
1574 
1575   Level: intermediate
1576 
1577 .keywords: SNES, update
1578 .seealso SNESDefaultUpdate(), SNESSetRhsBC(), SNESSetSolutionBC()
1579 @*/
1580 int SNESSetUpdate(SNES snes, int (*func)(SNES, int))
1581 {
1582   PetscFunctionBegin;
1583   PetscValidHeaderSpecific(snes, SNES_COOKIE);
1584   snes->update = func;
1585   PetscFunctionReturn(0);
1586 }
1587 
1588 #undef __FUNCT__
1589 #define __FUNCT__ "SNESDefaultUpdate"
1590 /*@
1591   SNESDefaultUpdate - The default update function which does nothing.
1592 
1593   Not collective
1594 
1595   Input Parameters:
1596 . snes - The nonlinear solver context
1597 . step - The current step of the iteration
1598 
1599   Level: intermediate
1600 
1601 .keywords: SNES, update
1602 .seealso SNESSetUpdate(), SNESDefaultRhsBC(), SNESDefaultSolutionBC()
1603 @*/
1604 int SNESDefaultUpdate(SNES snes, int step)
1605 {
1606   PetscFunctionBegin;
1607   PetscFunctionReturn(0);
1608 }
1609 
1610 #undef __FUNCT__
1611 #define __FUNCT__ "SNESScaleStep_Private"
1612 /*
1613    SNESScaleStep_Private - Scales a step so that its length is less than the
1614    positive parameter delta.
1615 
1616     Input Parameters:
1617 +   snes - the SNES context
1618 .   y - approximate solution of linear system
1619 .   fnorm - 2-norm of current function
1620 -   delta - trust region size
1621 
1622     Output Parameters:
1623 +   gpnorm - predicted function norm at the new point, assuming local
1624     linearization.  The value is zero if the step lies within the trust
1625     region, and exceeds zero otherwise.
1626 -   ynorm - 2-norm of the step
1627 
1628     Note:
1629     For non-trust region methods such as SNESLS, the parameter delta
1630     is set to be the maximum allowable step size.
1631 
1632 .keywords: SNES, nonlinear, scale, step
1633 */
1634 int SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
1635 {
1636   PetscReal   nrm;
1637   PetscScalar cnorm;
1638   int         ierr;
1639 
1640   PetscFunctionBegin;
1641   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1642   PetscValidHeaderSpecific(y,VEC_COOKIE);
1643   PetscCheckSameComm(snes,y);
1644 
1645   ierr = VecNorm(y,NORM_2,&nrm);CHKERRQ(ierr);
1646   if (nrm > *delta) {
1647      nrm = *delta/nrm;
1648      *gpnorm = (1.0 - nrm)*(*fnorm);
1649      cnorm = nrm;
1650      ierr = VecScale(&cnorm,y);CHKERRQ(ierr);
1651      *ynorm = *delta;
1652   } else {
1653      *gpnorm = 0.0;
1654      *ynorm = nrm;
1655   }
1656   PetscFunctionReturn(0);
1657 }
1658 
1659 #undef __FUNCT__
1660 #define __FUNCT__ "SNESSolve"
1661 /*@
1662    SNESSolve - Solves a nonlinear system.  Call SNESSolve after calling
1663    SNESCreate() and optional routines of the form SNESSetXXX().
1664 
1665    Collective on SNES
1666 
1667    Input Parameters:
1668 +  snes - the SNES context
1669 -  x - the solution vector
1670 
1671    Output Parameter:
1672 .  its - number of iterations until termination
1673 
1674    Notes:
1675    The user should initialize the vector,x, with the initial guess
1676    for the nonlinear solve prior to calling SNESSolve.  In particular,
1677    to employ an initial guess of zero, the user should explicitly set
1678    this vector to zero by calling VecSet().
1679 
1680    Level: beginner
1681 
1682 .keywords: SNES, nonlinear, solve
1683 
1684 .seealso: SNESCreate(), SNESDestroy()
1685 @*/
1686 int SNESSolve(SNES snes,Vec x,int *its)
1687 {
1688   int        ierr;
1689   PetscTruth flg;
1690 
1691   PetscFunctionBegin;
1692   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1693   PetscValidHeaderSpecific(x,VEC_COOKIE);
1694   PetscCheckSameComm(snes,x);
1695   PetscValidIntPointer(its);
1696   if (!snes->solve) SETERRQ(1,"SNESSetType() or SNESSetFromOptions() must be called before SNESSolve()");
1697 
1698   if (!snes->setupcalled) {ierr = SNESSetUp(snes,x);CHKERRQ(ierr);}
1699   else {snes->vec_sol = snes->vec_sol_always = x;}
1700   if (snes->conv_hist_reset == PETSC_TRUE) snes->conv_hist_len = 0;
1701   ierr = PetscLogEventBegin(SNES_Solve,snes,0,0,0);CHKERRQ(ierr);
1702   snes->nfuncs = 0; snes->linear_its = 0; snes->numFailures = 0;
1703   ierr = (*(snes)->solve)(snes,its);CHKERRQ(ierr);
1704   ierr = PetscLogEventEnd(SNES_Solve,snes,0,0,0);CHKERRQ(ierr);
1705   ierr = PetscOptionsHasName(snes->prefix,"-snes_view",&flg);CHKERRQ(ierr);
1706   if (flg && !PetscPreLoadingOn) { ierr = SNESView(snes,PETSC_VIEWER_STDOUT_(snes->comm));CHKERRQ(ierr); }
1707   ierr = PetscOptionsHasName(snes->prefix,"-snes_test_local_min",&flg);CHKERRQ(ierr);
1708   if (flg && !PetscPreLoadingOn) { ierr = SNESTestLocalMin(snes);CHKERRQ(ierr); }
1709   PetscFunctionReturn(0);
1710 }
1711 
1712 /* --------- Internal routines for SNES Package --------- */
1713 
1714 #undef __FUNCT__
1715 #define __FUNCT__ "SNESSetType"
1716 /*@C
1717    SNESSetType - Sets the method for the nonlinear solver.
1718 
1719    Collective on SNES
1720 
1721    Input Parameters:
1722 +  snes - the SNES context
1723 -  type - a known method
1724 
1725    Options Database Key:
1726 .  -snes_type <type> - Sets the method; use -help for a list
1727    of available methods (for instance, ls or tr)
1728 
1729    Notes:
1730    See "petsc/include/petscsnes.h" for available methods (for instance)
1731 +    SNESLS - Newton's method with line search
1732      (systems of nonlinear equations)
1733 .    SNESTR - Newton's method with trust region
1734      (systems of nonlinear equations)
1735 
1736   Normally, it is best to use the SNESSetFromOptions() command and then
1737   set the SNES solver type from the options database rather than by using
1738   this routine.  Using the options database provides the user with
1739   maximum flexibility in evaluating the many nonlinear solvers.
1740   The SNESSetType() routine is provided for those situations where it
1741   is necessary to set the nonlinear solver independently of the command
1742   line or options database.  This might be the case, for example, when
1743   the choice of solver changes during the execution of the program,
1744   and the user's application is taking responsibility for choosing the
1745   appropriate method.
1746 
1747   Level: intermediate
1748 
1749 .keywords: SNES, set, type
1750 
1751 .seealso: SNESType, SNESCreate()
1752 
1753 @*/
1754 int SNESSetType(SNES snes,const SNESType type)
1755 {
1756   int        ierr,(*r)(SNES);
1757   PetscTruth match;
1758 
1759   PetscFunctionBegin;
1760   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1761   PetscValidCharPointer(type);
1762 
1763   ierr = PetscTypeCompare((PetscObject)snes,type,&match);CHKERRQ(ierr);
1764   if (match) PetscFunctionReturn(0);
1765 
1766   if (snes->setupcalled) {
1767     ierr       = (*(snes)->destroy)(snes);CHKERRQ(ierr);
1768     snes->data = 0;
1769   }
1770 
1771   /* Get the function pointers for the iterative method requested */
1772   if (!SNESRegisterAllCalled) {ierr = SNESRegisterAll(PETSC_NULL);CHKERRQ(ierr);}
1773 
1774   ierr =  PetscFListFind(snes->comm,SNESList,type,(void (**)(void)) &r);CHKERRQ(ierr);
1775 
1776   if (!r) SETERRQ1(1,"Unable to find requested SNES type %s",type);
1777 
1778   if (snes->data) {ierr = PetscFree(snes->data);CHKERRQ(ierr);}
1779   snes->data = 0;
1780   ierr = (*r)(snes);CHKERRQ(ierr);
1781   ierr = PetscObjectChangeTypeName((PetscObject)snes,type);CHKERRQ(ierr);
1782 
1783   PetscFunctionReturn(0);
1784 }
1785 
1786 
1787 /* --------------------------------------------------------------------- */
1788 #undef __FUNCT__
1789 #define __FUNCT__ "SNESRegisterDestroy"
1790 /*@C
1791    SNESRegisterDestroy - Frees the list of nonlinear solvers that were
1792    registered by SNESRegisterDynamic().
1793 
1794    Not Collective
1795 
1796    Level: advanced
1797 
1798 .keywords: SNES, nonlinear, register, destroy
1799 
1800 .seealso: SNESRegisterAll(), SNESRegisterAll()
1801 @*/
1802 int SNESRegisterDestroy(void)
1803 {
1804   int ierr;
1805 
1806   PetscFunctionBegin;
1807   if (SNESList) {
1808     ierr = PetscFListDestroy(&SNESList);CHKERRQ(ierr);
1809     SNESList = 0;
1810   }
1811   SNESRegisterAllCalled = PETSC_FALSE;
1812   PetscFunctionReturn(0);
1813 }
1814 
1815 #undef __FUNCT__
1816 #define __FUNCT__ "SNESGetType"
1817 /*@C
1818    SNESGetType - Gets the SNES method type and name (as a string).
1819 
1820    Not Collective
1821 
1822    Input Parameter:
1823 .  snes - nonlinear solver context
1824 
1825    Output Parameter:
1826 .  type - SNES method (a character string)
1827 
1828    Level: intermediate
1829 
1830 .keywords: SNES, nonlinear, get, type, name
1831 @*/
1832 int SNESGetType(SNES snes,SNESType *type)
1833 {
1834   PetscFunctionBegin;
1835   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1836   *type = snes->type_name;
1837   PetscFunctionReturn(0);
1838 }
1839 
1840 #undef __FUNCT__
1841 #define __FUNCT__ "SNESGetSolution"
1842 /*@C
1843    SNESGetSolution - Returns the vector where the approximate solution is
1844    stored.
1845 
1846    Not Collective, but Vec is parallel if SNES is parallel
1847 
1848    Input Parameter:
1849 .  snes - the SNES context
1850 
1851    Output Parameter:
1852 .  x - the solution
1853 
1854    Level: advanced
1855 
1856 .keywords: SNES, nonlinear, get, solution
1857 
1858 .seealso: SNESGetFunction(), SNESGetSolutionUpdate()
1859 @*/
1860 int SNESGetSolution(SNES snes,Vec *x)
1861 {
1862   PetscFunctionBegin;
1863   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1864   *x = snes->vec_sol_always;
1865   PetscFunctionReturn(0);
1866 }
1867 
1868 #undef __FUNCT__
1869 #define __FUNCT__ "SNESGetSolutionUpdate"
1870 /*@C
1871    SNESGetSolutionUpdate - Returns the vector where the solution update is
1872    stored.
1873 
1874    Not Collective, but Vec is parallel if SNES is parallel
1875 
1876    Input Parameter:
1877 .  snes - the SNES context
1878 
1879    Output Parameter:
1880 .  x - the solution update
1881 
1882    Level: advanced
1883 
1884 .keywords: SNES, nonlinear, get, solution, update
1885 
1886 .seealso: SNESGetSolution(), SNESGetFunction
1887 @*/
1888 int SNESGetSolutionUpdate(SNES snes,Vec *x)
1889 {
1890   PetscFunctionBegin;
1891   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1892   *x = snes->vec_sol_update_always;
1893   PetscFunctionReturn(0);
1894 }
1895 
1896 #undef __FUNCT__
1897 #define __FUNCT__ "SNESGetFunction"
1898 /*@C
1899    SNESGetFunction - Returns the vector where the function is stored.
1900 
1901    Not Collective, but Vec is parallel if SNES is parallel
1902 
1903    Input Parameter:
1904 .  snes - the SNES context
1905 
1906    Output Parameter:
1907 +  r - the function (or PETSC_NULL)
1908 .  ctx - the function context (or PETSC_NULL)
1909 -  func - the function (or PETSC_NULL)
1910 
1911    Level: advanced
1912 
1913 .keywords: SNES, nonlinear, get, function
1914 
1915 .seealso: SNESSetFunction(), SNESGetSolution()
1916 @*/
1917 int SNESGetFunction(SNES snes,Vec *r,void **ctx,int (**func)(SNES,Vec,Vec,void*))
1918 {
1919   PetscFunctionBegin;
1920   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1921   if (r)    *r    = snes->vec_func_always;
1922   if (ctx)  *ctx  = snes->funP;
1923   if (func) *func = snes->computefunction;
1924   PetscFunctionReturn(0);
1925 }
1926 
1927 #undef __FUNCT__
1928 #define __FUNCT__ "SNESSetOptionsPrefix"
1929 /*@C
1930    SNESSetOptionsPrefix - Sets the prefix used for searching for all
1931    SNES options in the database.
1932 
1933    Collective on SNES
1934 
1935    Input Parameter:
1936 +  snes - the SNES context
1937 -  prefix - the prefix to prepend to all option names
1938 
1939    Notes:
1940    A hyphen (-) must NOT be given at the beginning of the prefix name.
1941    The first character of all runtime options is AUTOMATICALLY the hyphen.
1942 
1943    Level: advanced
1944 
1945 .keywords: SNES, set, options, prefix, database
1946 
1947 .seealso: SNESSetFromOptions()
1948 @*/
1949 int SNESSetOptionsPrefix(SNES snes,const char prefix[])
1950 {
1951   int ierr;
1952 
1953   PetscFunctionBegin;
1954   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1955   ierr = PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);CHKERRQ(ierr);
1956   ierr = KSPSetOptionsPrefix(snes->ksp,prefix);CHKERRQ(ierr);
1957   PetscFunctionReturn(0);
1958 }
1959 
1960 #undef __FUNCT__
1961 #define __FUNCT__ "SNESAppendOptionsPrefix"
1962 /*@C
1963    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
1964    SNES options in the database.
1965 
1966    Collective on SNES
1967 
1968    Input Parameters:
1969 +  snes - the SNES context
1970 -  prefix - the prefix to prepend to all option names
1971 
1972    Notes:
1973    A hyphen (-) must NOT be given at the beginning of the prefix name.
1974    The first character of all runtime options is AUTOMATICALLY the hyphen.
1975 
1976    Level: advanced
1977 
1978 .keywords: SNES, append, options, prefix, database
1979 
1980 .seealso: SNESGetOptionsPrefix()
1981 @*/
1982 int SNESAppendOptionsPrefix(SNES snes,const char prefix[])
1983 {
1984   int ierr;
1985 
1986   PetscFunctionBegin;
1987   PetscValidHeaderSpecific(snes,SNES_COOKIE);
1988   ierr = PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);CHKERRQ(ierr);
1989   ierr = KSPAppendOptionsPrefix(snes->ksp,prefix);CHKERRQ(ierr);
1990   PetscFunctionReturn(0);
1991 }
1992 
1993 #undef __FUNCT__
1994 #define __FUNCT__ "SNESGetOptionsPrefix"
1995 /*@C
1996    SNESGetOptionsPrefix - Sets the prefix used for searching for all
1997    SNES options in the database.
1998 
1999    Not Collective
2000 
2001    Input Parameter:
2002 .  snes - the SNES context
2003 
2004    Output Parameter:
2005 .  prefix - pointer to the prefix string used
2006 
2007    Notes: On the fortran side, the user should pass in a string 'prifix' of
2008    sufficient length to hold the prefix.
2009 
2010    Level: advanced
2011 
2012 .keywords: SNES, get, options, prefix, database
2013 
2014 .seealso: SNESAppendOptionsPrefix()
2015 @*/
2016 int SNESGetOptionsPrefix(SNES snes,char *prefix[])
2017 {
2018   int ierr;
2019 
2020   PetscFunctionBegin;
2021   PetscValidHeaderSpecific(snes,SNES_COOKIE);
2022   ierr = PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);CHKERRQ(ierr);
2023   PetscFunctionReturn(0);
2024 }
2025 
2026 
2027 #undef __FUNCT__
2028 #define __FUNCT__ "SNESRegister"
2029 /*@C
2030   SNESRegister - See SNESRegisterDynamic()
2031 
2032   Level: advanced
2033 @*/
2034 int SNESRegister(const char sname[],const char path[],const char name[],int (*function)(SNES))
2035 {
2036   char fullname[256];
2037   int  ierr;
2038 
2039   PetscFunctionBegin;
2040   ierr = PetscFListConcat(path,name,fullname);CHKERRQ(ierr);
2041   ierr = PetscFListAdd(&SNESList,sname,fullname,(void (*)(void))function);CHKERRQ(ierr);
2042   PetscFunctionReturn(0);
2043 }
2044 
2045 #undef __FUNCT__
2046 #define __FUNCT__ "SNESTestLocalMin"
2047 int SNESTestLocalMin(SNES snes)
2048 {
2049   int         ierr,N,i,j;
2050   Vec         u,uh,fh;
2051   PetscScalar value;
2052   PetscReal   norm;
2053 
2054   PetscFunctionBegin;
2055   ierr = SNESGetSolution(snes,&u);CHKERRQ(ierr);
2056   ierr = VecDuplicate(u,&uh);CHKERRQ(ierr);
2057   ierr = VecDuplicate(u,&fh);CHKERRQ(ierr);
2058 
2059   /* currently only works for sequential */
2060   ierr = PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
2061   ierr = VecGetSize(u,&N);CHKERRQ(ierr);
2062   for (i=0; i<N; i++) {
2063     ierr = VecCopy(u,uh);CHKERRQ(ierr);
2064     ierr  = PetscPrintf(PETSC_COMM_WORLD,"i = %d\n",i);CHKERRQ(ierr);
2065     for (j=-10; j<11; j++) {
2066       value = PetscSign(j)*exp(PetscAbs(j)-10.0);
2067       ierr  = VecSetValue(uh,i,value,ADD_VALUES);CHKERRQ(ierr);
2068       ierr  = (*snes->computefunction)(snes,uh,fh,snes->funP);CHKERRQ(ierr);
2069       ierr  = VecNorm(fh,NORM_2,&norm);CHKERRQ(ierr);
2070       ierr  = PetscPrintf(PETSC_COMM_WORLD,"       j norm %d %18.16e\n",j,norm);CHKERRQ(ierr);
2071       value = -value;
2072       ierr  = VecSetValue(uh,i,value,ADD_VALUES);CHKERRQ(ierr);
2073     }
2074   }
2075   ierr = VecDestroy(uh);CHKERRQ(ierr);
2076   ierr = VecDestroy(fh);CHKERRQ(ierr);
2077   PetscFunctionReturn(0);
2078 }
2079