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