Actual source code: snes.c

petsc-master 2019-11-16
Report Typos and Errors
  1:  #include <petsc/private/snesimpl.h>
  2:  #include <petscdmshell.h>
  3:  #include <petscdraw.h>
  4:  #include <petscds.h>
  5:  #include <petscdmadaptor.h>
  6:  #include <petscconvest.h>

  8: PetscBool         SNESRegisterAllCalled = PETSC_FALSE;
  9: PetscFunctionList SNESList              = NULL;

 11: /* Logging support */
 12: PetscClassId  SNES_CLASSID, DMSNES_CLASSID;
 13: PetscLogEvent SNES_Solve, SNES_Setup, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NPCSolve, SNES_ObjectiveEval;

 15: /*@
 16:    SNESSetErrorIfNotConverged - Causes SNESSolve() to generate an error if the solver has not converged.

 18:    Logically Collective on SNES

 20:    Input Parameters:
 21: +  snes - iterative context obtained from SNESCreate()
 22: -  flg - PETSC_TRUE indicates you want the error generated

 24:    Options database keys:
 25: .  -snes_error_if_not_converged : this takes an optional truth value (0/1/no/yes/true/false)

 27:    Level: intermediate

 29:    Notes:
 30:     Normally PETSc continues if a linear solver fails to converge, you can call SNESGetConvergedReason() after a SNESSolve()
 31:     to determine if it has converged.

 33: .seealso: SNESGetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIFNotConverged()
 34: @*/
 35: PetscErrorCode  SNESSetErrorIfNotConverged(SNES snes,PetscBool flg)
 36: {
 40:   snes->errorifnotconverged = flg;
 41:   return(0);
 42: }

 44: /*@
 45:    SNESGetErrorIfNotConverged - Will SNESSolve() generate an error if the solver does not converge?

 47:    Not Collective

 49:    Input Parameter:
 50: .  snes - iterative context obtained from SNESCreate()

 52:    Output Parameter:
 53: .  flag - PETSC_TRUE if it will generate an error, else PETSC_FALSE

 55:    Level: intermediate

 57: .seealso:  SNESSetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIFNotConverged()
 58: @*/
 59: PetscErrorCode  SNESGetErrorIfNotConverged(SNES snes,PetscBool  *flag)
 60: {
 64:   *flag = snes->errorifnotconverged;
 65:   return(0);
 66: }

 68: /*@
 69:     SNESSetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?

 71:    Logically Collective on SNES

 73:     Input Parameters:
 74: +   snes - the shell SNES
 75: -   flg - is the residual computed?

 77:    Level: advanced

 79: .seealso: SNESGetAlwaysComputesFinalResidual()
 80: @*/
 81: PetscErrorCode  SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
 82: {
 85:   snes->alwayscomputesfinalresidual = flg;
 86:   return(0);
 87: }

 89: /*@
 90:     SNESGetAlwaysComputesFinalResidual - does the SNES always compute the residual at the final solution?

 92:    Logically Collective on SNES

 94:     Input Parameter:
 95: .   snes - the shell SNES

 97:     Output Parameter:
 98: .   flg - is the residual computed?

100:    Level: advanced

102: .seealso: SNESSetAlwaysComputesFinalResidual()
103: @*/
104: PetscErrorCode  SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
105: {
108:   *flg = snes->alwayscomputesfinalresidual;
109:   return(0);
110: }

112: /*@
113:    SNESSetFunctionDomainError - tells SNES that the input vector to your SNESFunction is not
114:      in the functions domain. For example, negative pressure.

116:    Logically Collective on SNES

118:    Input Parameters:
119: .  snes - the SNES context

121:    Level: advanced

123: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction
124: @*/
125: PetscErrorCode  SNESSetFunctionDomainError(SNES snes)
126: {
129:   if (snes->errorifnotconverged) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates input vector is not in the function domain");
130:   snes->domainerror = PETSC_TRUE;
131:   return(0);
132: }

134: /*@
135:    SNESSetJacobianDomainError - tells SNES that computeJacobian does not make sense any more. For example there is a negative element transformation.

137:    Logically Collective on SNES

139:    Input Parameters:
140: .  snes - the SNES context

142:    Level: advanced

144: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError()
145: @*/
146: PetscErrorCode SNESSetJacobianDomainError(SNES snes)
147: {
150:   if (snes->errorifnotconverged) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates computeJacobian does not make sense");
151:   snes->jacobiandomainerror = PETSC_TRUE;
152:   return(0);
153: }

155: /*@
156:    SNESSetCheckJacobianDomainError - if or not to check jacobian domain error after each Jacobian evaluation. By default, we check Jacobian domain error
157:    in the debug mode, and do not check it in the optimized mode.

159:    Logically Collective on SNES

161:    Input Parameters:
162: +  snes - the SNES context
163: -  flg  - indicates if or not to check jacobian domain error after each Jacobian evaluation

165:    Level: advanced

167: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError(), SNESGetCheckJacobianDomainError()
168: @*/
169: PetscErrorCode SNESSetCheckJacobianDomainError(SNES snes, PetscBool flg)
170: {
173:   snes->checkjacdomainerror = flg;
174:   return(0);
175: }

177: /*@
178:    SNESGetCheckJacobianDomainError - Get an indicator whether or not we are checking Jacobian domain errors after each Jacobian evaluation.

180:    Logically Collective on SNES

182:    Input Parameters:
183: .  snes - the SNES context

185:    Output Parameters:
186: .  flg  - PETSC_FALSE indicates that we don't check jacobian domain errors after each Jacobian evaluation

188:    Level: advanced

190: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction(), SNESSetFunctionDomainError(), SNESSetCheckJacobianDomainError()
191: @*/
192: PetscErrorCode SNESGetCheckJacobianDomainError(SNES snes, PetscBool *flg)
193: {
197:   *flg = snes->checkjacdomainerror;
198:   return(0);
199: }

201: /*@
202:    SNESGetFunctionDomainError - Gets the status of the domain error after a call to SNESComputeFunction;

204:    Logically Collective on SNES

206:    Input Parameters:
207: .  snes - the SNES context

209:    Output Parameters:
210: .  domainerror - Set to PETSC_TRUE if there's a domain error; PETSC_FALSE otherwise.

212:    Level: advanced

214: .seealso: SNESSetFunctionDomainError(), SNESComputeFunction()
215: @*/
216: PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
217: {
221:   *domainerror = snes->domainerror;
222:   return(0);
223: }

225: /*@
226:    SNESGetJacobianDomainError - Gets the status of the Jacobian domain error after a call to SNESComputeJacobian;

228:    Logically Collective on SNES

230:    Input Parameters:
231: .  snes - the SNES context

233:    Output Parameters:
234: .  domainerror - Set to PETSC_TRUE if there's a jacobian domain error; PETSC_FALSE otherwise.

236:    Level: advanced

238: .seealso: SNESSetFunctionDomainError(), SNESComputeFunction(),SNESGetFunctionDomainError()
239: @*/
240: PetscErrorCode SNESGetJacobianDomainError(SNES snes, PetscBool *domainerror)
241: {
245:   *domainerror = snes->jacobiandomainerror;
246:   return(0);
247: }

249: /*@C
250:   SNESLoad - Loads a SNES that has been stored in binary  with SNESView().

252:   Collective on PetscViewer

254:   Input Parameters:
255: + newdm - the newly loaded SNES, this needs to have been created with SNESCreate() or
256:            some related function before a call to SNESLoad().
257: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()

259:    Level: intermediate

261:   Notes:
262:    The type is determined by the data in the file, any type set into the SNES before this call is ignored.

264:   Notes for advanced users:
265:   Most users should not need to know the details of the binary storage
266:   format, since SNESLoad() and TSView() completely hide these details.
267:   But for anyone who's interested, the standard binary matrix storage
268:   format is
269: .vb
270:      has not yet been determined
271: .ve

273: .seealso: PetscViewerBinaryOpen(), SNESView(), MatLoad(), VecLoad()
274: @*/
275: PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
276: {
278:   PetscBool      isbinary;
279:   PetscInt       classid;
280:   char           type[256];
281:   KSP            ksp;
282:   DM             dm;
283:   DMSNES         dmsnes;

288:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
289:   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");

291:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
292:   if (classid != SNES_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
293:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
294:   SNESSetType(snes, type);
295:   if (snes->ops->load) {
296:     (*snes->ops->load)(snes,viewer);
297:   }
298:   SNESGetDM(snes,&dm);
299:   DMGetDMSNES(dm,&dmsnes);
300:   DMSNESLoad(dmsnes,viewer);
301:   SNESGetKSP(snes,&ksp);
302:   KSPLoad(ksp,viewer);
303:   return(0);
304: }

306:  #include <petscdraw.h>
307: #if defined(PETSC_HAVE_SAWS)
308:  #include <petscviewersaws.h>
309: #endif

311: /*@C
312:    SNESViewFromOptions - View from Options

314:    Collective on SNES

316:    Input Parameters:
317: +  A - the application ordering context
318: .  obj - Optional object
319: -  name - command line option

321:    Level: intermediate
322: .seealso:  SNES, SNESView, PetscObjectViewFromOptions(), SNESCreate()
323: @*/
324: PetscErrorCode  SNESViewFromOptions(SNES A,PetscObject obj,const char name[])
325: {

330:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
331:   return(0);
332: }

334: PETSC_EXTERN PetscErrorCode SNESComputeJacobian_DMDA(SNES,Vec,Mat,Mat,void*);

336: /*@C
337:    SNESView - Prints the SNES data structure.

339:    Collective on SNES

341:    Input Parameters:
342: +  SNES - the SNES context
343: -  viewer - visualization context

345:    Options Database Key:
346: .  -snes_view - Calls SNESView() at end of SNESSolve()

348:    Notes:
349:    The available visualization contexts include
350: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
351: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
352:          output where only the first processor opens
353:          the file.  All other processors send their
354:          data to the first processor to print.

356:    The user can open an alternative visualization context with
357:    PetscViewerASCIIOpen() - output to a specified file.

359:    Level: beginner

361: .seealso: PetscViewerASCIIOpen()
362: @*/
363: PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
364: {
365:   SNESKSPEW      *kctx;
367:   KSP            ksp;
368:   SNESLineSearch linesearch;
369:   PetscBool      iascii,isstring,isbinary,isdraw;
370:   DMSNES         dmsnes;
371: #if defined(PETSC_HAVE_SAWS)
372:   PetscBool      issaws;
373: #endif

377:   if (!viewer) {
378:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer);
379:   }

383:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
384:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
385:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
386:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
387: #if defined(PETSC_HAVE_SAWS)
388:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
389: #endif
390:   if (iascii) {
391:     SNESNormSchedule normschedule;
392:     DM               dm;
393:     PetscErrorCode   (*cJ)(SNES,Vec,Mat,Mat,void*);
394:     void             *ctx;
395:     const char       *pre = "";

397:     PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer);
398:     if (!snes->setupcalled) {
399:       PetscViewerASCIIPrintf(viewer,"  SNES has not been set up so information may be incomplete\n");
400:     }
401:     if (snes->ops->view) {
402:       PetscViewerASCIIPushTab(viewer);
403:       (*snes->ops->view)(snes,viewer);
404:       PetscViewerASCIIPopTab(viewer);
405:     }
406:     PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, maximum function evaluations=%D\n",snes->max_its,snes->max_funcs);
407:     PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol);
408:     if (snes->usesksp) {
409:       PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",snes->linear_its);
410:     }
411:     PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%D\n",snes->nfuncs);
412:     SNESGetNormSchedule(snes, &normschedule);
413:     if (normschedule > 0) {PetscViewerASCIIPrintf(viewer,"  norm schedule %s\n",SNESNormSchedules[normschedule]);}
414:     if (snes->gridsequence) {
415:       PetscViewerASCIIPrintf(viewer,"  total number of grid sequence refinements=%D\n",snes->gridsequence);
416:     }
417:     if (snes->ksp_ewconv) {
418:       kctx = (SNESKSPEW*)snes->kspconvctx;
419:       if (kctx) {
420:         PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %D)\n",kctx->version);
421:         PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold);
422:         PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2);
423:       }
424:     }
425:     if (snes->lagpreconditioner == -1) {
426:       PetscViewerASCIIPrintf(viewer,"  Preconditioned is never rebuilt\n");
427:     } else if (snes->lagpreconditioner > 1) {
428:       PetscViewerASCIIPrintf(viewer,"  Preconditioned is rebuilt every %D new Jacobians\n",snes->lagpreconditioner);
429:     }
430:     if (snes->lagjacobian == -1) {
431:       PetscViewerASCIIPrintf(viewer,"  Jacobian is never rebuilt\n");
432:     } else if (snes->lagjacobian > 1) {
433:       PetscViewerASCIIPrintf(viewer,"  Jacobian is rebuilt every %D SNES iterations\n",snes->lagjacobian);
434:     }
435:     SNESGetDM(snes,&dm);
436:     DMSNESGetJacobian(dm,&cJ,&ctx);
437:     if (snes->mf_operator) {
438:       PetscViewerASCIIPrintf(viewer,"  Jacobian is applied matrix-free with differencing\n");
439:       pre  = "Preconditioning ";
440:     }
441:     if (cJ == SNESComputeJacobianDefault) {
442:       PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using finite differences one column at a time\n",pre);
443:     } else if (cJ == SNESComputeJacobianDefaultColor) {
444:       PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using finite differences with coloring\n",pre);
445:     /* it slightly breaks data encapsulation for access the DMDA information directly */
446:     } else if (cJ == SNESComputeJacobian_DMDA) {
447:       MatFDColoring fdcoloring;
448:       PetscObjectQuery((PetscObject)dm,"DMDASNES_FDCOLORING",(PetscObject*)&fdcoloring);
449:       if (fdcoloring) {
450:         PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using colored finite differences on a DMDA\n",pre);
451:       } else {
452:         PetscViewerASCIIPrintf(viewer,"  %sJacobian is built using a DMDA local Jacobian\n",pre);
453:       }
454:     } else if (snes->mf) {
455:       PetscViewerASCIIPrintf(viewer,"  Jacobian is applied matrix-free with differencing, no explict Jacobian\n");
456:     }
457:   } else if (isstring) {
458:     const char *type;
459:     SNESGetType(snes,&type);
460:     PetscViewerStringSPrintf(viewer," SNESType: %-7.7s",type);
461:     if (snes->ops->view) {(*snes->ops->view)(snes,viewer);}
462:   } else if (isbinary) {
463:     PetscInt    classid = SNES_FILE_CLASSID;
464:     MPI_Comm    comm;
465:     PetscMPIInt rank;
466:     char        type[256];

468:     PetscObjectGetComm((PetscObject)snes,&comm);
469:     MPI_Comm_rank(comm,&rank);
470:     if (!rank) {
471:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
472:       PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));
473:       PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR,PETSC_FALSE);
474:     }
475:     if (snes->ops->view) {
476:       (*snes->ops->view)(snes,viewer);
477:     }
478:   } else if (isdraw) {
479:     PetscDraw draw;
480:     char      str[36];
481:     PetscReal x,y,bottom,h;

483:     PetscViewerDrawGetDraw(viewer,0,&draw);
484:     PetscDrawGetCurrentPoint(draw,&x,&y);
485:     PetscStrncpy(str,"SNES: ",sizeof(str));
486:     PetscStrlcat(str,((PetscObject)snes)->type_name,sizeof(str));
487:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h);
488:     bottom = y - h;
489:     PetscDrawPushCurrentPoint(draw,x,bottom);
490:     if (snes->ops->view) {
491:       (*snes->ops->view)(snes,viewer);
492:     }
493: #if defined(PETSC_HAVE_SAWS)
494:   } else if (issaws) {
495:     PetscMPIInt rank;
496:     const char *name;

498:     PetscObjectGetName((PetscObject)snes,&name);
499:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
500:     if (!((PetscObject)snes)->amsmem && !rank) {
501:       char       dir[1024];

503:       PetscObjectViewSAWs((PetscObject)snes,viewer);
504:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);
505:       PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
506:       if (!snes->conv_hist) {
507:         SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE);
508:       }
509:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name);
510:       PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
511:     }
512: #endif
513:   }
514:   if (snes->linesearch) {
515:     SNESGetLineSearch(snes, &linesearch);
516:     PetscViewerASCIIPushTab(viewer);
517:     SNESLineSearchView(linesearch, viewer);
518:     PetscViewerASCIIPopTab(viewer);
519:   }
520:   if (snes->npc && snes->usesnpc) {
521:     PetscViewerASCIIPushTab(viewer);
522:     SNESView(snes->npc, viewer);
523:     PetscViewerASCIIPopTab(viewer);
524:   }
525:   PetscViewerASCIIPushTab(viewer);
526:   DMGetDMSNES(snes->dm,&dmsnes);
527:   DMSNESView(dmsnes, viewer);
528:   PetscViewerASCIIPopTab(viewer);
529:   if (snes->usesksp) {
530:     SNESGetKSP(snes,&ksp);
531:     PetscViewerASCIIPushTab(viewer);
532:     KSPView(ksp,viewer);
533:     PetscViewerASCIIPopTab(viewer);
534:   }
535:   if (isdraw) {
536:     PetscDraw draw;
537:     PetscViewerDrawGetDraw(viewer,0,&draw);
538:     PetscDrawPopCurrentPoint(draw);
539:   }
540:   return(0);
541: }

543: /*
544:   We retain a list of functions that also take SNES command
545:   line options. These are called at the end SNESSetFromOptions()
546: */
547: #define MAXSETFROMOPTIONS 5
548: static PetscInt numberofsetfromoptions;
549: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);

551: /*@C
552:   SNESAddOptionsChecker - Adds an additional function to check for SNES options.

554:   Not Collective

556:   Input Parameter:
557: . snescheck - function that checks for options

559:   Level: developer

561: .seealso: SNESSetFromOptions()
562: @*/
563: PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
564: {
566:   if (numberofsetfromoptions >= MAXSETFROMOPTIONS) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %D allowed", MAXSETFROMOPTIONS);
567:   othersetfromoptions[numberofsetfromoptions++] = snescheck;
568:   return(0);
569: }

571: PETSC_INTERN PetscErrorCode SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*);

573: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
574: {
575:   Mat            J;
577:   MatNullSpace   nullsp;


582:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
583:     Mat A = snes->jacobian, B = snes->jacobian_pre;
584:     MatCreateVecs(A ? A : B, NULL,&snes->vec_func);
585:   }

587:   if (version == 1) {
588:     MatCreateSNESMF(snes,&J);
589:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
590:     MatSetFromOptions(J);
591:   } else if (version == 2) {
592:     if (!snes->vec_func) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
593: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
594:     SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J);
595: #else
596:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator rutines (version 2)");
597: #endif
598:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator rutines, only version 1 and 2");

600:   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
601:   if (snes->jacobian) {
602:     MatGetNullSpace(snes->jacobian,&nullsp);
603:     if (nullsp) {
604:       MatSetNullSpace(J,nullsp);
605:     }
606:   }

608:   PetscInfo1(snes,"Setting default matrix-free operator routines (version %D)\n", version);
609:   if (hasOperator) {

611:     /* This version replaces the user provided Jacobian matrix with a
612:        matrix-free version but still employs the user-provided preconditioner matrix. */
613:     SNESSetJacobian(snes,J,0,0,0);
614:   } else {
615:     /* This version replaces both the user-provided Jacobian and the user-
616:      provided preconditioner Jacobian with the default matrix free version. */
617:     if ((snes->npcside== PC_LEFT) && snes->npc) {
618:       if (!snes->jacobian){SNESSetJacobian(snes,J,0,0,0);}
619:     } else {
620:       KSP       ksp;
621:       PC        pc;
622:       PetscBool match;

624:       SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,0);
625:       /* Force no preconditioner */
626:       SNESGetKSP(snes,&ksp);
627:       KSPGetPC(ksp,&pc);
628:       PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&match);
629:       if (!match) {
630:         PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n");
631:         PCSetType(pc,PCNONE);
632:       }
633:     }
634:   }
635:   MatDestroy(&J);
636:   return(0);
637: }

639: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
640: {
641:   SNES           snes = (SNES)ctx;
643:   Vec            Xfine,Xfine_named = NULL,Xcoarse;

646:   if (PetscLogPrintInfo) {
647:     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
648:     DMGetRefineLevel(dmfine,&finelevel);
649:     DMGetCoarsenLevel(dmfine,&fineclevel);
650:     DMGetRefineLevel(dmcoarse,&coarselevel);
651:     DMGetCoarsenLevel(dmcoarse,&coarseclevel);
652:     PetscInfo4(dmfine,"Restricting SNES solution vector from level %D-%D to level %D-%D\n",finelevel,fineclevel,coarselevel,coarseclevel);
653:   }
654:   if (dmfine == snes->dm) Xfine = snes->vec_sol;
655:   else {
656:     DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);
657:     Xfine = Xfine_named;
658:   }
659:   DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
660:   if (Inject) {
661:     MatRestrict(Inject,Xfine,Xcoarse);
662:   } else {
663:     MatRestrict(Restrict,Xfine,Xcoarse);
664:     VecPointwiseMult(Xcoarse,Xcoarse,Rscale);
665:   }
666:   DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
667:   if (Xfine_named) {DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);}
668:   return(0);
669: }

671: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
672: {

676:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
677:   return(0);
678: }

680: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
681:  * safely call SNESGetDM() in their residual evaluation routine. */
682: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
683: {
684:   SNES           snes = (SNES)ctx;
686:   Vec            X,Xnamed = NULL;
687:   DM             dmsave;
688:   void           *ctxsave;
689:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL;

692:   dmsave = snes->dm;
693:   KSPGetDM(ksp,&snes->dm);
694:   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
695:   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
696:     DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
697:     X    = Xnamed;
698:     SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave);
699:     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
700:     if (jac == SNESComputeJacobianDefaultColor) {
701:       SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,0);
702:     }
703:   }
704:   /* Make sure KSP DM has the Jacobian computation routine */
705:   {
706:     DMSNES sdm;

708:     DMGetDMSNES(snes->dm, &sdm);
709:     if (!sdm->ops->computejacobian) {
710:       DMCopyDMSNES(dmsave, snes->dm);
711:     }
712:   }
713:   /* Compute the operators */
714:   SNESComputeJacobian(snes,X,A,B);
715:   /* Put the previous context back */
716:   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
717:     SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);
718:   }

720:   if (Xnamed) {DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);}
721:   snes->dm = dmsave;
722:   return(0);
723: }

725: /*@
726:    SNESSetUpMatrices - ensures that matrices are available for SNES, to be called by SNESSetUp_XXX()

728:    Collective

730:    Input Arguments:
731: .  snes - snes to configure

733:    Level: developer

735: .seealso: SNESSetUp()
736: @*/
737: PetscErrorCode SNESSetUpMatrices(SNES snes)
738: {
740:   DM             dm;
741:   DMSNES         sdm;

744:   SNESGetDM(snes,&dm);
745:   DMGetDMSNES(dm,&sdm);
746:   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_PLIB,"DMSNES not properly configured");
747:   else if (!snes->jacobian && snes->mf) {
748:     Mat  J;
749:     void *functx;
750:     MatCreateSNESMF(snes,&J);
751:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
752:     MatSetFromOptions(J);
753:     SNESGetFunction(snes,NULL,NULL,&functx);
754:     SNESSetJacobian(snes,J,J,0,0);
755:     MatDestroy(&J);
756:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
757:     Mat J,B;
758:     MatCreateSNESMF(snes,&J);
759:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
760:     MatSetFromOptions(J);
761:     DMCreateMatrix(snes->dm,&B);
762:     /* sdm->computejacobian was already set to reach here */
763:     SNESSetJacobian(snes,J,B,NULL,NULL);
764:     MatDestroy(&J);
765:     MatDestroy(&B);
766:   } else if (!snes->jacobian_pre) {
767:     PetscErrorCode (*nspconstr)(DM, PetscInt, MatNullSpace *);
768:     PetscDS          prob;
769:     Mat              J, B;
770:     MatNullSpace     nullspace = NULL;
771:     PetscBool        hasPrec   = PETSC_FALSE;
772:     PetscInt         Nf;

774:     J    = snes->jacobian;
775:     DMGetDS(dm, &prob);
776:     if (prob) {PetscDSHasJacobianPreconditioner(prob, &hasPrec);}
777:     if (J)            {PetscObjectReference((PetscObject) J);}
778:     else if (hasPrec) {DMCreateMatrix(snes->dm, &J);}
779:     DMCreateMatrix(snes->dm, &B);
780:     PetscDSGetNumFields(prob, &Nf);
781:     DMGetNullSpaceConstructor(snes->dm, Nf, &nspconstr);
782:     if (nspconstr) (*nspconstr)(snes->dm, -1, &nullspace);
783:     MatSetNullSpace(B, nullspace);
784:     MatNullSpaceDestroy(&nullspace);
785:     SNESSetJacobian(snes, J ? J : B, B, NULL, NULL);
786:     MatDestroy(&J);
787:     MatDestroy(&B);
788:   }
789:   {
790:     KSP ksp;
791:     SNESGetKSP(snes,&ksp);
792:     KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);
793:     DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
794:   }
795:   return(0);
796: }

798: /*@C
799:    SNESMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

801:    Collective on SNES

803:    Input Parameters:
804: +  snes - SNES object you wish to monitor
805: .  name - the monitor type one is seeking
806: .  help - message indicating what monitoring is done
807: .  manual - manual page for the monitor
808: .  monitor - the monitor function
809: -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the SNES or PetscViewer objects

811:    Level: developer

813: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
814:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
815:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
816:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
817:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
818:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
819:           PetscOptionsFList(), PetscOptionsEList()
820: @*/
821: PetscErrorCode  SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
822: {
823:   PetscErrorCode    ierr;
824:   PetscViewer       viewer;
825:   PetscViewerFormat format;
826:   PetscBool         flg;

829:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,name,&viewer,&format,&flg);
830:   if (flg) {
831:     PetscViewerAndFormat *vf;
832:     PetscViewerAndFormatCreate(viewer,format,&vf);
833:     PetscObjectDereference((PetscObject)viewer);
834:     if (monitorsetup) {
835:       (*monitorsetup)(snes,vf);
836:     }
837:     SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
838:   }
839:   return(0);
840: }

842: /*@
843:    SNESSetFromOptions - Sets various SNES and KSP parameters from user options.

845:    Collective on SNES

847:    Input Parameter:
848: .  snes - the SNES context

850:    Options Database Keys:
851: +  -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
852: .  -snes_stol - convergence tolerance in terms of the norm
853:                 of the change in the solution between steps
854: .  -snes_atol <abstol> - absolute tolerance of residual norm
855: .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
856: .  -snes_divergence_tolerance <divtol> - if the residual goes above divtol*rnorm0, exit with divergence
857: .  -snes_force_iteration <force> - force SNESSolve() to take at least one iteration
858: .  -snes_max_it <max_it> - maximum number of iterations
859: .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
860: .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
861: .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
862: .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
863: .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
864: .  -snes_trtol <trtol> - trust region tolerance
865: .  -snes_no_convergence_test - skip convergence test in nonlinear
866:                                solver; hence iterations will continue until max_it
867:                                or some other criterion is reached. Saves expense
868:                                of convergence test
869: .  -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
870: .  -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
871: .  -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
872: .  -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
873: .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
874: .  -snes_monitor_lg_range - plots residual norm at each iteration
875: .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
876: .  -snes_fd_color - use finite differences with coloring to compute Jacobian
877: .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
878: .  -snes_converged_reason - print the reason for convergence/divergence after each solve
879: -  -npc_snes_type <type> - the SNES type to use as a nonlinear preconditioner

881:     Options Database for Eisenstat-Walker method:
882: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
883: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
884: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
885: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
886: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
887: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
888: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
889: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

891:    Notes:
892:    To see all options, run your program with the -help option or consult
893:    Users-Manual: ch_snes

895:    Level: beginner

897: .seealso: SNESSetOptionsPrefix(), SNESResetFromOptions()
898: @*/
899: PetscErrorCode  SNESSetFromOptions(SNES snes)
900: {
901:   PetscBool      flg,pcset,persist,set;
902:   PetscInt       i,indx,lag,grids;
903:   const char     *deft        = SNESNEWTONLS;
904:   const char     *convtests[] = {"default","skip"};
905:   SNESKSPEW      *kctx        = NULL;
906:   char           type[256], monfilename[PETSC_MAX_PATH_LEN];
908:   PCSide         pcside;
909:   const char     *optionsprefix;

913:   SNESRegisterAll();
914:   PetscObjectOptionsBegin((PetscObject)snes);
915:   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
916:   PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg);
917:   if (flg) {
918:     SNESSetType(snes,type);
919:   } else if (!((PetscObject)snes)->type_name) {
920:     SNESSetType(snes,deft);
921:   }
922:   PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL);
923:   PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL);

925:   PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL);
926:   PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL);
927:   PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL);
928:   PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL);
929:   PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL);
930:   PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL);
931:   PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL);
932:   PetscOptionsBool("-snes_force_iteration","Force SNESSolve() to take at least one iteration","SNESSetForceIteration",snes->forceiteration,&snes->forceiteration,NULL);
933:   PetscOptionsBool("-snes_check_jacobian_domain_error","Check Jacobian domain error after Jacobian evaluation","SNESCheckJacobianDomainError",snes->checkjacdomainerror,&snes->checkjacdomainerror,NULL);

935:   PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg);
936:   if (flg) {
937:     SNESSetLagPreconditioner(snes,lag);
938:   }
939:   PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg);
940:   if (flg) {
941:     SNESSetLagPreconditionerPersists(snes,persist);
942:   }
943:   PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg);
944:   if (flg) {
945:     SNESSetLagJacobian(snes,lag);
946:   }
947:   PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg);
948:   if (flg) {
949:     SNESSetLagJacobianPersists(snes,persist);
950:   }

952:   PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg);
953:   if (flg) {
954:     SNESSetGridSequence(snes,grids);
955:   }

957:   PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,2,"default",&indx,&flg);
958:   if (flg) {
959:     switch (indx) {
960:     case 0: SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL); break;
961:     case 1: SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL);    break;
962:     }
963:   }

965:   PetscOptionsEList("-snes_norm_schedule","SNES Norm schedule","SNESSetNormSchedule",SNESNormSchedules,5,"function",&indx,&flg);
966:   if (flg) { SNESSetNormSchedule(snes,(SNESNormSchedule)indx); }

968:   PetscOptionsEList("-snes_function_type","SNES Norm schedule","SNESSetFunctionType",SNESFunctionTypes,2,"unpreconditioned",&indx,&flg);
969:   if (flg) { SNESSetFunctionType(snes,(SNESFunctionType)indx); }

971:   kctx = (SNESKSPEW*)snes->kspconvctx;

973:   PetscOptionsBool("-snes_ksp_ew","Use Eisentat-Walker linear system convergence test","SNESKSPSetUseEW",snes->ksp_ewconv,&snes->ksp_ewconv,NULL);

975:   PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL);
976:   PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL);
977:   PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL);
978:   PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL);
979:   PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL);
980:   PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL);
981:   PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL);

983:   flg  = PETSC_FALSE;
984:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
985:   if (set && flg) {SNESMonitorCancel(snes);}

987:   SNESMonitorSetFromOptions(snes,"-snes_monitor","Monitor norm of function","SNESMonitorDefault",SNESMonitorDefault,NULL);
988:   SNESMonitorSetFromOptions(snes,"-snes_monitor_short","Monitor norm of function with fewer digits","SNESMonitorDefaultShort",SNESMonitorDefaultShort,NULL);
989:   SNESMonitorSetFromOptions(snes,"-snes_monitor_range","Monitor range of elements of function","SNESMonitorRange",SNESMonitorRange,NULL);

991:   SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp);
992:   SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL);
993:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL);
994:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL);
995:   SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL);
996:   SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL);
997:   SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL);

999:   PetscOptionsString("-snes_monitor_python","Use Python function","SNESMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
1000:   if (flg) {PetscPythonMonitorSet((PetscObject)snes,monfilename);}

1002:   flg  = PETSC_FALSE;
1003:   PetscOptionsBool("-snes_monitor_lg_residualnorm","Plot function norm at each iteration","SNESMonitorLGResidualNorm",flg,&flg,NULL);
1004:   if (flg) {
1005:     PetscDrawLG ctx;

1007:     SNESMonitorLGCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
1008:     SNESMonitorSet(snes,SNESMonitorLGResidualNorm,ctx,(PetscErrorCode (*)(void**))PetscDrawLGDestroy);
1009:   }
1010:   flg  = PETSC_FALSE;
1011:   PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);
1012:   if (flg) {
1013:     PetscViewer ctx;

1015:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
1016:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
1017:   }

1019:   flg  = PETSC_FALSE;
1020:   PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);
1021:   if (flg) {
1022:     void    *functx;
1023:     DM      dm;
1024:     DMSNES  sdm;
1025:     SNESGetDM(snes,&dm);
1026:     DMGetDMSNES(dm,&sdm);
1027:     sdm->jacobianctx = NULL;
1028:     SNESGetFunction(snes,NULL,NULL,&functx);
1029:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);
1030:     PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");
1031:   }

1033:   flg  = PETSC_FALSE;
1034:   PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);
1035:   if (flg) {
1036:     SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);
1037:   }

1039:   flg  = PETSC_FALSE;
1040:   PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL);
1041:   if (flg) {
1042:     DM             dm;
1043:     DMSNES         sdm;
1044:     SNESGetDM(snes,&dm);
1045:     DMGetDMSNES(dm,&sdm);
1046:     sdm->jacobianctx = NULL;
1047:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,0);
1048:     PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n");
1049:   }

1051:   flg  = PETSC_FALSE;
1052:   PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg);
1053:   if (flg && snes->mf_operator) {
1054:     snes->mf_operator = PETSC_TRUE;
1055:     snes->mf          = PETSC_TRUE;
1056:   }
1057:   flg  = PETSC_FALSE;
1058:   PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg);
1059:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
1060:   PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,0);

1062:   flg  = PETSC_FALSE;
1063:   SNESGetNPCSide(snes,&pcside);
1064:   PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);
1065:   if (flg) {SNESSetNPCSide(snes,pcside);}

1067: #if defined(PETSC_HAVE_SAWS)
1068:   /*
1069:     Publish convergence information using SAWs
1070:   */
1071:   flg  = PETSC_FALSE;
1072:   PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL);
1073:   if (flg) {
1074:     void *ctx;
1075:     SNESMonitorSAWsCreate(snes,&ctx);
1076:     SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy);
1077:   }
1078: #endif
1079: #if defined(PETSC_HAVE_SAWS)
1080:   {
1081:   PetscBool set;
1082:   flg  = PETSC_FALSE;
1083:   PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set);
1084:   if (set) {
1085:     PetscObjectSAWsSetBlock((PetscObject)snes,flg);
1086:   }
1087:   }
1088: #endif

1090:   for (i = 0; i < numberofsetfromoptions; i++) {
1091:     (*othersetfromoptions[i])(snes);
1092:   }

1094:   if (snes->ops->setfromoptions) {
1095:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
1096:   }

1098:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1099:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
1100:   PetscOptionsEnd();

1102:   if (snes->linesearch) {
1103:     SNESGetLineSearch(snes, &snes->linesearch);
1104:     SNESLineSearchSetFromOptions(snes->linesearch);
1105:   }

1107:   if (snes->usesksp) {
1108:     if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
1109:     KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
1110:     KSPSetFromOptions(snes->ksp);
1111:   }

1113:   /* if user has set the SNES NPC type via options database, create it. */
1114:   SNESGetOptionsPrefix(snes, &optionsprefix);
1115:   PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset);
1116:   if (pcset && (!snes->npc)) {
1117:     SNESGetNPC(snes, &snes->npc);
1118:   }
1119:   if (snes->npc) {
1120:     SNESSetFromOptions(snes->npc);
1121:   }
1122:   snes->setfromoptionscalled++;
1123:   return(0);
1124: }

1126: /*@
1127:    SNESResetFromOptions - Sets various SNES and KSP parameters from user options ONLY if the SNES was previously set from options

1129:    Collective on SNES

1131:    Input Parameter:
1132: .  snes - the SNES context

1134:    Level: beginner

1136: .seealso: SNESSetFromOptions(), SNESSetOptionsPrefix()
1137: @*/
1138: PetscErrorCode SNESResetFromOptions(SNES snes)
1139: {

1143:   if (snes->setfromoptionscalled) {SNESSetFromOptions(snes);}
1144:   return(0);
1145: }

1147: /*@C
1148:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1149:    the nonlinear solvers.

1151:    Logically Collective on SNES

1153:    Input Parameters:
1154: +  snes - the SNES context
1155: .  compute - function to compute the context
1156: -  destroy - function to destroy the context

1158:    Level: intermediate

1160:    Notes:
1161:    This function is currently not available from Fortran.

1163: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1164: @*/
1165: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1166: {
1169:   snes->ops->usercompute = compute;
1170:   snes->ops->userdestroy = destroy;
1171:   return(0);
1172: }

1174: /*@
1175:    SNESSetApplicationContext - Sets the optional user-defined context for
1176:    the nonlinear solvers.

1178:    Logically Collective on SNES

1180:    Input Parameters:
1181: +  snes - the SNES context
1182: -  usrP - optional user context

1184:    Level: intermediate

1186:    Fortran Notes:
1187:     To use this from Fortran you must write a Fortran interface definition for this
1188:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

1190: .seealso: SNESGetApplicationContext()
1191: @*/
1192: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1193: {
1195:   KSP            ksp;

1199:   SNESGetKSP(snes,&ksp);
1200:   KSPSetApplicationContext(ksp,usrP);
1201:   snes->user = usrP;
1202:   return(0);
1203: }

1205: /*@
1206:    SNESGetApplicationContext - Gets the user-defined context for the
1207:    nonlinear solvers.

1209:    Not Collective

1211:    Input Parameter:
1212: .  snes - SNES context

1214:    Output Parameter:
1215: .  usrP - user context

1217:    Fortran Notes:
1218:     To use this from Fortran you must write a Fortran interface definition for this
1219:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

1221:    Level: intermediate

1223: .seealso: SNESSetApplicationContext()
1224: @*/
1225: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1226: {
1229:   *(void**)usrP = snes->user;
1230:   return(0);
1231: }

1233: /*@
1234:    SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply
1235:                           the Jacobian.

1237:    Collective on SNES

1239:    Input Parameters:
1240: +  snes - SNES context
1241: .  mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
1242: -  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used

1244:    Options Database:
1245: + -snes_mf - use matrix free for both the mat and pmat operator
1246: - -snes_mf_operator - use matrix free only for the mat operator

1248:    Level: intermediate

1250: .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF()
1251: @*/
1252: PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1253: {
1258:   if (mf && !mf_operator) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"If using mf must also use mf_operator");
1259:   snes->mf          = mf;
1260:   snes->mf_operator = mf_operator;
1261:   return(0);
1262: }

1264: /*@
1265:    SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply
1266:                           the Jacobian.

1268:    Collective on SNES

1270:    Input Parameter:
1271: .  snes - SNES context

1273:    Output Parameters:
1274: +  mf - use matrix-free for both the Amat and Pmat used by SNESSetJacobian(), both the Amat and Pmat set in SNESSetJacobian() will be ignored
1275: -  mf_operator - use matrix-free only for the Amat used by SNESSetJacobian(), this means the user provided Pmat will continue to be used

1277:    Options Database:
1278: + -snes_mf - use matrix free for both the mat and pmat operator
1279: - -snes_mf_operator - use matrix free only for the mat operator

1281:    Level: intermediate

1283: .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
1284: @*/
1285: PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1286: {
1289:   if (mf)          *mf          = snes->mf;
1290:   if (mf_operator) *mf_operator = snes->mf_operator;
1291:   return(0);
1292: }

1294: /*@
1295:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1296:    at this time.

1298:    Not Collective

1300:    Input Parameter:
1301: .  snes - SNES context

1303:    Output Parameter:
1304: .  iter - iteration number

1306:    Notes:
1307:    For example, during the computation of iteration 2 this would return 1.

1309:    This is useful for using lagged Jacobians (where one does not recompute the
1310:    Jacobian at each SNES iteration). For example, the code
1311: .vb
1312:       SNESGetIterationNumber(snes,&it);
1313:       if (!(it % 2)) {
1314:         [compute Jacobian here]
1315:       }
1316: .ve
1317:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1318:    recomputed every second SNES iteration.

1320:    After the SNES solve is complete this will return the number of nonlinear iterations used.

1322:    Level: intermediate

1324: .seealso:   SNESGetLinearSolveIterations()
1325: @*/
1326: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1327: {
1331:   *iter = snes->iter;
1332:   return(0);
1333: }

1335: /*@
1336:    SNESSetIterationNumber - Sets the current iteration number.

1338:    Not Collective

1340:    Input Parameter:
1341: +  snes - SNES context
1342: -  iter - iteration number

1344:    Level: developer

1346: .seealso:   SNESGetLinearSolveIterations()
1347: @*/
1348: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1349: {

1354:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1355:   snes->iter = iter;
1356:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1357:   return(0);
1358: }

1360: /*@
1361:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1362:    attempted by the nonlinear solver.

1364:    Not Collective

1366:    Input Parameter:
1367: .  snes - SNES context

1369:    Output Parameter:
1370: .  nfails - number of unsuccessful steps attempted

1372:    Notes:
1373:    This counter is reset to zero for each successive call to SNESSolve().

1375:    Level: intermediate

1377: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1378:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1379: @*/
1380: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1381: {
1385:   *nfails = snes->numFailures;
1386:   return(0);
1387: }

1389: /*@
1390:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1391:    attempted by the nonlinear solver before it gives up.

1393:    Not Collective

1395:    Input Parameters:
1396: +  snes     - SNES context
1397: -  maxFails - maximum of unsuccessful steps

1399:    Level: intermediate

1401: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1402:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1403: @*/
1404: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1405: {
1408:   snes->maxFailures = maxFails;
1409:   return(0);
1410: }

1412: /*@
1413:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1414:    attempted by the nonlinear solver before it gives up.

1416:    Not Collective

1418:    Input Parameter:
1419: .  snes     - SNES context

1421:    Output Parameter:
1422: .  maxFails - maximum of unsuccessful steps

1424:    Level: intermediate

1426: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1427:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1429: @*/
1430: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1431: {
1435:   *maxFails = snes->maxFailures;
1436:   return(0);
1437: }

1439: /*@
1440:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1441:      done by SNES.

1443:    Not Collective

1445:    Input Parameter:
1446: .  snes     - SNES context

1448:    Output Parameter:
1449: .  nfuncs - number of evaluations

1451:    Level: intermediate

1453:    Notes:
1454:     Reset every time SNESSolve is called unless SNESSetCountersReset() is used.

1456: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1457: @*/
1458: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1459: {
1463:   *nfuncs = snes->nfuncs;
1464:   return(0);
1465: }

1467: /*@
1468:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1469:    linear solvers.

1471:    Not Collective

1473:    Input Parameter:
1474: .  snes - SNES context

1476:    Output Parameter:
1477: .  nfails - number of failed solves

1479:    Level: intermediate

1481:    Options Database Keys:
1482: . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated

1484:    Notes:
1485:    This counter is reset to zero for each successive call to SNESSolve().

1487: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1488: @*/
1489: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1490: {
1494:   *nfails = snes->numLinearSolveFailures;
1495:   return(0);
1496: }

1498: /*@
1499:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1500:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1502:    Logically Collective on SNES

1504:    Input Parameters:
1505: +  snes     - SNES context
1506: -  maxFails - maximum allowed linear solve failures

1508:    Level: intermediate

1510:    Options Database Keys:
1511: . -snes_max_linear_solve_fail <num> - The number of failures before the solve is terminated

1513:    Notes:
1514:     By default this is 0; that is SNES returns on the first failed linear solve

1516: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1517: @*/
1518: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1519: {
1523:   snes->maxLinearSolveFailures = maxFails;
1524:   return(0);
1525: }

1527: /*@
1528:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1529:      are allowed before SNES terminates

1531:    Not Collective

1533:    Input Parameter:
1534: .  snes     - SNES context

1536:    Output Parameter:
1537: .  maxFails - maximum of unsuccessful solves allowed

1539:    Level: intermediate

1541:    Notes:
1542:     By default this is 1; that is SNES returns on the first failed linear solve

1544: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1545: @*/
1546: PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1547: {
1551:   *maxFails = snes->maxLinearSolveFailures;
1552:   return(0);
1553: }

1555: /*@
1556:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1557:    used by the nonlinear solver.

1559:    Not Collective

1561:    Input Parameter:
1562: .  snes - SNES context

1564:    Output Parameter:
1565: .  lits - number of linear iterations

1567:    Notes:
1568:    This counter is reset to zero for each successive call to SNESSolve() unless SNESSetCountersReset() is used.

1570:    If the linear solver fails inside the SNESSolve() the iterations for that call to the linear solver are not included. If you wish to count them
1571:    then call KSPGetIterationNumber() after the failed solve.

1573:    Level: intermediate

1575: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1576: @*/
1577: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1578: {
1582:   *lits = snes->linear_its;
1583:   return(0);
1584: }

1586: /*@
1587:    SNESSetCountersReset - Sets whether or not the counters for linear iterations and function evaluations
1588:    are reset every time SNESSolve() is called.

1590:    Logically Collective on SNES

1592:    Input Parameter:
1593: +  snes - SNES context
1594: -  reset - whether to reset the counters or not

1596:    Notes:
1597:    This defaults to PETSC_TRUE

1599:    Level: developer

1601: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1602: @*/
1603: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1604: {
1608:   snes->counters_reset = reset;
1609:   return(0);
1610: }


1613: /*@
1614:    SNESSetKSP - Sets a KSP context for the SNES object to use

1616:    Not Collective, but the SNES and KSP objects must live on the same MPI_Comm

1618:    Input Parameters:
1619: +  snes - the SNES context
1620: -  ksp - the KSP context

1622:    Notes:
1623:    The SNES object already has its KSP object, you can obtain with SNESGetKSP()
1624:    so this routine is rarely needed.

1626:    The KSP object that is already in the SNES object has its reference count
1627:    decreased by one.

1629:    Level: developer

1631: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1632: @*/
1633: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1634: {

1641:   PetscObjectReference((PetscObject)ksp);
1642:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1643:   snes->ksp = ksp;
1644:   return(0);
1645: }

1647: /* -----------------------------------------------------------*/
1648: /*@
1649:    SNESCreate - Creates a nonlinear solver context.

1651:    Collective

1653:    Input Parameters:
1654: .  comm - MPI communicator

1656:    Output Parameter:
1657: .  outsnes - the new SNES context

1659:    Options Database Keys:
1660: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1661:                and no preconditioning matrix
1662: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1663:                products, and a user-provided preconditioning matrix
1664:                as set by SNESSetJacobian()
1665: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1667:    Level: beginner

1669:    Developer Notes:
1670:     SNES always creates a KSP object even though many SNES methods do not use it. This is
1671:                     unfortunate and should be fixed at some point. The flag snes->usesksp indicates if the
1672:                     particular method does use KSP and regulates if the information about the KSP is printed
1673:                     in SNESView(). TSSetFromOptions() does call SNESSetFromOptions() which can lead to users being confused
1674:                     by help messages about meaningless SNES options.

1676:                     SNES always creates the snes->kspconvctx even though it is used by only one type. This should
1677:                     be fixed.

1679: .seealso: SNESSolve(), SNESDestroy(), SNES, SNESSetLagPreconditioner()

1681: @*/
1682: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1683: {
1685:   SNES           snes;
1686:   SNESKSPEW      *kctx;

1690:   *outsnes = NULL;
1691:   SNESInitializePackage();

1693:   PetscHeaderCreate(snes,SNES_CLASSID,"SNES","Nonlinear solver","SNES",comm,SNESDestroy,SNESView);

1695:   snes->ops->converged    = SNESConvergedDefault;
1696:   snes->usesksp           = PETSC_TRUE;
1697:   snes->tolerancesset     = PETSC_FALSE;
1698:   snes->max_its           = 50;
1699:   snes->max_funcs         = 10000;
1700:   snes->norm              = 0.0;
1701:   snes->xnorm             = 0.0;
1702:   snes->ynorm             = 0.0;
1703:   snes->normschedule      = SNES_NORM_ALWAYS;
1704:   snes->functype          = SNES_FUNCTION_DEFAULT;
1705: #if defined(PETSC_USE_REAL_SINGLE)
1706:   snes->rtol              = 1.e-5;
1707: #else
1708:   snes->rtol              = 1.e-8;
1709: #endif
1710:   snes->ttol              = 0.0;
1711: #if defined(PETSC_USE_REAL_SINGLE)
1712:   snes->abstol            = 1.e-25;
1713: #else
1714:   snes->abstol            = 1.e-50;
1715: #endif
1716: #if defined(PETSC_USE_REAL_SINGLE)
1717:   snes->stol              = 1.e-5;
1718: #else
1719:   snes->stol              = 1.e-8;
1720: #endif
1721: #if defined(PETSC_USE_REAL_SINGLE)
1722:   snes->deltatol          = 1.e-6;
1723: #else
1724:   snes->deltatol          = 1.e-12;
1725: #endif
1726:   snes->divtol            = 1.e4;
1727:   snes->rnorm0            = 0;
1728:   snes->nfuncs            = 0;
1729:   snes->numFailures       = 0;
1730:   snes->maxFailures       = 1;
1731:   snes->linear_its        = 0;
1732:   snes->lagjacobian       = 1;
1733:   snes->jac_iter          = 0;
1734:   snes->lagjac_persist    = PETSC_FALSE;
1735:   snes->lagpreconditioner = 1;
1736:   snes->pre_iter          = 0;
1737:   snes->lagpre_persist    = PETSC_FALSE;
1738:   snes->numbermonitors    = 0;
1739:   snes->data              = 0;
1740:   snes->setupcalled       = PETSC_FALSE;
1741:   snes->ksp_ewconv        = PETSC_FALSE;
1742:   snes->nwork             = 0;
1743:   snes->work              = 0;
1744:   snes->nvwork            = 0;
1745:   snes->vwork             = 0;
1746:   snes->conv_hist_len     = 0;
1747:   snes->conv_hist_max     = 0;
1748:   snes->conv_hist         = NULL;
1749:   snes->conv_hist_its     = NULL;
1750:   snes->conv_hist_reset   = PETSC_TRUE;
1751:   snes->counters_reset    = PETSC_TRUE;
1752:   snes->vec_func_init_set = PETSC_FALSE;
1753:   snes->reason            = SNES_CONVERGED_ITERATING;
1754:   snes->npcside           = PC_RIGHT;
1755:   snes->setfromoptionscalled = 0;

1757:   snes->mf          = PETSC_FALSE;
1758:   snes->mf_operator = PETSC_FALSE;
1759:   snes->mf_version  = 1;

1761:   snes->numLinearSolveFailures = 0;
1762:   snes->maxLinearSolveFailures = 1;

1764:   snes->vizerotolerance = 1.e-8;
1765: #if defined(PETSC_USE_DEBUG)
1766:   snes->checkjacdomainerror = PETSC_TRUE;
1767: #else
1768:   snes->checkjacdomainerror = PETSC_FALSE;
1769: #endif

1771:   /* Set this to true if the implementation of SNESSolve_XXX does compute the residual at the final solution. */
1772:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

1774:   /* Create context to compute Eisenstat-Walker relative tolerance for KSP */
1775:   PetscNewLog(snes,&kctx);

1777:   snes->kspconvctx  = (void*)kctx;
1778:   kctx->version     = 2;
1779:   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1780:                              this was too large for some test cases */
1781:   kctx->rtol_last   = 0.0;
1782:   kctx->rtol_max    = .9;
1783:   kctx->gamma       = 1.0;
1784:   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
1785:   kctx->alpha2      = kctx->alpha;
1786:   kctx->threshold   = .1;
1787:   kctx->lresid_last = 0.0;
1788:   kctx->norm_last   = 0.0;

1790:   *outsnes = snes;
1791:   return(0);
1792: }

1794: /*MC
1795:     SNESFunction - Functional form used to convey the nonlinear function to be solved by SNES

1797:      Synopsis:
1798:      #include "petscsnes.h"
1799:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1801:      Input Parameters:
1802: +     snes - the SNES context
1803: .     x    - state at which to evaluate residual
1804: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1806:      Output Parameter:
1807: .     f  - vector to put residual (function value)

1809:    Level: intermediate

1811: .seealso:   SNESSetFunction(), SNESGetFunction()
1812: M*/

1814: /*@C
1815:    SNESSetFunction - Sets the function evaluation routine and function
1816:    vector for use by the SNES routines in solving systems of nonlinear
1817:    equations.

1819:    Logically Collective on SNES

1821:    Input Parameters:
1822: +  snes - the SNES context
1823: .  r - vector to store function value
1824: .  f - function evaluation routine; see SNESFunction for calling sequence details
1825: -  ctx - [optional] user-defined context for private data for the
1826:          function evaluation routine (may be NULL)

1828:    Notes:
1829:    The Newton-like methods typically solve linear systems of the form
1830: $      f'(x) x = -f(x),
1831:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1833:    Level: beginner

1835: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1836: @*/
1837: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1838: {
1840:   DM             dm;

1844:   if (r) {
1847:     PetscObjectReference((PetscObject)r);
1848:     VecDestroy(&snes->vec_func);

1850:     snes->vec_func = r;
1851:   }
1852:   SNESGetDM(snes,&dm);
1853:   DMSNESSetFunction(dm,f,ctx);
1854:   return(0);
1855: }


1858: /*@C
1859:    SNESSetInitialFunction - Sets the function vector to be used as the
1860:    function norm at the initialization of the method.  In some
1861:    instances, the user has precomputed the function before calling
1862:    SNESSolve.  This function allows one to avoid a redundant call
1863:    to SNESComputeFunction in that case.

1865:    Logically Collective on SNES

1867:    Input Parameters:
1868: +  snes - the SNES context
1869: -  f - vector to store function value

1871:    Notes:
1872:    This should not be modified during the solution procedure.

1874:    This is used extensively in the SNESFAS hierarchy and in nonlinear preconditioning.

1876:    Level: developer

1878: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1879: @*/
1880: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1881: {
1883:   Vec            vec_func;

1889:   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1890:     snes->vec_func_init_set = PETSC_FALSE;
1891:     return(0);
1892:   }
1893:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1894:   VecCopy(f, vec_func);

1896:   snes->vec_func_init_set = PETSC_TRUE;
1897:   return(0);
1898: }

1900: /*@
1901:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1902:    of the SNES method.

1904:    Logically Collective on SNES

1906:    Input Parameters:
1907: +  snes - the SNES context
1908: -  normschedule - the frequency of norm computation

1910:    Options Database Key:
1911: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

1913:    Notes:
1914:    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
1915:    of the nonlinear function and the taking of its norm at every iteration to
1916:    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
1917:    (SNESNGS) and the like do not require the norm of the function to be computed, and therfore
1918:    may either be monitored for convergence or not.  As these are often used as nonlinear
1919:    preconditioners, monitoring the norm of their error is not a useful enterprise within
1920:    their solution.

1922:    Level: developer

1924: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1925: @*/
1926: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1927: {
1930:   snes->normschedule = normschedule;
1931:   return(0);
1932: }


1935: /*@
1936:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1937:    of the SNES method.

1939:    Logically Collective on SNES

1941:    Input Parameters:
1942: +  snes - the SNES context
1943: -  normschedule - the type of the norm used

1945:    Level: advanced

1947: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1948: @*/
1949: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1950: {
1953:   *normschedule = snes->normschedule;
1954:   return(0);
1955: }


1958: /*@
1959:   SNESSetFunctionNorm - Sets the last computed residual norm.

1961:   Logically Collective on SNES

1963:   Input Parameters:
1964: + snes - the SNES context

1966: - normschedule - the frequency of norm computation

1968:   Level: developer

1970: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1971: @*/
1972: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1973: {
1976:   snes->norm = norm;
1977:   return(0);
1978: }

1980: /*@
1981:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1983:   Not Collective

1985:   Input Parameter:
1986: . snes - the SNES context

1988:   Output Parameter:
1989: . norm - the last computed residual norm

1991:   Level: developer

1993: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1994: @*/
1995: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1996: {
2000:   *norm = snes->norm;
2001:   return(0);
2002: }

2004: /*@
2005:   SNESGetUpdateNorm - Gets the last computed norm of the Newton update

2007:   Not Collective

2009:   Input Parameter:
2010: . snes - the SNES context

2012:   Output Parameter:
2013: . ynorm - the last computed update norm

2015:   Level: developer

2017: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm()
2018: @*/
2019: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2020: {
2024:   *ynorm = snes->ynorm;
2025:   return(0);
2026: }

2028: /*@
2029:   SNESGetSolutionNorm - Gets the last computed norm of the solution

2031:   Not Collective

2033:   Input Parameter:
2034: . snes - the SNES context

2036:   Output Parameter:
2037: . xnorm - the last computed solution norm

2039:   Level: developer

2041: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm(), SNESGetUpdateNorm()
2042: @*/
2043: PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2044: {
2048:   *xnorm = snes->xnorm;
2049:   return(0);
2050: }

2052: /*@C
2053:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
2054:    of the SNES method.

2056:    Logically Collective on SNES

2058:    Input Parameters:
2059: +  snes - the SNES context
2060: -  normschedule - the frequency of norm computation

2062:    Notes:
2063:    Only certain SNES methods support certain SNESNormSchedules.  Most require evaluation
2064:    of the nonlinear function and the taking of its norm at every iteration to
2065:    even ensure convergence at all.  However, methods such as custom Gauss-Seidel methods
2066:    (SNESNGS) and the like do not require the norm of the function to be computed, and therfore
2067:    may either be monitored for convergence or not.  As these are often used as nonlinear
2068:    preconditioners, monitoring the norm of their error is not a useful enterprise within
2069:    their solution.

2071:    Level: developer

2073: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2074: @*/
2075: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
2076: {
2079:   snes->functype = type;
2080:   return(0);
2081: }


2084: /*@C
2085:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
2086:    of the SNES method.

2088:    Logically Collective on SNES

2090:    Input Parameters:
2091: +  snes - the SNES context
2092: -  normschedule - the type of the norm used

2094:    Level: advanced

2096: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2097: @*/
2098: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2099: {
2102:   *type = snes->functype;
2103:   return(0);
2104: }

2106: /*MC
2107:     SNESNGSFunction - function used to convey a Gauss-Seidel sweep on the nonlinear function

2109:      Synopsis:
2110:      #include <petscsnes.h>
2111: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

2113: +  X   - solution vector
2114: .  B   - RHS vector
2115: -  ctx - optional user-defined Gauss-Seidel context

2117:    Level: intermediate

2119: .seealso:   SNESSetNGS(), SNESGetNGS()
2120: M*/

2122: /*@C
2123:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2124:    use with composed nonlinear solvers.

2126:    Input Parameters:
2127: +  snes   - the SNES context
2128: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
2129: -  ctx    - [optional] user-defined context for private data for the
2130:             smoother evaluation routine (may be NULL)

2132:    Notes:
2133:    The NGS routines are used by the composed nonlinear solver to generate
2134:     a problem appropriate update to the solution, particularly FAS.

2136:    Level: intermediate

2138: .seealso: SNESGetFunction(), SNESComputeNGS()
2139: @*/
2140: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
2141: {
2143:   DM             dm;

2147:   SNESGetDM(snes,&dm);
2148:   DMSNESSetNGS(dm,f,ctx);
2149:   return(0);
2150: }

2152: PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
2153: {
2155:   DM             dm;
2156:   DMSNES         sdm;

2159:   SNESGetDM(snes,&dm);
2160:   DMGetDMSNES(dm,&sdm);
2161:   if (!sdm->ops->computepfunction) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");
2162:   if (!sdm->ops->computepjacobian) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2163:   /*  A(x)*x - b(x) */
2164:   PetscStackPush("SNES Picard user function");
2165:   (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
2166:   PetscStackPop;
2167:   PetscStackPush("SNES Picard user Jacobian");
2168:   (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
2169:   PetscStackPop;
2170:   VecScale(f,-1.0);
2171:   MatMultAdd(snes->jacobian,x,f,f);
2172:   return(0);
2173: }

2175: PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
2176: {
2178:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2179:   return(0);
2180: }

2182: /*@C
2183:    SNESSetPicard - Use SNES to solve the semilinear-system A(x) x = b(x) via a Picard type iteration (Picard linearization)

2185:    Logically Collective on SNES

2187:    Input Parameters:
2188: +  snes - the SNES context
2189: .  r - vector to store function value
2190: .  b - function evaluation routine
2191: .  Amat - matrix with which A(x) x - b(x) is to be computed
2192: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2193: .  J  - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
2194: -  ctx - [optional] user-defined context for private data for the
2195:          function evaluation routine (may be NULL)

2197:    Notes:
2198:     We do not recomemend using this routine. It is far better to provide the nonlinear function F() and some approximation to the Jacobian and use
2199:     an approximate Newton solver. This interface is provided to allow porting/testing a previous Picard based code in PETSc before converting it to approximate Newton.

2201:     One can call SNESSetPicard() or SNESSetFunction() (and possibly SNESSetJacobian()) but cannot call both

2203: $     Solves the equation A(x) x = b(x) via the defect correction algorithm A(x^{n}) (x^{n+1} - x^{n}) = b(x^{n}) - A(x^{n})x^{n}
2204: $     Note that when an exact solver is used this corresponds to the "classic" Picard A(x^{n}) x^{n+1} = b(x^{n}) iteration.

2206:      Run with -snes_mf_operator to solve the system with Newton's method using A(x^{n}) to construct the preconditioner.

2208:    We implement the defect correction form of the Picard iteration because it converges much more generally when inexact linear solvers are used then
2209:    the direct Picard iteration A(x^n) x^{n+1} = b(x^n)

2211:    There is some controversity over the definition of a Picard iteration for nonlinear systems but almost everyone agrees that it involves a linear solve and some
2212:    believe it is the iteration  A(x^{n}) x^{n+1} = b(x^{n}) hence we use the name Picard. If anyone has an authoritative  reference that defines the Picard iteration
2213:    different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument :-).

2215:    Level: intermediate

2217: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2218: @*/
2219: PetscErrorCode  SNESSetPicard(SNES snes,Vec r,PetscErrorCode (*b)(SNES,Vec,Vec,void*),Mat Amat, Mat Pmat, PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2220: {
2222:   DM             dm;

2226:   SNESGetDM(snes, &dm);
2227:   DMSNESSetPicard(dm,b,J,ctx);
2228:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2229:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2230:   return(0);
2231: }

2233: /*@C
2234:    SNESGetPicard - Returns the context for the Picard iteration

2236:    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.

2238:    Input Parameter:
2239: .  snes - the SNES context

2241:    Output Parameter:
2242: +  r - the function (or NULL)
2243: .  f - the function (or NULL); see SNESFunction for calling sequence details
2244: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2245: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2246: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2247: -  ctx - the function context (or NULL)

2249:    Level: advanced

2251: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2252: @*/
2253: PetscErrorCode  SNESGetPicard(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),Mat *Amat, Mat *Pmat, PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2254: {
2256:   DM             dm;

2260:   SNESGetFunction(snes,r,NULL,NULL);
2261:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2262:   SNESGetDM(snes,&dm);
2263:   DMSNESGetPicard(dm,f,J,ctx);
2264:   return(0);
2265: }

2267: /*@C
2268:    SNESSetComputeInitialGuess - Sets a routine used to compute an initial guess for the problem

2270:    Logically Collective on SNES

2272:    Input Parameters:
2273: +  snes - the SNES context
2274: .  func - function evaluation routine
2275: -  ctx - [optional] user-defined context for private data for the
2276:          function evaluation routine (may be NULL)

2278:    Calling sequence of func:
2279: $    func (SNES snes,Vec x,void *ctx);

2281: .  f - function vector
2282: -  ctx - optional user-defined function context

2284:    Level: intermediate

2286: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2287: @*/
2288: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2289: {
2292:   if (func) snes->ops->computeinitialguess = func;
2293:   if (ctx)  snes->initialguessP            = ctx;
2294:   return(0);
2295: }

2297: /* --------------------------------------------------------------- */
2298: /*@C
2299:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2300:    it assumes a zero right hand side.

2302:    Logically Collective on SNES

2304:    Input Parameter:
2305: .  snes - the SNES context

2307:    Output Parameter:
2308: .  rhs - the right hand side vector or NULL if the right hand side vector is null

2310:    Level: intermediate

2312: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2313: @*/
2314: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2315: {
2319:   *rhs = snes->vec_rhs;
2320:   return(0);
2321: }

2323: /*@
2324:    SNESComputeFunction - Calls the function that has been set with SNESSetFunction().

2326:    Collective on SNES

2328:    Input Parameters:
2329: +  snes - the SNES context
2330: -  x - input vector

2332:    Output Parameter:
2333: .  y - function vector, as set by SNESSetFunction()

2335:    Notes:
2336:    SNESComputeFunction() is typically used within nonlinear solvers
2337:    implementations, so most users would not generally call this routine
2338:    themselves.

2340:    Level: developer

2342: .seealso: SNESSetFunction(), SNESGetFunction()
2343: @*/
2344: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2345: {
2347:   DM             dm;
2348:   DMSNES         sdm;

2356:   VecValidValues(x,2,PETSC_TRUE);

2358:   SNESGetDM(snes,&dm);
2359:   DMGetDMSNES(dm,&sdm);
2360:   if (sdm->ops->computefunction) {
2361:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2362:       PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2363:     }
2364:     VecLockReadPush(x);
2365:     PetscStackPush("SNES user function");
2366:     /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2367:     snes->domainerror = PETSC_FALSE;
2368:     (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);
2369:     PetscStackPop;
2370:     VecLockReadPop(x);
2371:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2372:       PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2373:     }
2374:   } else if (snes->vec_rhs) {
2375:     MatMult(snes->jacobian, x, y);
2376:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2377:   if (snes->vec_rhs) {
2378:     VecAXPY(y,-1.0,snes->vec_rhs);
2379:   }
2380:   snes->nfuncs++;
2381:   /*
2382:      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2383:      propagate the value to all processes
2384:   */
2385:   if (snes->domainerror) {
2386:     VecSetInf(y);
2387:   }
2388:   return(0);
2389: }

2391: /*@
2392:    SNESComputeNGS - Calls the Gauss-Seidel function that has been set with  SNESSetNGS().

2394:    Collective on SNES

2396:    Input Parameters:
2397: +  snes - the SNES context
2398: .  x - input vector
2399: -  b - rhs vector

2401:    Output Parameter:
2402: .  x - new solution vector

2404:    Notes:
2405:    SNESComputeNGS() is typically used within composed nonlinear solver
2406:    implementations, so most users would not generally call this routine
2407:    themselves.

2409:    Level: developer

2411: .seealso: SNESSetNGS(), SNESComputeFunction()
2412: @*/
2413: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2414: {
2416:   DM             dm;
2417:   DMSNES         sdm;

2425:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2426:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2427:   SNESGetDM(snes,&dm);
2428:   DMGetDMSNES(dm,&sdm);
2429:   if (sdm->ops->computegs) {
2430:     if (b) {VecLockReadPush(b);}
2431:     PetscStackPush("SNES user NGS");
2432:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2433:     PetscStackPop;
2434:     if (b) {VecLockReadPop(b);}
2435:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2436:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2437:   return(0);
2438: }

2440: PetscErrorCode SNESTestJacobian(SNES snes)
2441: {
2442:   Mat               A,B,C,D,jacobian;
2443:   Vec               x = snes->vec_sol,f = snes->vec_func;
2444:   PetscErrorCode    ierr;
2445:   PetscReal         nrm,gnorm;
2446:   PetscReal         threshold = 1.e-5;
2447:   MatType           mattype;
2448:   PetscInt          m,n,M,N;
2449:   void              *functx;
2450:   PetscBool         complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg;
2451:   PetscViewer       viewer,mviewer;
2452:   MPI_Comm          comm;
2453:   PetscInt          tabs;
2454:   static PetscBool  directionsprinted = PETSC_FALSE;
2455:   PetscViewerFormat format;

2458:   PetscObjectOptionsBegin((PetscObject)snes);
2459:   PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test);
2460:   PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL);
2461:   PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print);
2462:   if (!complete_print) {
2463:     PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print);
2464:   }
2465:   /* for compatibility with PETSc 3.9 and older. */
2466:   PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print);
2467:   PetscOptionsEnd();
2468:   if (!test) return(0);

2470:   PetscObjectGetComm((PetscObject)snes,&comm);
2471:   PetscViewerASCIIGetStdout(comm,&viewer);
2472:   PetscViewerASCIIGetTab(viewer, &tabs);
2473:   PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);
2474:   PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n");
2475:   if (!complete_print && !directionsprinted) {
2476:     PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n");
2477:     PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n");
2478:   }
2479:   if (!directionsprinted) {
2480:     PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n");
2481:     PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n");
2482:     directionsprinted = PETSC_TRUE;
2483:   }
2484:   if (complete_print) {
2485:     PetscViewerPushFormat(mviewer,format);
2486:   }

2488:   PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg);
2489:   if (!flg) jacobian = snes->jacobian;
2490:   else jacobian = snes->jacobian_pre;

2492:   if (!x) {
2493:     MatCreateVecs(jacobian, &x, NULL);
2494:   } else {
2495:     PetscObjectReference((PetscObject) x);
2496:   }
2497:   if (!f) {
2498:     VecDuplicate(x, &f);
2499:   } else {
2500:     PetscObjectReference((PetscObject) f);
2501:   }
2502:   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2503:   SNESComputeFunction(snes,x,f);
2504:   VecDestroy(&f);

2506:   while (jacobian) {
2507:     PetscObjectBaseTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPISBAIJ,"");
2508:     if (flg) {
2509:       A    = jacobian;
2510:       PetscObjectReference((PetscObject)A);
2511:     } else {
2512:       MatComputeOperator(jacobian,MATAIJ,&A);
2513:     }

2515:     MatGetType(A,&mattype);
2516:     MatGetSize(A,&M,&N);
2517:     MatGetLocalSize(A,&m,&n);

2519:     MatCreate(PetscObjectComm((PetscObject)A),&B);
2520:     MatSetType(B,mattype);
2521:     MatSetSizes(B,m,n,M,N);
2522:     MatSetBlockSizesFromMats(B,A,A);
2523:     MatSetUp(B);
2524:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2526:     SNESGetFunction(snes,NULL,NULL,&functx);
2527:     SNESComputeJacobianDefault(snes,x,B,B,functx);

2529:     MatDuplicate(B,MAT_COPY_VALUES,&D);
2530:     MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2531:     MatNorm(D,NORM_FROBENIUS,&nrm);
2532:     MatNorm(A,NORM_FROBENIUS,&gnorm);
2533:     MatDestroy(&D);
2534:     if (!gnorm) gnorm = 1; /* just in case */
2535:     PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm);

2537:     if (complete_print) {
2538:       PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n");
2539:       MatView(jacobian,mviewer);
2540:       PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n");
2541:       MatView(B,mviewer);
2542:     }

2544:     if (threshold_print || complete_print) {
2545:       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2546:       PetscScalar       *cvals;
2547:       const PetscInt    *bcols;
2548:       const PetscScalar *bvals;

2550:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2551:       MatSetType(C,mattype);
2552:       MatSetSizes(C,m,n,M,N);
2553:       MatSetBlockSizesFromMats(C,A,A);
2554:       MatSetUp(C);
2555:       MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2557:       MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2558:       MatGetOwnershipRange(B,&Istart,&Iend);

2560:       for (row = Istart; row < Iend; row++) {
2561:         MatGetRow(B,row,&bncols,&bcols,&bvals);
2562:         PetscMalloc2(bncols,&ccols,bncols,&cvals);
2563:         for (j = 0, cncols = 0; j < bncols; j++) {
2564:           if (PetscAbsScalar(bvals[j]) > threshold) {
2565:             ccols[cncols] = bcols[j];
2566:             cvals[cncols] = bvals[j];
2567:             cncols += 1;
2568:           }
2569:         }
2570:         if (cncols) {
2571:           MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES);
2572:         }
2573:         MatRestoreRow(B,row,&bncols,&bcols,&bvals);
2574:         PetscFree2(ccols,cvals);
2575:       }
2576:       MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2577:       MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
2578:       PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold);
2579:       MatView(C,complete_print ? mviewer : viewer);
2580:       MatDestroy(&C);
2581:     }
2582:     MatDestroy(&A);
2583:     MatDestroy(&B);

2585:     if (jacobian != snes->jacobian_pre) {
2586:       jacobian = snes->jacobian_pre;
2587:       PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n");
2588:     }
2589:     else jacobian = NULL;
2590:   }
2591:   VecDestroy(&x);
2592:   if (complete_print) {
2593:     PetscViewerPopFormat(mviewer);
2594:   }
2595:   if (mviewer) { PetscViewerDestroy(&mviewer); }
2596:   PetscViewerASCIISetTab(viewer,tabs);
2597:   return(0);
2598: }

2600: /*@
2601:    SNESComputeJacobian - Computes the Jacobian matrix that has been set with SNESSetJacobian().

2603:    Collective on SNES

2605:    Input Parameters:
2606: +  snes - the SNES context
2607: -  x - input vector

2609:    Output Parameters:
2610: +  A - Jacobian matrix
2611: -  B - optional preconditioning matrix

2613:   Options Database Keys:
2614: +    -snes_lag_preconditioner <lag>
2615: .    -snes_lag_jacobian <lag>
2616: .    -snes_test_jacobian - compare the user provided Jacobian with one compute via finite differences to check for errors
2617: .    -snes_test_jacobian_display - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian
2618: .    -snes_test_jacobian_display_threshold <numerical value>  - display entries in the difference between the user provided Jacobian and finite difference Jacobian that are greater than a certain value to help users detect errors
2619: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2620: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2621: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2622: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2623: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2624: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2625: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2626: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2627: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2628: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2629: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2632:    Notes:
2633:    Most users should not need to explicitly call this routine, as it
2634:    is used internally within the nonlinear solvers.

2636:    Developer Notes:
2637:     This has duplicative ways of checking the accuracy of the user provided Jacobian (see the options above). This is for historical reasons, the routine SNESTestJacobian() use to used
2638:       for with the SNESType of test that has been removed.

2640:    Level: developer

2642: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2643: @*/
2644: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2645: {
2647:   PetscBool      flag;
2648:   DM             dm;
2649:   DMSNES         sdm;
2650:   KSP            ksp;

2656:   VecValidValues(X,2,PETSC_TRUE);
2657:   SNESGetDM(snes,&dm);
2658:   DMGetDMSNES(dm,&sdm);

2660:   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Must call SNESSetJacobian(), DMSNESSetJacobian(), DMDASNESSetJacobianLocal(), etc");

2662:   /* make sure that MatAssemblyBegin/End() is called on A matrix if it is matrix free */

2664:   if (snes->lagjacobian == -2) {
2665:     snes->lagjacobian = -1;

2667:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2668:   } else if (snes->lagjacobian == -1) {
2669:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2670:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2671:     if (flag) {
2672:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2673:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2674:     }
2675:     return(0);
2676:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2677:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2678:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2679:     if (flag) {
2680:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2681:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2682:     }
2683:     return(0);
2684:   }
2685:   if (snes->npc && snes->npcside== PC_LEFT) {
2686:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2687:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2688:     return(0);
2689:   }

2691:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2692:   VecLockReadPush(X);
2693:   PetscStackPush("SNES user Jacobian function");
2694:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2695:   PetscStackPop;
2696:   VecLockReadPop(X);
2697:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2699:   /* attach latest linearization point to the preconditioning matrix */
2700:   PetscObjectCompose((PetscObject)B,"__SNES_latest_X",(PetscObject)X);

2702:   /* the next line ensures that snes->ksp exists */
2703:   SNESGetKSP(snes,&ksp);
2704:   if (snes->lagpreconditioner == -2) {
2705:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2706:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2707:     snes->lagpreconditioner = -1;
2708:   } else if (snes->lagpreconditioner == -1) {
2709:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2710:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2711:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2712:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2713:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2714:   } else {
2715:     PetscInfo(snes,"Rebuilding preconditioner\n");
2716:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2717:   }

2719:   SNESTestJacobian(snes);
2720:   /* make sure user returned a correct Jacobian and preconditioner */
2723:   {
2724:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2725:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2726:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2727:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2728:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2729:     if (flag || flag_draw || flag_contour) {
2730:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2731:       PetscViewer  vdraw,vstdout;
2732:       PetscBool    flg;
2733:       if (flag_operator) {
2734:         MatComputeOperator(A,MATAIJ,&Bexp_mine);
2735:         Bexp = Bexp_mine;
2736:       } else {
2737:         /* See if the preconditioning matrix can be viewed and added directly */
2738:         PetscObjectBaseTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2739:         if (flg) Bexp = B;
2740:         else {
2741:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2742:           MatComputeOperator(B,MATAIJ,&Bexp_mine);
2743:           Bexp = Bexp_mine;
2744:         }
2745:       }
2746:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2747:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2748:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2749:       if (flag_draw || flag_contour) {
2750:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2751:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2752:       } else vdraw = NULL;
2753:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2754:       if (flag) {MatView(Bexp,vstdout);}
2755:       if (vdraw) {MatView(Bexp,vdraw);}
2756:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2757:       if (flag) {MatView(FDexp,vstdout);}
2758:       if (vdraw) {MatView(FDexp,vdraw);}
2759:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2760:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2761:       if (flag) {MatView(FDexp,vstdout);}
2762:       if (vdraw) {              /* Always use contour for the difference */
2763:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2764:         MatView(FDexp,vdraw);
2765:         PetscViewerPopFormat(vdraw);
2766:       }
2767:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2768:       PetscViewerDestroy(&vdraw);
2769:       MatDestroy(&Bexp_mine);
2770:       MatDestroy(&FDexp);
2771:     }
2772:   }
2773:   {
2774:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2775:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2776:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2777:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2778:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2779:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2780:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2781:     if (flag_threshold) {
2782:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2783:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2784:     }
2785:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2786:       Mat            Bfd;
2787:       PetscViewer    vdraw,vstdout;
2788:       MatColoring    coloring;
2789:       ISColoring     iscoloring;
2790:       MatFDColoring  matfdcoloring;
2791:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2792:       void           *funcctx;
2793:       PetscReal      norm1,norm2,normmax;

2795:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2796:       MatColoringCreate(Bfd,&coloring);
2797:       MatColoringSetType(coloring,MATCOLORINGSL);
2798:       MatColoringSetFromOptions(coloring);
2799:       MatColoringApply(coloring,&iscoloring);
2800:       MatColoringDestroy(&coloring);
2801:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2802:       MatFDColoringSetFromOptions(matfdcoloring);
2803:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2804:       ISColoringDestroy(&iscoloring);

2806:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2807:       SNESGetFunction(snes,NULL,&func,&funcctx);
2808:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2809:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2810:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2811:       MatFDColoringSetFromOptions(matfdcoloring);
2812:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2813:       MatFDColoringDestroy(&matfdcoloring);

2815:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2816:       if (flag_draw || flag_contour) {
2817:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2818:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2819:       } else vdraw = NULL;
2820:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2821:       if (flag_display) {MatView(B,vstdout);}
2822:       if (vdraw) {MatView(B,vdraw);}
2823:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2824:       if (flag_display) {MatView(Bfd,vstdout);}
2825:       if (vdraw) {MatView(Bfd,vdraw);}
2826:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2827:       MatNorm(Bfd,NORM_1,&norm1);
2828:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2829:       MatNorm(Bfd,NORM_MAX,&normmax);
2830:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2831:       if (flag_display) {MatView(Bfd,vstdout);}
2832:       if (vdraw) {              /* Always use contour for the difference */
2833:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2834:         MatView(Bfd,vdraw);
2835:         PetscViewerPopFormat(vdraw);
2836:       }
2837:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2839:       if (flag_threshold) {
2840:         PetscInt bs,rstart,rend,i;
2841:         MatGetBlockSize(B,&bs);
2842:         MatGetOwnershipRange(B,&rstart,&rend);
2843:         for (i=rstart; i<rend; i++) {
2844:           const PetscScalar *ba,*ca;
2845:           const PetscInt    *bj,*cj;
2846:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2847:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2848:           MatGetRow(B,i,&bn,&bj,&ba);
2849:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2850:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2851:           for (j=0; j<bn; j++) {
2852:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2853:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2854:               maxentrycol = bj[j];
2855:               maxentry    = PetscRealPart(ba[j]);
2856:             }
2857:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2858:               maxdiffcol = bj[j];
2859:               maxdiff    = PetscRealPart(ca[j]);
2860:             }
2861:             if (rdiff > maxrdiff) {
2862:               maxrdiffcol = bj[j];
2863:               maxrdiff    = rdiff;
2864:             }
2865:           }
2866:           if (maxrdiff > 1) {
2867:             PetscViewerASCIIPrintf(vstdout,"row %D (maxentry=%g at %D, maxdiff=%g at %D, maxrdiff=%g at %D):",i,(double)maxentry,maxentrycol,(double)maxdiff,maxdiffcol,(double)maxrdiff,maxrdiffcol);
2868:             for (j=0; j<bn; j++) {
2869:               PetscReal rdiff;
2870:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2871:               if (rdiff > 1) {
2872:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2873:               }
2874:             }
2875:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2876:           }
2877:           MatRestoreRow(B,i,&bn,&bj,&ba);
2878:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2879:         }
2880:       }
2881:       PetscViewerDestroy(&vdraw);
2882:       MatDestroy(&Bfd);
2883:     }
2884:   }
2885:   return(0);
2886: }

2888: /*MC
2889:     SNESJacobianFunction - Function used to convey the nonlinear Jacobian of the function to be solved by SNES

2891:      Synopsis:
2892:      #include "petscsnes.h"
2893:      PetscErrorCode SNESJacobianFunction(SNES snes,Vec x,Mat Amat,Mat Pmat,void *ctx);

2895: +  x - input vector
2896: .  Amat - the matrix that defines the (approximate) Jacobian
2897: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2898: -  ctx - [optional] user-defined Jacobian context

2900:    Level: intermediate

2902: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2903: M*/

2905: /*@C
2906:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2907:    location to store the matrix.

2909:    Logically Collective on SNES

2911:    Input Parameters:
2912: +  snes - the SNES context
2913: .  Amat - the matrix that defines the (approximate) Jacobian
2914: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2915: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2916: -  ctx - [optional] user-defined context for private data for the
2917:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2919:    Notes:
2920:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2921:    each matrix.

2923:    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
2924:    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.

2926:    If using SNESComputeJacobianDefaultColor() to assemble a Jacobian, the ctx argument
2927:    must be a MatFDColoring.

2929:    Other defect-correction schemes can be used by computing a different matrix in place of the Jacobian.  One common
2930:    example is to use the "Picard linearization" which only differentiates through the highest order parts of each term.

2932:    Level: beginner

2934: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
2935:           SNESSetPicard(), SNESJacobianFunction
2936: @*/
2937: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2938: {
2940:   DM             dm;

2948:   SNESGetDM(snes,&dm);
2949:   DMSNESSetJacobian(dm,J,ctx);
2950:   if (Amat) {
2951:     PetscObjectReference((PetscObject)Amat);
2952:     MatDestroy(&snes->jacobian);

2954:     snes->jacobian = Amat;
2955:   }
2956:   if (Pmat) {
2957:     PetscObjectReference((PetscObject)Pmat);
2958:     MatDestroy(&snes->jacobian_pre);

2960:     snes->jacobian_pre = Pmat;
2961:   }
2962:   return(0);
2963: }

2965: /*@C
2966:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2967:    provided context for evaluating the Jacobian.

2969:    Not Collective, but Mat object will be parallel if SNES object is

2971:    Input Parameter:
2972: .  snes - the nonlinear solver context

2974:    Output Parameters:
2975: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2976: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2977: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2978: -  ctx - location to stash Jacobian ctx (or NULL)

2980:    Level: advanced

2982: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2983: @*/
2984: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2985: {
2987:   DM             dm;
2988:   DMSNES         sdm;

2992:   if (Amat) *Amat = snes->jacobian;
2993:   if (Pmat) *Pmat = snes->jacobian_pre;
2994:   SNESGetDM(snes,&dm);
2995:   DMGetDMSNES(dm,&sdm);
2996:   if (J) *J = sdm->ops->computejacobian;
2997:   if (ctx) *ctx = sdm->jacobianctx;
2998:   return(0);
2999: }

3001: /*@
3002:    SNESSetUp - Sets up the internal data structures for the later use
3003:    of a nonlinear solver.

3005:    Collective on SNES

3007:    Input Parameters:
3008: .  snes - the SNES context

3010:    Notes:
3011:    For basic use of the SNES solvers the user need not explicitly call
3012:    SNESSetUp(), since these actions will automatically occur during
3013:    the call to SNESSolve().  However, if one wishes to control this
3014:    phase separately, SNESSetUp() should be called after SNESCreate()
3015:    and optional routines of the form SNESSetXXX(), but before SNESSolve().

3017:    Level: advanced

3019: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
3020: @*/
3021: PetscErrorCode  SNESSetUp(SNES snes)
3022: {
3024:   DM             dm;
3025:   DMSNES         sdm;
3026:   SNESLineSearch linesearch, pclinesearch;
3027:   void           *lsprectx,*lspostctx;
3028:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
3029:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
3030:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
3031:   Vec            f,fpc;
3032:   void           *funcctx;
3033:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
3034:   void           *jacctx,*appctx;
3035:   Mat            j,jpre;

3039:   if (snes->setupcalled) return(0);
3040:   PetscLogEventBegin(SNES_Setup,snes,0,0,0);

3042:   if (!((PetscObject)snes)->type_name) {
3043:     SNESSetType(snes,SNESNEWTONLS);
3044:   }

3046:   SNESGetFunction(snes,&snes->vec_func,NULL,NULL);

3048:   SNESGetDM(snes,&dm);
3049:   DMGetDMSNES(dm,&sdm);
3050:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
3051:   if (!sdm->ops->computejacobian) {
3052:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
3053:   }
3054:   if (!snes->vec_func) {
3055:     DMCreateGlobalVector(dm,&snes->vec_func);
3056:   }

3058:   if (!snes->ksp) {
3059:     SNESGetKSP(snes, &snes->ksp);
3060:   }

3062:   if (snes->linesearch) {
3063:     SNESGetLineSearch(snes, &snes->linesearch);
3064:     SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);
3065:   }

3067:   if (snes->npc && (snes->npcside== PC_LEFT)) {
3068:     snes->mf          = PETSC_TRUE;
3069:     snes->mf_operator = PETSC_FALSE;
3070:   }

3072:   if (snes->npc) {
3073:     /* copy the DM over */
3074:     SNESGetDM(snes,&dm);
3075:     SNESSetDM(snes->npc,dm);

3077:     SNESGetFunction(snes,&f,&func,&funcctx);
3078:     VecDuplicate(f,&fpc);
3079:     SNESSetFunction(snes->npc,fpc,func,funcctx);
3080:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
3081:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
3082:     SNESGetApplicationContext(snes,&appctx);
3083:     SNESSetApplicationContext(snes->npc,appctx);
3084:     VecDestroy(&fpc);

3086:     /* copy the function pointers over */
3087:     PetscObjectCopyFortranFunctionPointers((PetscObject)snes,(PetscObject)snes->npc);

3089:     /* default to 1 iteration */
3090:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
3091:     if (snes->npcside==PC_RIGHT) {
3092:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
3093:     } else {
3094:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
3095:     }
3096:     SNESSetFromOptions(snes->npc);

3098:     /* copy the line search context over */
3099:     if (snes->linesearch && snes->npc->linesearch) {
3100:       SNESGetLineSearch(snes,&linesearch);
3101:       SNESGetLineSearch(snes->npc,&pclinesearch);
3102:       SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
3103:       SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
3104:       SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
3105:       SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
3106:       PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
3107:     }
3108:   }
3109:   if (snes->mf) {
3110:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
3111:   }
3112:   if (snes->ops->usercompute && !snes->user) {
3113:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
3114:   }

3116:   snes->jac_iter = 0;
3117:   snes->pre_iter = 0;

3119:   if (snes->ops->setup) {
3120:     (*snes->ops->setup)(snes);
3121:   }

3123:   if (snes->npc && (snes->npcside== PC_LEFT)) {
3124:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3125:       if (snes->linesearch){
3126:         SNESGetLineSearch(snes,&linesearch);
3127:         SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
3128:       }
3129:     }
3130:   }
3131:   PetscLogEventEnd(SNES_Setup,snes,0,0,0);
3132:   snes->setupcalled = PETSC_TRUE;
3133:   return(0);
3134: }

3136: /*@
3137:    SNESReset - Resets a SNES context to the snessetupcalled = 0 state and removes any allocated Vecs and Mats

3139:    Collective on SNES

3141:    Input Parameter:
3142: .  snes - iterative context obtained from SNESCreate()

3144:    Level: intermediate

3146:    Notes:
3147:     Also calls the application context destroy routine set with SNESSetComputeApplicationContext()

3149: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
3150: @*/
3151: PetscErrorCode  SNESReset(SNES snes)
3152: {

3157:   if (snes->ops->userdestroy && snes->user) {
3158:     (*snes->ops->userdestroy)((void**)&snes->user);
3159:     snes->user = NULL;
3160:   }
3161:   if (snes->npc) {
3162:     SNESReset(snes->npc);
3163:   }

3165:   if (snes->ops->reset) {
3166:     (*snes->ops->reset)(snes);
3167:   }
3168:   if (snes->ksp) {
3169:     KSPReset(snes->ksp);
3170:   }

3172:   if (snes->linesearch) {
3173:     SNESLineSearchReset(snes->linesearch);
3174:   }

3176:   VecDestroy(&snes->vec_rhs);
3177:   VecDestroy(&snes->vec_sol);
3178:   VecDestroy(&snes->vec_sol_update);
3179:   VecDestroy(&snes->vec_func);
3180:   MatDestroy(&snes->jacobian);
3181:   MatDestroy(&snes->jacobian_pre);
3182:   VecDestroyVecs(snes->nwork,&snes->work);
3183:   VecDestroyVecs(snes->nvwork,&snes->vwork);

3185:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3187:   snes->nwork       = snes->nvwork = 0;
3188:   snes->setupcalled = PETSC_FALSE;
3189:   return(0);
3190: }

3192: /*@
3193:    SNESDestroy - Destroys the nonlinear solver context that was created
3194:    with SNESCreate().

3196:    Collective on SNES

3198:    Input Parameter:
3199: .  snes - the SNES context

3201:    Level: beginner

3203: .seealso: SNESCreate(), SNESSolve()
3204: @*/
3205: PetscErrorCode  SNESDestroy(SNES *snes)
3206: {

3210:   if (!*snes) return(0);
3212:   if (--((PetscObject)(*snes))->refct > 0) {*snes = 0; return(0);}

3214:   SNESReset((*snes));
3215:   SNESDestroy(&(*snes)->npc);

3217:   /* if memory was published with SAWs then destroy it */
3218:   PetscObjectSAWsViewOff((PetscObject)*snes);
3219:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

3221:   if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
3222:   DMDestroy(&(*snes)->dm);
3223:   KSPDestroy(&(*snes)->ksp);
3224:   SNESLineSearchDestroy(&(*snes)->linesearch);

3226:   PetscFree((*snes)->kspconvctx);
3227:   if ((*snes)->ops->convergeddestroy) {
3228:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
3229:   }
3230:   if ((*snes)->conv_hist_alloc) {
3231:     PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its);
3232:   }
3233:   SNESMonitorCancel((*snes));
3234:   PetscHeaderDestroy(snes);
3235:   return(0);
3236: }

3238: /* ----------- Routines to set solver parameters ---------- */

3240: /*@
3241:    SNESSetLagPreconditioner - Determines when the preconditioner is rebuilt in the nonlinear solve.

3243:    Logically Collective on SNES

3245:    Input Parameters:
3246: +  snes - the SNES context
3247: -  lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3248:          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that

3250:    Options Database Keys:
3251: .    -snes_lag_preconditioner <lag>

3253:    Notes:
3254:    The default is 1
3255:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3256:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

3258:    Level: intermediate

3260: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian()

3262: @*/
3263: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3264: {
3267:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3268:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3270:   snes->lagpreconditioner = lag;
3271:   return(0);
3272: }

3274: /*@
3275:    SNESSetGridSequence - sets the number of steps of grid sequencing that SNES does

3277:    Logically Collective on SNES

3279:    Input Parameters:
3280: +  snes - the SNES context
3281: -  steps - the number of refinements to do, defaults to 0

3283:    Options Database Keys:
3284: .    -snes_grid_sequence <steps>

3286:    Level: intermediate

3288:    Notes:
3289:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

3291: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetGridSequence()

3293: @*/
3294: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3295: {
3299:   snes->gridsequence = steps;
3300:   return(0);
3301: }

3303: /*@
3304:    SNESGetGridSequence - gets the number of steps of grid sequencing that SNES does

3306:    Logically Collective on SNES

3308:    Input Parameter:
3309: .  snes - the SNES context

3311:    Output Parameter:
3312: .  steps - the number of refinements to do, defaults to 0

3314:    Options Database Keys:
3315: .    -snes_grid_sequence <steps>

3317:    Level: intermediate

3319:    Notes:
3320:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

3322: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESSetGridSequence()

3324: @*/
3325: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3326: {
3329:   *steps = snes->gridsequence;
3330:   return(0);
3331: }

3333: /*@
3334:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3336:    Not Collective

3338:    Input Parameter:
3339: .  snes - the SNES context

3341:    Output Parameter:
3342: .   lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3343:          the Jacobian is built etc. -2 indicates rebuild preconditioner at next chance but then never rebuild after that

3345:    Options Database Keys:
3346: .    -snes_lag_preconditioner <lag>

3348:    Notes:
3349:    The default is 1
3350:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3352:    Level: intermediate

3354: .seealso: SNESSetTrustRegionTolerance(), SNESSetLagPreconditioner()

3356: @*/
3357: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3358: {
3361:   *lag = snes->lagpreconditioner;
3362:   return(0);
3363: }

3365: /*@
3366:    SNESSetLagJacobian - Determines when the Jacobian is rebuilt in the nonlinear solve. See SNESSetLagPreconditioner() for determining how
3367:      often the preconditioner is rebuilt.

3369:    Logically Collective on SNES

3371:    Input Parameters:
3372: +  snes - the SNES context
3373: -  lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3374:          the Jacobian is built etc. -2 means rebuild at next chance but then never again

3376:    Options Database Keys:
3377: .    -snes_lag_jacobian <lag>

3379:    Notes:
3380:    The default is 1
3381:    The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3382:    If  -1 is used before the very first nonlinear solve the CODE WILL FAIL! because no Jacobian is used, use -2 to indicate you want it recomputed
3383:    at the next Newton step but never again (unless it is reset to another value)

3385:    Level: intermediate

3387: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagPreconditioner(), SNESGetLagJacobian()

3389: @*/
3390: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3391: {
3394:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3395:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3397:   snes->lagjacobian = lag;
3398:   return(0);
3399: }

3401: /*@
3402:    SNESGetLagJacobian - Indicates how often the Jacobian is rebuilt. See SNESGetLagPreconditioner() to determine when the preconditioner is rebuilt

3404:    Not Collective

3406:    Input Parameter:
3407: .  snes - the SNES context

3409:    Output Parameter:
3410: .   lag - -1 indicates NEVER rebuild, 1 means rebuild every time the Jacobian is computed within a single nonlinear solve, 2 means every second time
3411:          the Jacobian is built etc.

3413:    Options Database Keys:
3414: .    -snes_lag_jacobian <lag>

3416:    Notes:
3417:    The default is 1
3418:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3420:    Level: intermediate

3422: .seealso: SNESSetTrustRegionTolerance(), SNESSetLagJacobian(), SNESSetLagPreconditioner(), SNESGetLagPreconditioner()

3424: @*/
3425: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3426: {
3429:   *lag = snes->lagjacobian;
3430:   return(0);
3431: }

3433: /*@
3434:    SNESSetLagJacobianPersists - Set whether or not the Jacobian lagging persists through multiple solves

3436:    Logically collective on SNES

3438:    Input Parameter:
3439: +  snes - the SNES context
3440: -   flg - jacobian lagging persists if true

3442:    Options Database Keys:
3443: .    -snes_lag_jacobian_persists <flg>

3445:    Notes:
3446:     This is useful both for nonlinear preconditioning, where it's appropriate to have the Jacobian be stale by
3447:    several solves, and for implicit time-stepping, where Jacobian lagging in the inner nonlinear solve over several
3448:    timesteps may present huge efficiency gains.

3450:    Level: developer

3452: .seealso: SNESSetLagPreconditionerPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC()

3454: @*/
3455: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3456: {
3460:   snes->lagjac_persist = flg;
3461:   return(0);
3462: }

3464: /*@
3465:    SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple solves

3467:    Logically Collective on SNES

3469:    Input Parameter:
3470: +  snes - the SNES context
3471: -   flg - preconditioner lagging persists if true

3473:    Options Database Keys:
3474: .    -snes_lag_jacobian_persists <flg>

3476:    Notes:
3477:     This is useful both for nonlinear preconditioning, where it's appropriate to have the preconditioner be stale
3478:    by several solves, and for implicit time-stepping, where preconditioner lagging in the inner nonlinear solve over
3479:    several timesteps may present huge efficiency gains.

3481:    Level: developer

3483: .seealso: SNESSetLagJacobianPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC()

3485: @*/
3486: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3487: {
3491:   snes->lagpre_persist = flg;
3492:   return(0);
3493: }

3495: /*@
3496:    SNESSetForceIteration - force SNESSolve() to take at least one iteration regardless of the initial residual norm

3498:    Logically Collective on SNES

3500:    Input Parameters:
3501: +  snes - the SNES context
3502: -  force - PETSC_TRUE require at least one iteration

3504:    Options Database Keys:
3505: .    -snes_force_iteration <force> - Sets forcing an iteration

3507:    Notes:
3508:    This is used sometimes with TS to prevent TS from detecting a false steady state solution

3510:    Level: intermediate

3512: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3513: @*/
3514: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3515: {
3518:   snes->forceiteration = force;
3519:   return(0);
3520: }

3522: /*@
3523:    SNESGetForceIteration - Whether or not to force SNESSolve() take at least one iteration regardless of the initial residual norm

3525:    Logically Collective on SNES

3527:    Input Parameters:
3528: .  snes - the SNES context

3530:    Output Parameter:
3531: .  force - PETSC_TRUE requires at least one iteration.

3533:    Level: intermediate

3535: .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3536: @*/
3537: PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
3538: {
3541:   *force = snes->forceiteration;
3542:   return(0);
3543: }

3545: /*@
3546:    SNESSetTolerances - Sets various parameters used in convergence tests.

3548:    Logically Collective on SNES

3550:    Input Parameters:
3551: +  snes - the SNES context
3552: .  abstol - absolute convergence tolerance
3553: .  rtol - relative convergence tolerance
3554: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3555: .  maxit - maximum number of iterations
3556: -  maxf - maximum number of function evaluations (-1 indicates no limit)

3558:    Options Database Keys:
3559: +    -snes_atol <abstol> - Sets abstol
3560: .    -snes_rtol <rtol> - Sets rtol
3561: .    -snes_stol <stol> - Sets stol
3562: .    -snes_max_it <maxit> - Sets maxit
3563: -    -snes_max_funcs <maxf> - Sets maxf

3565:    Notes:
3566:    The default maximum number of iterations is 50.
3567:    The default maximum number of function evaluations is 1000.

3569:    Level: intermediate

3571: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3572: @*/
3573: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3574: {

3583:   if (abstol != PETSC_DEFAULT) {
3584:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3585:     snes->abstol = abstol;
3586:   }
3587:   if (rtol != PETSC_DEFAULT) {
3588:     if (rtol < 0.0 || 1.0 <= rtol) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Relative tolerance %g must be non-negative and less than 1.0",(double)rtol);
3589:     snes->rtol = rtol;
3590:   }
3591:   if (stol != PETSC_DEFAULT) {
3592:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3593:     snes->stol = stol;
3594:   }
3595:   if (maxit != PETSC_DEFAULT) {
3596:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3597:     snes->max_its = maxit;
3598:   }
3599:   if (maxf != PETSC_DEFAULT) {
3600:     if (maxf < -1) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be -1 or nonnegative",maxf);
3601:     snes->max_funcs = maxf;
3602:   }
3603:   snes->tolerancesset = PETSC_TRUE;
3604:   return(0);
3605: }

3607: /*@
3608:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3610:    Logically Collective on SNES

3612:    Input Parameters:
3613: +  snes - the SNES context
3614: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3616:    Options Database Keys:
3617: .    -snes_divergence_tolerance <divtol> - Sets divtol

3619:    Notes:
3620:    The default divergence tolerance is 1e4.

3622:    Level: intermediate

3624: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3625: @*/
3626: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3627: {

3632:   if (divtol != PETSC_DEFAULT) {
3633:     snes->divtol = divtol;
3634:   }
3635:   else {
3636:     snes->divtol = 1.0e4;
3637:   }
3638:   return(0);
3639: }

3641: /*@
3642:    SNESGetTolerances - Gets various parameters used in convergence tests.

3644:    Not Collective

3646:    Input Parameters:
3647: +  snes - the SNES context
3648: .  atol - absolute convergence tolerance
3649: .  rtol - relative convergence tolerance
3650: .  stol -  convergence tolerance in terms of the norm
3651:            of the change in the solution between steps
3652: .  maxit - maximum number of iterations
3653: -  maxf - maximum number of function evaluations

3655:    Notes:
3656:    The user can specify NULL for any parameter that is not needed.

3658:    Level: intermediate

3660: .seealso: SNESSetTolerances()
3661: @*/
3662: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3663: {
3666:   if (atol)  *atol  = snes->abstol;
3667:   if (rtol)  *rtol  = snes->rtol;
3668:   if (stol)  *stol  = snes->stol;
3669:   if (maxit) *maxit = snes->max_its;
3670:   if (maxf)  *maxf  = snes->max_funcs;
3671:   return(0);
3672: }

3674: /*@
3675:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3677:    Not Collective

3679:    Input Parameters:
3680: +  snes - the SNES context
3681: -  divtol - divergence tolerance

3683:    Level: intermediate

3685: .seealso: SNESSetDivergenceTolerance()
3686: @*/
3687: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3688: {
3691:   if (divtol) *divtol = snes->divtol;
3692:   return(0);
3693: }

3695: /*@
3696:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3698:    Logically Collective on SNES

3700:    Input Parameters:
3701: +  snes - the SNES context
3702: -  tol - tolerance

3704:    Options Database Key:
3705: .  -snes_trtol <tol> - Sets tol

3707:    Level: intermediate

3709: .seealso: SNESSetTolerances()
3710: @*/
3711: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3712: {
3716:   snes->deltatol = tol;
3717:   return(0);
3718: }

3720: /*
3721:    Duplicate the lg monitors for SNES from KSP; for some reason with
3722:    dynamic libraries things don't work under Sun4 if we just use
3723:    macros instead of functions
3724: */
3725: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3726: {

3731:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3732:   return(0);
3733: }

3735: PetscErrorCode  SNESMonitorLGCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscDrawLG *lgctx)
3736: {

3740:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3741:   return(0);
3742: }

3744: PETSC_INTERN PetscErrorCode  SNESMonitorRange_Private(SNES,PetscInt,PetscReal*);

3746: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3747: {
3748:   PetscDrawLG      lg;
3749:   PetscErrorCode   ierr;
3750:   PetscReal        x,y,per;
3751:   PetscViewer      v = (PetscViewer)monctx;
3752:   static PetscReal prev; /* should be in the context */
3753:   PetscDraw        draw;

3757:   PetscViewerDrawGetDrawLG(v,0,&lg);
3758:   if (!n) {PetscDrawLGReset(lg);}
3759:   PetscDrawLGGetDraw(lg,&draw);
3760:   PetscDrawSetTitle(draw,"Residual norm");
3761:   x    = (PetscReal)n;
3762:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3763:   else y = -15.0;
3764:   PetscDrawLGAddPoint(lg,&x,&y);
3765:   if (n < 20 || !(n % 5) || snes->reason) {
3766:     PetscDrawLGDraw(lg);
3767:     PetscDrawLGSave(lg);
3768:   }

3770:   PetscViewerDrawGetDrawLG(v,1,&lg);
3771:   if (!n) {PetscDrawLGReset(lg);}
3772:   PetscDrawLGGetDraw(lg,&draw);
3773:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3774:    SNESMonitorRange_Private(snes,n,&per);
3775:   x    = (PetscReal)n;
3776:   y    = 100.0*per;
3777:   PetscDrawLGAddPoint(lg,&x,&y);
3778:   if (n < 20 || !(n % 5) || snes->reason) {
3779:     PetscDrawLGDraw(lg);
3780:     PetscDrawLGSave(lg);
3781:   }

3783:   PetscViewerDrawGetDrawLG(v,2,&lg);
3784:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3785:   PetscDrawLGGetDraw(lg,&draw);
3786:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3787:   x    = (PetscReal)n;
3788:   y    = (prev - rnorm)/prev;
3789:   PetscDrawLGAddPoint(lg,&x,&y);
3790:   if (n < 20 || !(n % 5) || snes->reason) {
3791:     PetscDrawLGDraw(lg);
3792:     PetscDrawLGSave(lg);
3793:   }

3795:   PetscViewerDrawGetDrawLG(v,3,&lg);
3796:   if (!n) {PetscDrawLGReset(lg);}
3797:   PetscDrawLGGetDraw(lg,&draw);
3798:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3799:   x    = (PetscReal)n;
3800:   y    = (prev - rnorm)/(prev*per);
3801:   if (n > 2) { /*skip initial crazy value */
3802:     PetscDrawLGAddPoint(lg,&x,&y);
3803:   }
3804:   if (n < 20 || !(n % 5) || snes->reason) {
3805:     PetscDrawLGDraw(lg);
3806:     PetscDrawLGSave(lg);
3807:   }
3808:   prev = rnorm;
3809:   return(0);
3810: }

3812: /*@
3813:    SNESMonitor - runs the user provided monitor routines, if they exist

3815:    Collective on SNES

3817:    Input Parameters:
3818: +  snes - nonlinear solver context obtained from SNESCreate()
3819: .  iter - iteration number
3820: -  rnorm - relative norm of the residual

3822:    Notes:
3823:    This routine is called by the SNES implementations.
3824:    It does not typically need to be called by the user.

3826:    Level: developer

3828: .seealso: SNESMonitorSet()
3829: @*/
3830: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3831: {
3833:   PetscInt       i,n = snes->numbermonitors;

3836:   VecLockReadPush(snes->vec_sol);
3837:   for (i=0; i<n; i++) {
3838:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3839:   }
3840:   VecLockReadPop(snes->vec_sol);
3841:   return(0);
3842: }

3844: /* ------------ Routines to set performance monitoring options ----------- */

3846: /*MC
3847:     SNESMonitorFunction - functional form passed to SNESMonitorSet() to monitor convergence of nonlinear solver

3849:      Synopsis:
3850:      #include <petscsnes.h>
3851: $    PetscErrorCode SNESMonitorFunction(SNES snes,PetscInt its, PetscReal norm,void *mctx)

3853: +    snes - the SNES context
3854: .    its - iteration number
3855: .    norm - 2-norm function value (may be estimated)
3856: -    mctx - [optional] monitoring context

3858:    Level: advanced

3860: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3861: M*/

3863: /*@C
3864:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3865:    iteration of the nonlinear solver to display the iteration's
3866:    progress.

3868:    Logically Collective on SNES

3870:    Input Parameters:
3871: +  snes - the SNES context
3872: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3873: .  mctx - [optional] user-defined context for private data for the
3874:           monitor routine (use NULL if no context is desired)
3875: -  monitordestroy - [optional] routine that frees monitor context
3876:           (may be NULL)

3878:    Options Database Keys:
3879: +    -snes_monitor        - sets SNESMonitorDefault()
3880: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3881:                             uses SNESMonitorLGCreate()
3882: -    -snes_monitor_cancel - cancels all monitors that have
3883:                             been hardwired into a code by
3884:                             calls to SNESMonitorSet(), but
3885:                             does not cancel those set via
3886:                             the options database.

3888:    Notes:
3889:    Several different monitoring routines may be set by calling
3890:    SNESMonitorSet() multiple times; all will be called in the
3891:    order in which they were set.

3893:    Fortran Notes:
3894:     Only a single monitor function can be set for each SNES object

3896:    Level: intermediate

3898: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3899: @*/
3900: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3901: {
3902:   PetscInt       i;
3904:   PetscBool      identical;

3908:   for (i=0; i<snes->numbermonitors;i++) {
3909:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3910:     if (identical) return(0);
3911:   }
3912:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3913:   snes->monitor[snes->numbermonitors]          = f;
3914:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3915:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3916:   return(0);
3917: }

3919: /*@
3920:    SNESMonitorCancel - Clears all the monitor functions for a SNES object.

3922:    Logically Collective on SNES

3924:    Input Parameters:
3925: .  snes - the SNES context

3927:    Options Database Key:
3928: .  -snes_monitor_cancel - cancels all monitors that have been hardwired
3929:     into a code by calls to SNESMonitorSet(), but does not cancel those
3930:     set via the options database

3932:    Notes:
3933:    There is no way to clear one specific monitor from a SNES object.

3935:    Level: intermediate

3937: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3938: @*/
3939: PetscErrorCode  SNESMonitorCancel(SNES snes)
3940: {
3942:   PetscInt       i;

3946:   for (i=0; i<snes->numbermonitors; i++) {
3947:     if (snes->monitordestroy[i]) {
3948:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3949:     }
3950:   }
3951:   snes->numbermonitors = 0;
3952:   return(0);
3953: }

3955: /*MC
3956:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

3958:      Synopsis:
3959:      #include <petscsnes.h>
3960: $     PetscErrorCode SNESConvergenceTest(SNES snes,PetscInt it,PetscReal xnorm,PetscReal gnorm,PetscReal f,SNESConvergedReason *reason,void *cctx)

3962: +    snes - the SNES context
3963: .    it - current iteration (0 is the first and is before any Newton step)
3964: .    cctx - [optional] convergence context
3965: .    reason - reason for convergence/divergence
3966: .    xnorm - 2-norm of current iterate
3967: .    gnorm - 2-norm of current step
3968: -    f - 2-norm of function

3970:    Level: intermediate

3972: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3973: M*/

3975: /*@C
3976:    SNESSetConvergenceTest - Sets the function that is to be used
3977:    to test for convergence of the nonlinear iterative solution.

3979:    Logically Collective on SNES

3981:    Input Parameters:
3982: +  snes - the SNES context
3983: .  SNESConvergenceTestFunction - routine to test for convergence
3984: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3985: -  destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)

3987:    Level: advanced

3989: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3990: @*/
3991: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3992: {

3997:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3998:   if (snes->ops->convergeddestroy) {
3999:     (*snes->ops->convergeddestroy)(snes->cnvP);
4000:   }
4001:   snes->ops->converged        = SNESConvergenceTestFunction;
4002:   snes->ops->convergeddestroy = destroy;
4003:   snes->cnvP                  = cctx;
4004:   return(0);
4005: }

4007: /*@
4008:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

4010:    Not Collective

4012:    Input Parameter:
4013: .  snes - the SNES context

4015:    Output Parameter:
4016: .  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4017:             manual pages for the individual convergence tests for complete lists

4019:    Options Database:
4020: .   -snes_converged_reason - prints the reason to standard out

4022:    Level: intermediate

4024:    Notes:
4025:     Should only be called after the call the SNESSolve() is complete, if it is called earlier it returns the value SNES__CONVERGED_ITERATING.

4027: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
4028: @*/
4029: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4030: {
4034:   *reason = snes->reason;
4035:   return(0);
4036: }

4038: /*@
4039:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

4041:    Not Collective

4043:    Input Parameters:
4044: +  snes - the SNES context
4045: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4046:             manual pages for the individual convergence tests for complete lists

4048:    Level: intermediate

4050: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
4051: @*/
4052: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
4053: {
4056:   snes->reason = reason;
4057:   return(0);
4058: }

4060: /*@
4061:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

4063:    Logically Collective on SNES

4065:    Input Parameters:
4066: +  snes - iterative context obtained from SNESCreate()
4067: .  a   - array to hold history, this array will contain the function norms computed at each step
4068: .  its - integer array holds the number of linear iterations for each solve.
4069: .  na  - size of a and its
4070: -  reset - PETSC_TRUE indicates each new nonlinear solve resets the history counter to zero,
4071:            else it continues storing new values for new nonlinear solves after the old ones

4073:    Notes:
4074:    If 'a' and 'its' are NULL then space is allocated for the history. If 'na' PETSC_DECIDE or PETSC_DEFAULT then a
4075:    default array of length 10000 is allocated.

4077:    This routine is useful, e.g., when running a code for purposes
4078:    of accurate performance monitoring, when no I/O should be done
4079:    during the section of code that is being timed.

4081:    Level: intermediate

4083: .seealso: SNESGetConvergenceHistory()

4085: @*/
4086: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4087: {

4094:   if (!a) {
4095:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
4096:     PetscCalloc2(na,&a,na,&its);
4097:     snes->conv_hist_alloc = PETSC_TRUE;
4098:   }
4099:   snes->conv_hist       = a;
4100:   snes->conv_hist_its   = its;
4101:   snes->conv_hist_max   = na;
4102:   snes->conv_hist_len   = 0;
4103:   snes->conv_hist_reset = reset;
4104:   return(0);
4105: }

4107: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4108: #include <engine.h>   /* MATLAB include file */
4109: #include <mex.h>      /* MATLAB include file */

4111: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4112: {
4113:   mxArray   *mat;
4114:   PetscInt  i;
4115:   PetscReal *ar;

4118:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4119:   ar  = (PetscReal*) mxGetData(mat);
4120:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4121:   PetscFunctionReturn(mat);
4122: }
4123: #endif

4125: /*@C
4126:    SNESGetConvergenceHistory - Gets the array used to hold the convergence history.

4128:    Not Collective

4130:    Input Parameter:
4131: .  snes - iterative context obtained from SNESCreate()

4133:    Output Parameters:
4134: +  a   - array to hold history
4135: .  its - integer array holds the number of linear iterations (or
4136:          negative if not converged) for each solve.
4137: -  na  - size of a and its

4139:    Notes:
4140:     The calling sequence for this routine in Fortran is
4141: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

4143:    This routine is useful, e.g., when running a code for purposes
4144:    of accurate performance monitoring, when no I/O should be done
4145:    during the section of code that is being timed.

4147:    Level: intermediate

4149: .seealso: SNESSetConvergencHistory()

4151: @*/
4152: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4153: {
4156:   if (a)   *a   = snes->conv_hist;
4157:   if (its) *its = snes->conv_hist_its;
4158:   if (na)  *na  = snes->conv_hist_len;
4159:   return(0);
4160: }

4162: /*@C
4163:   SNESSetUpdate - Sets the general-purpose update function called
4164:   at the beginning of every iteration of the nonlinear solve. Specifically
4165:   it is called just before the Jacobian is "evaluated".

4167:   Logically Collective on SNES

4169:   Input Parameters:
4170: + snes - The nonlinear solver context
4171: - func - The function

4173:   Calling sequence of func:
4174: $ func (SNES snes, PetscInt step);

4176: . step - The current step of the iteration

4178:   Level: advanced

4180:   Note: This is NOT what one uses to update the ghost points before a function evaluation, that should be done at the beginning of your FormFunction()
4181:         This is not used by most users.

4183: .seealso SNESSetJacobian(), SNESSolve()
4184: @*/
4185: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4186: {
4189:   snes->ops->update = func;
4190:   return(0);
4191: }

4193: /*
4194:    SNESScaleStep_Private - Scales a step so that its length is less than the
4195:    positive parameter delta.

4197:     Input Parameters:
4198: +   snes - the SNES context
4199: .   y - approximate solution of linear system
4200: .   fnorm - 2-norm of current function
4201: -   delta - trust region size

4203:     Output Parameters:
4204: +   gpnorm - predicted function norm at the new point, assuming local
4205:     linearization.  The value is zero if the step lies within the trust
4206:     region, and exceeds zero otherwise.
4207: -   ynorm - 2-norm of the step

4209:     Note:
4210:     For non-trust region methods such as SNESNEWTONLS, the parameter delta
4211:     is set to be the maximum allowable step size.

4213: */
4214: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4215: {
4216:   PetscReal      nrm;
4217:   PetscScalar    cnorm;


4225:   VecNorm(y,NORM_2,&nrm);
4226:   if (nrm > *delta) {
4227:     nrm     = *delta/nrm;
4228:     *gpnorm = (1.0 - nrm)*(*fnorm);
4229:     cnorm   = nrm;
4230:     VecScale(y,cnorm);
4231:     *ynorm  = *delta;
4232:   } else {
4233:     *gpnorm = 0.0;
4234:     *ynorm  = nrm;
4235:   }
4236:   return(0);
4237: }

4239: /*@
4240:    SNESReasonView - Displays the reason a SNES solve converged or diverged to a viewer

4242:    Collective on SNES

4244:    Parameter:
4245: +  snes - iterative context obtained from SNESCreate()
4246: -  viewer - the viewer to display the reason


4249:    Options Database Keys:
4250: .  -snes_converged_reason - print reason for converged or diverged, also prints number of iterations

4252:    Level: beginner

4254: .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault()

4256: @*/
4257: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
4258: {
4259:   PetscViewerFormat format;
4260:   PetscBool         isAscii;
4261:   PetscErrorCode    ierr;

4264:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
4265:   if (isAscii) {
4266:     PetscViewerGetFormat(viewer, &format);
4267:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
4268:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4269:       DM                dm;
4270:       Vec               u;
4271:       PetscDS           prob;
4272:       PetscInt          Nf, f;
4273:       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4274:       void            **exactCtx;
4275:       PetscReal         error;

4277:       SNESGetDM(snes, &dm);
4278:       SNESGetSolution(snes, &u);
4279:       DMGetDS(dm, &prob);
4280:       PetscDSGetNumFields(prob, &Nf);
4281:       PetscMalloc2(Nf, &exactSol, Nf, &exactCtx);
4282:       for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]);}
4283:       DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error);
4284:       PetscFree2(exactSol, exactCtx);
4285:       if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
4286:       else                 {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
4287:     }
4288:     if (snes->reason > 0) {
4289:       if (((PetscObject) snes)->prefix) {
4290:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4291:       } else {
4292:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4293:       }
4294:     } else {
4295:       if (((PetscObject) snes)->prefix) {
4296:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4297:       } else {
4298:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4299:       }
4300:     }
4301:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4302:   }
4303:   return(0);
4304: }

4306: /*@C
4307:   SNESReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed.

4309:   Collective on SNES

4311:   Input Parameters:
4312: . snes   - the SNES object

4314:   Level: intermediate

4316: @*/
4317: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
4318: {
4319:   PetscErrorCode    ierr;
4320:   PetscViewer       viewer;
4321:   PetscBool         flg;
4322:   static PetscBool  incall = PETSC_FALSE;
4323:   PetscViewerFormat format;

4326:   if (incall) return(0);
4327:   incall = PETSC_TRUE;
4328:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4329:   if (flg) {
4330:     PetscViewerPushFormat(viewer,format);
4331:     SNESReasonView(snes,viewer);
4332:     PetscViewerPopFormat(viewer);
4333:     PetscViewerDestroy(&viewer);
4334:   }
4335:   incall = PETSC_FALSE;
4336:   return(0);
4337: }

4339: /*@
4340:    SNESSolve - Solves a nonlinear system F(x) = b.
4341:    Call SNESSolve() after calling SNESCreate() and optional routines of the form SNESSetXXX().

4343:    Collective on SNES

4345:    Input Parameters:
4346: +  snes - the SNES context
4347: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4348: -  x - the solution vector.

4350:    Notes:
4351:    The user should initialize the vector,x, with the initial guess
4352:    for the nonlinear solve prior to calling SNESSolve.  In particular,
4353:    to employ an initial guess of zero, the user should explicitly set
4354:    this vector to zero by calling VecSet().

4356:    Level: beginner

4358: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4359: @*/
4360: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4361: {
4362:   PetscErrorCode    ierr;
4363:   PetscBool         flg;
4364:   PetscInt          grid;
4365:   Vec               xcreated = NULL;
4366:   DM                dm;


4375:   /* High level operations using the nonlinear solver */
4376:   {
4377:     PetscViewer       viewer;
4378:     PetscViewerFormat format;
4379:     PetscInt          num;
4380:     PetscBool         flg;
4381:     static PetscBool  incall = PETSC_FALSE;

4383:     if (!incall) {
4384:       /* Estimate the convergence rate of the discretization */
4385:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4386:       if (flg) {
4387:         PetscConvEst conv;
4388:         DM           dm;
4389:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4390:         PetscInt     Nf;

4392:         incall = PETSC_TRUE;
4393:         SNESGetDM(snes, &dm);
4394:         DMGetNumFields(dm, &Nf);
4395:         PetscCalloc1(Nf, &alpha);
4396:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4397:         PetscConvEstSetSolver(conv, (PetscObject) snes);
4398:         PetscConvEstSetFromOptions(conv);
4399:         PetscConvEstSetUp(conv);
4400:         PetscConvEstGetConvRate(conv, alpha);
4401:         PetscViewerPushFormat(viewer, format);
4402:         PetscConvEstRateView(conv, alpha, viewer);
4403:         PetscViewerPopFormat(viewer);
4404:         PetscViewerDestroy(&viewer);
4405:         PetscConvEstDestroy(&conv);
4406:         PetscFree(alpha);
4407:         incall = PETSC_FALSE;
4408:       }
4409:       /* Adaptively refine the initial grid */
4410:       num  = 1;
4411:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);
4412:       if (flg) {
4413:         DMAdaptor adaptor;

4415:         incall = PETSC_TRUE;
4416:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4417:         DMAdaptorSetSolver(adaptor, snes);
4418:         DMAdaptorSetSequenceLength(adaptor, num);
4419:         DMAdaptorSetFromOptions(adaptor);
4420:         DMAdaptorSetUp(adaptor);
4421:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4422:         DMAdaptorDestroy(&adaptor);
4423:         incall = PETSC_FALSE;
4424:       }
4425:       /* Use grid sequencing to adapt */
4426:       num  = 0;
4427:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4428:       if (num) {
4429:         DMAdaptor adaptor;

4431:         incall = PETSC_TRUE;
4432:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4433:         DMAdaptorSetSolver(adaptor, snes);
4434:         DMAdaptorSetSequenceLength(adaptor, num);
4435:         DMAdaptorSetFromOptions(adaptor);
4436:         DMAdaptorSetUp(adaptor);
4437:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4438:         DMAdaptorDestroy(&adaptor);
4439:         incall = PETSC_FALSE;
4440:       }
4441:     }
4442:   }
4443:   if (!x) {
4444:     SNESGetDM(snes,&dm);
4445:     DMCreateGlobalVector(dm,&xcreated);
4446:     x    = xcreated;
4447:   }
4448:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

4450:   for (grid=0; grid<snes->gridsequence; grid++) {PetscViewerASCIIPushTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));}
4451:   for (grid=0; grid<snes->gridsequence+1; grid++) {

4453:     /* set solution vector */
4454:     if (!grid) {PetscObjectReference((PetscObject)x);}
4455:     VecDestroy(&snes->vec_sol);
4456:     snes->vec_sol = x;
4457:     SNESGetDM(snes,&dm);

4459:     /* set affine vector if provided */
4460:     if (b) { PetscObjectReference((PetscObject)b); }
4461:     VecDestroy(&snes->vec_rhs);
4462:     snes->vec_rhs = b;

4464:     if (snes->vec_rhs && (snes->vec_func == snes->vec_rhs)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Right hand side vector cannot be function vector");
4465:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4466:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4467:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4468:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4469:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4470:     }
4471:     DMShellSetGlobalVector(dm,snes->vec_sol);
4472:     SNESSetUp(snes);

4474:     if (!grid) {
4475:       if (snes->ops->computeinitialguess) {
4476:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4477:       }
4478:     }

4480:     if (snes->conv_hist_reset) snes->conv_hist_len = 0;
4481:     if (snes->counters_reset) {snes->nfuncs = 0; snes->linear_its = 0; snes->numFailures = 0;}

4483:     PetscLogEventBegin(SNES_Solve,snes,0,0,0);
4484:     (*snes->ops->solve)(snes);
4485:     PetscLogEventEnd(SNES_Solve,snes,0,0,0);
4486:     if (!snes->reason) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");
4487:     snes->domainerror = PETSC_FALSE; /* clear the flag if it has been set */

4489:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4490:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

4492:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg);
4493:     if (flg && !PetscPreLoadingOn) { SNESTestLocalMin(snes); }
4494:     SNESReasonViewFromOptions(snes);

4496:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4497:     if (snes->reason < 0) break;
4498:     if (grid <  snes->gridsequence) {
4499:       DM  fine;
4500:       Vec xnew;
4501:       Mat interp;

4503:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4504:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4505:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4506:       DMCreateGlobalVector(fine,&xnew);
4507:       MatInterpolate(interp,x,xnew);
4508:       DMInterpolate(snes->dm,interp,fine);
4509:       MatDestroy(&interp);
4510:       x    = xnew;

4512:       SNESReset(snes);
4513:       SNESSetDM(snes,fine);
4514:       SNESResetFromOptions(snes);
4515:       DMDestroy(&fine);
4516:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4517:     }
4518:   }
4519:   SNESViewFromOptions(snes,NULL,"-snes_view");
4520:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4522:   VecDestroy(&xcreated);
4523:   PetscObjectSAWsBlock((PetscObject)snes);
4524:   return(0);
4525: }

4527: /* --------- Internal routines for SNES Package --------- */

4529: /*@C
4530:    SNESSetType - Sets the method for the nonlinear solver.

4532:    Collective on SNES

4534:    Input Parameters:
4535: +  snes - the SNES context
4536: -  type - a known method

4538:    Options Database Key:
4539: .  -snes_type <type> - Sets the method; use -help for a list
4540:    of available methods (for instance, newtonls or newtontr)

4542:    Notes:
4543:    See "petsc/include/petscsnes.h" for available methods (for instance)
4544: +    SNESNEWTONLS - Newton's method with line search
4545:      (systems of nonlinear equations)
4546: -    SNESNEWTONTR - Newton's method with trust region
4547:      (systems of nonlinear equations)

4549:   Normally, it is best to use the SNESSetFromOptions() command and then
4550:   set the SNES solver type from the options database rather than by using
4551:   this routine.  Using the options database provides the user with
4552:   maximum flexibility in evaluating the many nonlinear solvers.
4553:   The SNESSetType() routine is provided for those situations where it
4554:   is necessary to set the nonlinear solver independently of the command
4555:   line or options database.  This might be the case, for example, when
4556:   the choice of solver changes during the execution of the program,
4557:   and the user's application is taking responsibility for choosing the
4558:   appropriate method.

4560:     Developer Notes:
4561:     SNESRegister() adds a constructor for a new SNESType to SNESList, SNESSetType() locates
4562:     the constructor in that list and calls it to create the spexific object.

4564:   Level: intermediate

4566: .seealso: SNESType, SNESCreate(), SNESDestroy(), SNESGetType(), SNESSetFromOptions()

4568: @*/
4569: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4570: {
4571:   PetscErrorCode ierr,(*r)(SNES);
4572:   PetscBool      match;


4578:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4579:   if (match) return(0);

4581:   PetscFunctionListFind(SNESList,type,&r);
4582:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4583:   /* Destroy the previous private SNES context */
4584:   if (snes->ops->destroy) {
4585:     (*(snes)->ops->destroy)(snes);
4586:     snes->ops->destroy = NULL;
4587:   }
4588:   /* Reinitialize function pointers in SNESOps structure */
4589:   snes->ops->setup          = 0;
4590:   snes->ops->solve          = 0;
4591:   snes->ops->view           = 0;
4592:   snes->ops->setfromoptions = 0;
4593:   snes->ops->destroy        = 0;

4595:   /* It may happen the user has customized the line search before calling SNESSetType */
4596:   if (((PetscObject)snes)->type_name) {
4597:     SNESLineSearchDestroy(&snes->linesearch);
4598:   }

4600:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4601:   snes->setupcalled = PETSC_FALSE;

4603:   PetscObjectChangeTypeName((PetscObject)snes,type);
4604:   (*r)(snes);
4605:   return(0);
4606: }

4608: /*@C
4609:    SNESGetType - Gets the SNES method type and name (as a string).

4611:    Not Collective

4613:    Input Parameter:
4614: .  snes - nonlinear solver context

4616:    Output Parameter:
4617: .  type - SNES method (a character string)

4619:    Level: intermediate

4621: @*/
4622: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4623: {
4627:   *type = ((PetscObject)snes)->type_name;
4628:   return(0);
4629: }

4631: /*@
4632:   SNESSetSolution - Sets the solution vector for use by the SNES routines.

4634:   Logically Collective on SNES

4636:   Input Parameters:
4637: + snes - the SNES context obtained from SNESCreate()
4638: - u    - the solution vector

4640:   Level: beginner

4642: @*/
4643: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4644: {
4645:   DM             dm;

4651:   PetscObjectReference((PetscObject) u);
4652:   VecDestroy(&snes->vec_sol);

4654:   snes->vec_sol = u;

4656:   SNESGetDM(snes, &dm);
4657:   DMShellSetGlobalVector(dm, u);
4658:   return(0);
4659: }

4661: /*@
4662:    SNESGetSolution - Returns the vector where the approximate solution is
4663:    stored. This is the fine grid solution when using SNESSetGridSequence().

4665:    Not Collective, but Vec is parallel if SNES is parallel

4667:    Input Parameter:
4668: .  snes - the SNES context

4670:    Output Parameter:
4671: .  x - the solution

4673:    Level: intermediate

4675: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4676: @*/
4677: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4678: {
4682:   *x = snes->vec_sol;
4683:   return(0);
4684: }

4686: /*@
4687:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4688:    stored.

4690:    Not Collective, but Vec is parallel if SNES is parallel

4692:    Input Parameter:
4693: .  snes - the SNES context

4695:    Output Parameter:
4696: .  x - the solution update

4698:    Level: advanced

4700: .seealso: SNESGetSolution(), SNESGetFunction()
4701: @*/
4702: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4703: {
4707:   *x = snes->vec_sol_update;
4708:   return(0);
4709: }

4711: /*@C
4712:    SNESGetFunction - Returns the vector where the function is stored.

4714:    Not Collective, but Vec is parallel if SNES is parallel. Collective if Vec is requested, but has not been created yet.

4716:    Input Parameter:
4717: .  snes - the SNES context

4719:    Output Parameter:
4720: +  r - the vector that is used to store residuals (or NULL if you don't want it)
4721: .  f - the function (or NULL if you don't want it); see SNESFunction for calling sequence details
4722: -  ctx - the function context (or NULL if you don't want it)

4724:    Level: advanced

4726:     Notes: The vector r DOES NOT, in general contain the current value of the SNES nonlinear function

4728: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4729: @*/
4730: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4731: {
4733:   DM             dm;

4737:   if (r) {
4738:     if (!snes->vec_func) {
4739:       if (snes->vec_rhs) {
4740:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4741:       } else if (snes->vec_sol) {
4742:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4743:       } else if (snes->dm) {
4744:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4745:       }
4746:     }
4747:     *r = snes->vec_func;
4748:   }
4749:   SNESGetDM(snes,&dm);
4750:   DMSNESGetFunction(dm,f,ctx);
4751:   return(0);
4752: }

4754: /*@C
4755:    SNESGetNGS - Returns the NGS function and context.

4757:    Input Parameter:
4758: .  snes - the SNES context

4760:    Output Parameter:
4761: +  f - the function (or NULL) see SNESNGSFunction for details
4762: -  ctx    - the function context (or NULL)

4764:    Level: advanced

4766: .seealso: SNESSetNGS(), SNESGetFunction()
4767: @*/

4769: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4770: {
4772:   DM             dm;

4776:   SNESGetDM(snes,&dm);
4777:   DMSNESGetNGS(dm,f,ctx);
4778:   return(0);
4779: }

4781: /*@C
4782:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4783:    SNES options in the database.

4785:    Logically Collective on SNES

4787:    Input Parameter:
4788: +  snes - the SNES context
4789: -  prefix - the prefix to prepend to all option names

4791:    Notes:
4792:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4793:    The first character of all runtime options is AUTOMATICALLY the hyphen.

4795:    Level: advanced

4797: .seealso: SNESSetFromOptions()
4798: @*/
4799: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4800: {

4805:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4806:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4807:   if (snes->linesearch) {
4808:     SNESGetLineSearch(snes,&snes->linesearch);
4809:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4810:   }
4811:   KSPSetOptionsPrefix(snes->ksp,prefix);
4812:   return(0);
4813: }

4815: /*@C
4816:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4817:    SNES options in the database.

4819:    Logically Collective on SNES

4821:    Input Parameters:
4822: +  snes - the SNES context
4823: -  prefix - the prefix to prepend to all option names

4825:    Notes:
4826:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4827:    The first character of all runtime options is AUTOMATICALLY the hyphen.

4829:    Level: advanced

4831: .seealso: SNESGetOptionsPrefix()
4832: @*/
4833: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4834: {

4839:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4840:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4841:   if (snes->linesearch) {
4842:     SNESGetLineSearch(snes,&snes->linesearch);
4843:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4844:   }
4845:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4846:   return(0);
4847: }

4849: /*@C
4850:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4851:    SNES options in the database.

4853:    Not Collective

4855:    Input Parameter:
4856: .  snes - the SNES context

4858:    Output Parameter:
4859: .  prefix - pointer to the prefix string used

4861:    Notes:
4862:     On the fortran side, the user should pass in a string 'prefix' of
4863:    sufficient length to hold the prefix.

4865:    Level: advanced

4867: .seealso: SNESAppendOptionsPrefix()
4868: @*/
4869: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4870: {

4875:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4876:   return(0);
4877: }


4880: /*@C
4881:   SNESRegister - Adds a method to the nonlinear solver package.

4883:    Not collective

4885:    Input Parameters:
4886: +  name_solver - name of a new user-defined solver
4887: -  routine_create - routine to create method context

4889:    Notes:
4890:    SNESRegister() may be called multiple times to add several user-defined solvers.

4892:    Sample usage:
4893: .vb
4894:    SNESRegister("my_solver",MySolverCreate);
4895: .ve

4897:    Then, your solver can be chosen with the procedural interface via
4898: $     SNESSetType(snes,"my_solver")
4899:    or at runtime via the option
4900: $     -snes_type my_solver

4902:    Level: advanced

4904:     Note: If your function is not being put into a shared library then use SNESRegister() instead

4906: .seealso: SNESRegisterAll(), SNESRegisterDestroy()

4908:   Level: advanced
4909: @*/
4910: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4911: {

4915:   SNESInitializePackage();
4916:   PetscFunctionListAdd(&SNESList,sname,function);
4917:   return(0);
4918: }

4920: PetscErrorCode  SNESTestLocalMin(SNES snes)
4921: {
4923:   PetscInt       N,i,j;
4924:   Vec            u,uh,fh;
4925:   PetscScalar    value;
4926:   PetscReal      norm;

4929:   SNESGetSolution(snes,&u);
4930:   VecDuplicate(u,&uh);
4931:   VecDuplicate(u,&fh);

4933:   /* currently only works for sequential */
4934:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4935:   VecGetSize(u,&N);
4936:   for (i=0; i<N; i++) {
4937:     VecCopy(u,uh);
4938:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4939:     for (j=-10; j<11; j++) {
4940:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4941:       VecSetValue(uh,i,value,ADD_VALUES);
4942:       SNESComputeFunction(snes,uh,fh);
4943:       VecNorm(fh,NORM_2,&norm);
4944:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4945:       value = -value;
4946:       VecSetValue(uh,i,value,ADD_VALUES);
4947:     }
4948:   }
4949:   VecDestroy(&uh);
4950:   VecDestroy(&fh);
4951:   return(0);
4952: }

4954: /*@
4955:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4956:    computing relative tolerance for linear solvers within an inexact
4957:    Newton method.

4959:    Logically Collective on SNES

4961:    Input Parameters:
4962: +  snes - SNES context
4963: -  flag - PETSC_TRUE or PETSC_FALSE

4965:     Options Database:
4966: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4967: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4968: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4969: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4970: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4971: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4972: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4973: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4975:    Notes:
4976:    Currently, the default is to use a constant relative tolerance for
4977:    the inner linear solvers.  Alternatively, one can use the
4978:    Eisenstat-Walker method, where the relative convergence tolerance
4979:    is reset at each Newton iteration according progress of the nonlinear
4980:    solver.

4982:    Level: advanced

4984:    Reference:
4985:    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
4986:    inexact Newton method", SISC 17 (1), pp.16-32, 1996.

4988: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4989: @*/
4990: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4991: {
4995:   snes->ksp_ewconv = flag;
4996:   return(0);
4997: }

4999: /*@
5000:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
5001:    for computing relative tolerance for linear solvers within an
5002:    inexact Newton method.

5004:    Not Collective

5006:    Input Parameter:
5007: .  snes - SNES context

5009:    Output Parameter:
5010: .  flag - PETSC_TRUE or PETSC_FALSE

5012:    Notes:
5013:    Currently, the default is to use a constant relative tolerance for
5014:    the inner linear solvers.  Alternatively, one can use the
5015:    Eisenstat-Walker method, where the relative convergence tolerance
5016:    is reset at each Newton iteration according progress of the nonlinear
5017:    solver.

5019:    Level: advanced

5021:    Reference:
5022:    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
5023:    inexact Newton method", SISC 17 (1), pp.16-32, 1996.

5025: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
5026: @*/
5027: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
5028: {
5032:   *flag = snes->ksp_ewconv;
5033:   return(0);
5034: }

5036: /*@
5037:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5038:    convergence criteria for the linear solvers within an inexact
5039:    Newton method.

5041:    Logically Collective on SNES

5043:    Input Parameters:
5044: +    snes - SNES context
5045: .    version - version 1, 2 (default is 2) or 3
5046: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5047: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5048: .    gamma - multiplicative factor for version 2 rtol computation
5049:              (0 <= gamma2 <= 1)
5050: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5051: .    alpha2 - power for safeguard
5052: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5054:    Note:
5055:    Version 3 was contributed by Luis Chacon, June 2006.

5057:    Use PETSC_DEFAULT to retain the default for any of the parameters.

5059:    Level: advanced

5061:    Reference:
5062:    S. C. Eisenstat and H. F. Walker, "Choosing the forcing terms in an
5063:    inexact Newton method", Utah State University Math. Stat. Dept. Res.
5064:    Report 6/94/75, June, 1994, to appear in SIAM J. Sci. Comput.

5066: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
5067: @*/
5068: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
5069: {
5070:   SNESKSPEW *kctx;

5074:   kctx = (SNESKSPEW*)snes->kspconvctx;
5075:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");

5084:   if (version != PETSC_DEFAULT)   kctx->version   = version;
5085:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
5086:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
5087:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
5088:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
5089:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
5090:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

5092:   if (kctx->version < 1 || kctx->version > 3) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 and 3 are supported: %D",kctx->version);
5093:   if (kctx->rtol_0 < 0.0 || kctx->rtol_0 >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_0 < 1.0: %g",(double)kctx->rtol_0);
5094:   if (kctx->rtol_max < 0.0 || kctx->rtol_max >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= rtol_max (%g) < 1.0\n",(double)kctx->rtol_max);
5095:   if (kctx->gamma < 0.0 || kctx->gamma > 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 <= gamma (%g) <= 1.0\n",(double)kctx->gamma);
5096:   if (kctx->alpha <= 1.0 || kctx->alpha > 2.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"1.0 < alpha (%g) <= 2.0\n",(double)kctx->alpha);
5097:   if (kctx->threshold <= 0.0 || kctx->threshold >= 1.0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"0.0 < threshold (%g) < 1.0\n",(double)kctx->threshold);
5098:   return(0);
5099: }

5101: /*@
5102:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5103:    convergence criteria for the linear solvers within an inexact
5104:    Newton method.

5106:    Not Collective

5108:    Input Parameters:
5109:      snes - SNES context

5111:    Output Parameters:
5112: +    version - version 1, 2 (default is 2) or 3
5113: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5114: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5115: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5116: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5117: .    alpha2 - power for safeguard
5118: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5120:    Level: advanced

5122: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
5123: @*/
5124: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
5125: {
5126:   SNESKSPEW *kctx;

5130:   kctx = (SNESKSPEW*)snes->kspconvctx;
5131:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5132:   if (version)   *version   = kctx->version;
5133:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
5134:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
5135:   if (gamma)     *gamma     = kctx->gamma;
5136:   if (alpha)     *alpha     = kctx->alpha;
5137:   if (alpha2)    *alpha2    = kctx->alpha2;
5138:   if (threshold) *threshold = kctx->threshold;
5139:   return(0);
5140: }

5142:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5143: {
5145:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5146:   PetscReal      rtol  = PETSC_DEFAULT,stol;

5149:   if (!snes->ksp_ewconv) return(0);
5150:   if (!snes->iter) {
5151:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5152:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
5153:   }
5154:   else {
5155:     if (kctx->version == 1) {
5156:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
5157:       if (rtol < 0.0) rtol = -rtol;
5158:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5159:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5160:     } else if (kctx->version == 2) {
5161:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5162:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5163:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5164:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5165:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5166:       /* safeguard: avoid sharp decrease of rtol */
5167:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5168:       stol = PetscMax(rtol,stol);
5169:       rtol = PetscMin(kctx->rtol_0,stol);
5170:       /* safeguard: avoid oversolving */
5171:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5172:       stol = PetscMax(rtol,stol);
5173:       rtol = PetscMin(kctx->rtol_0,stol);
5174:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
5175:   }
5176:   /* safeguard: avoid rtol greater than one */
5177:   rtol = PetscMin(rtol,kctx->rtol_max);
5178:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
5179:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
5180:   return(0);
5181: }

5183: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5184: {
5186:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5187:   PCSide         pcside;
5188:   Vec            lres;

5191:   if (!snes->ksp_ewconv) return(0);
5192:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
5193:   kctx->norm_last = snes->norm;
5194:   if (kctx->version == 1) {
5195:     PC        pc;
5196:     PetscBool isNone;

5198:     KSPGetPC(ksp, &pc);
5199:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
5200:     KSPGetPCSide(ksp,&pcside);
5201:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
5202:       /* KSP residual is true linear residual */
5203:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
5204:     } else {
5205:       /* KSP residual is preconditioned residual */
5206:       /* compute true linear residual norm */
5207:       VecDuplicate(b,&lres);
5208:       MatMult(snes->jacobian,x,lres);
5209:       VecAYPX(lres,-1.0,b);
5210:       VecNorm(lres,NORM_2,&kctx->lresid_last);
5211:       VecDestroy(&lres);
5212:     }
5213:   }
5214:   return(0);
5215: }

5217: /*@
5218:    SNESGetKSP - Returns the KSP context for a SNES solver.

5220:    Not Collective, but if SNES object is parallel, then KSP object is parallel

5222:    Input Parameter:
5223: .  snes - the SNES context

5225:    Output Parameter:
5226: .  ksp - the KSP context

5228:    Notes:
5229:    The user can then directly manipulate the KSP context to set various
5230:    options, etc.  Likewise, the user can then extract and manipulate the
5231:    PC contexts as well.

5233:    Level: beginner

5235: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5236: @*/
5237: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
5238: {


5245:   if (!snes->ksp) {
5246:     PetscBool monitor = PETSC_FALSE;

5248:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
5249:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
5250:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

5252:     KSPSetPreSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPreSolve_SNESEW,snes);
5253:     KSPSetPostSolve(snes->ksp,(PetscErrorCode (*)(KSP,Vec,Vec,void*))KSPPostSolve_SNESEW,snes);

5255:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
5256:     if (monitor) {
5257:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
5258:     }
5259:     monitor = PETSC_FALSE;
5260:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
5261:     if (monitor) {
5262:       PetscObject *objs;
5263:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
5264:       objs[0] = (PetscObject) snes;
5265:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
5266:     }
5267:     PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options);
5268:   }
5269:   *ksp = snes->ksp;
5270:   return(0);
5271: }


5274:  #include <petsc/private/dmimpl.h>
5275: /*@
5276:    SNESSetDM - Sets the DM that may be used by some nonlinear solvers or their underlying preconditioners

5278:    Logically Collective on SNES

5280:    Input Parameters:
5281: +  snes - the nonlinear solver context
5282: -  dm - the dm, cannot be NULL

5284:    Notes:
5285:    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
5286:    even when not using interfaces like DMSNESSetFunction().  Use DMClone() to get a distinct DM when solving different
5287:    problems using the same function space.

5289:    Level: intermediate

5291: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
5292: @*/
5293: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5294: {
5296:   KSP            ksp;
5297:   DMSNES         sdm;

5302:   PetscObjectReference((PetscObject)dm);
5303:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5304:     if (snes->dm->dmsnes && !dm->dmsnes) {
5305:       DMCopyDMSNES(snes->dm,dm);
5306:       DMGetDMSNES(snes->dm,&sdm);
5307:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5308:     }
5309:     DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5310:     DMDestroy(&snes->dm);
5311:   }
5312:   snes->dm     = dm;
5313:   snes->dmAuto = PETSC_FALSE;

5315:   SNESGetKSP(snes,&ksp);
5316:   KSPSetDM(ksp,dm);
5317:   KSPSetDMActive(ksp,PETSC_FALSE);
5318:   if (snes->npc) {
5319:     SNESSetDM(snes->npc, snes->dm);
5320:     SNESSetNPCSide(snes,snes->npcside);
5321:   }
5322:   return(0);
5323: }

5325: /*@
5326:    SNESGetDM - Gets the DM that may be used by some preconditioners

5328:    Not Collective but DM obtained is parallel on SNES

5330:    Input Parameter:
5331: . snes - the preconditioner context

5333:    Output Parameter:
5334: .  dm - the dm

5336:    Level: intermediate

5338: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5339: @*/
5340: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5341: {

5346:   if (!snes->dm) {
5347:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5348:     snes->dmAuto = PETSC_TRUE;
5349:   }
5350:   *dm = snes->dm;
5351:   return(0);
5352: }

5354: /*@
5355:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5357:   Collective on SNES

5359:   Input Parameters:
5360: + snes - iterative context obtained from SNESCreate()
5361: - pc   - the preconditioner object

5363:   Notes:
5364:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5365:   to configure it using the API).

5367:   Level: developer

5369: .seealso: SNESGetNPC(), SNESHasNPC()
5370: @*/
5371: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5372: {

5379:   PetscObjectReference((PetscObject) pc);
5380:   SNESDestroy(&snes->npc);
5381:   snes->npc = pc;
5382:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5383:   return(0);
5384: }

5386: /*@
5387:   SNESGetNPC - Creates a nonlinear preconditioning solver (SNES) to be used to precondition the nonlinear solver.

5389:   Not Collective; but any changes to the obtained SNES object must be applied collectively

5391:   Input Parameter:
5392: . snes - iterative context obtained from SNESCreate()

5394:   Output Parameter:
5395: . pc - preconditioner context

5397:   Options Database:
5398: . -npc_snes_type <type> - set the type of the SNES to use as the nonlinear preconditioner

5400:   Notes:
5401:     If a SNES was previously set with SNESSetNPC() then that SNES is returned, otherwise a new SNES object is created.

5403:     The (preconditioner) SNES returned automatically inherits the same nonlinear function and Jacobian supplied to the original
5404:     SNES during SNESSetUp()

5406:   Level: developer

5408: .seealso: SNESSetNPC(), SNESHasNPC(), SNES, SNESCreate()
5409: @*/
5410: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5411: {
5413:   const char     *optionsprefix;

5418:   if (!snes->npc) {
5419:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5420:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5421:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5422:     SNESGetOptionsPrefix(snes,&optionsprefix);
5423:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5424:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5425:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5426:   }
5427:   *pc = snes->npc;
5428:   return(0);
5429: }

5431: /*@
5432:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5434:   Not Collective

5436:   Input Parameter:
5437: . snes - iterative context obtained from SNESCreate()

5439:   Output Parameter:
5440: . has_npc - whether the SNES has an NPC or not

5442:   Level: developer

5444: .seealso: SNESSetNPC(), SNESGetNPC()
5445: @*/
5446: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5447: {
5450:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5451:   return(0);
5452: }

5454: /*@
5455:     SNESSetNPCSide - Sets the preconditioning side.

5457:     Logically Collective on SNES

5459:     Input Parameter:
5460: .   snes - iterative context obtained from SNESCreate()

5462:     Output Parameter:
5463: .   side - the preconditioning side, where side is one of
5464: .vb
5465:       PC_LEFT - left preconditioning
5466:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5467: .ve

5469:     Options Database Keys:
5470: .   -snes_pc_side <right,left>

5472:     Notes:
5473:     SNESNRICHARDSON and SNESNCG only support left preconditioning.

5475:     Level: intermediate

5477: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5478: @*/
5479: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5480: {
5484:   snes->npcside= side;
5485:   return(0);
5486: }

5488: /*@
5489:     SNESGetNPCSide - Gets the preconditioning side.

5491:     Not Collective

5493:     Input Parameter:
5494: .   snes - iterative context obtained from SNESCreate()

5496:     Output Parameter:
5497: .   side - the preconditioning side, where side is one of
5498: .vb
5499:       PC_LEFT - left preconditioning
5500:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5501: .ve

5503:     Level: intermediate

5505: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5506: @*/
5507: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5508: {
5512:   *side = snes->npcside;
5513:   return(0);
5514: }

5516: /*@
5517:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5519:   Collective on SNES

5521:   Input Parameters:
5522: + snes - iterative context obtained from SNESCreate()
5523: - linesearch   - the linesearch object

5525:   Notes:
5526:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5527:   to configure it using the API).

5529:   Level: developer

5531: .seealso: SNESGetLineSearch()
5532: @*/
5533: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5534: {

5541:   PetscObjectReference((PetscObject) linesearch);
5542:   SNESLineSearchDestroy(&snes->linesearch);

5544:   snes->linesearch = linesearch;

5546:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5547:   return(0);
5548: }

5550: /*@
5551:   SNESGetLineSearch - Returns a pointer to the line search context set with SNESSetLineSearch()
5552:   or creates a default line search instance associated with the SNES and returns it.

5554:   Not Collective

5556:   Input Parameter:
5557: . snes - iterative context obtained from SNESCreate()

5559:   Output Parameter:
5560: . linesearch - linesearch context

5562:   Level: beginner

5564: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5565: @*/
5566: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5567: {
5569:   const char     *optionsprefix;

5574:   if (!snes->linesearch) {
5575:     SNESGetOptionsPrefix(snes, &optionsprefix);
5576:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5577:     SNESLineSearchSetSNES(snes->linesearch, snes);
5578:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5579:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5580:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5581:   }
5582:   *linesearch = snes->linesearch;
5583:   return(0);
5584: }