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