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