Actual source code: snes.c

petsc-3.13.6 2020-09-29
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 Section 1.5 Writing Application Codes with PETSc 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);
472:       PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));
473:       PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR);
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 the users manual

894:    Notes:
895:       SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explictly with
896:       finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.

898:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

986:   flg  = PETSC_FALSE;
987:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
988:   if (set && flg) {SNESMonitorCancel(snes);}

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

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

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

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

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

1018:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
1019:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
1020:   }

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

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

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

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

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

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

1093:   for (i = 0; i < numberofsetfromoptions; i++) {
1094:     (*othersetfromoptions[i])(snes);
1095:   }

1097:   if (snes->ops->setfromoptions) {
1098:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
1099:   }

1101:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1102:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
1103:   PetscOptionsEnd();

1105:   if (snes->linesearch) {
1106:     SNESGetLineSearch(snes, &snes->linesearch);
1107:     SNESLineSearchSetFromOptions(snes->linesearch);
1108:   }

1110:   if (snes->usesksp) {
1111:     if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
1112:     KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
1113:     KSPSetFromOptions(snes->ksp);
1114:   }

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

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

1132:    Collective on SNES

1134:    Input Parameter:
1135: .  snes - the SNES context

1137:    Level: beginner

1139: .seealso: SNESSetFromOptions(), SNESSetOptionsPrefix()
1140: @*/
1141: PetscErrorCode SNESResetFromOptions(SNES snes)
1142: {

1146:   if (snes->setfromoptionscalled) {SNESSetFromOptions(snes);}
1147:   return(0);
1148: }

1150: /*@C
1151:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1152:    the nonlinear solvers.

1154:    Logically Collective on SNES

1156:    Input Parameters:
1157: +  snes - the SNES context
1158: .  compute - function to compute the context
1159: -  destroy - function to destroy the context

1161:    Level: intermediate

1163:    Notes:
1164:    This function is currently not available from Fortran.

1166: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1167: @*/
1168: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1169: {
1172:   snes->ops->usercompute = compute;
1173:   snes->ops->userdestroy = destroy;
1174:   return(0);
1175: }

1177: /*@
1178:    SNESSetApplicationContext - Sets the optional user-defined context for
1179:    the nonlinear solvers.

1181:    Logically Collective on SNES

1183:    Input Parameters:
1184: +  snes - the SNES context
1185: -  usrP - optional user context

1187:    Level: intermediate

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

1193: .seealso: SNESGetApplicationContext()
1194: @*/
1195: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1196: {
1198:   KSP            ksp;

1202:   SNESGetKSP(snes,&ksp);
1203:   KSPSetApplicationContext(ksp,usrP);
1204:   snes->user = usrP;
1205:   return(0);
1206: }

1208: /*@
1209:    SNESGetApplicationContext - Gets the user-defined context for the
1210:    nonlinear solvers.

1212:    Not Collective

1214:    Input Parameter:
1215: .  snes - SNES context

1217:    Output Parameter:
1218: .  usrP - user context

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

1224:    Level: intermediate

1226: .seealso: SNESSetApplicationContext()
1227: @*/
1228: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1229: {
1232:   *(void**)usrP = snes->user;
1233:   return(0);
1234: }

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

1239:    Collective on SNES

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

1246:    Options Database:
1247: + -snes_mf - use matrix free for both the mat and pmat operator
1248: . -snes_mf_operator - use matrix free only for the mat operator
1249: . -snes_fd_color - compute the Jacobian via coloring and finite differences.
1250: - -snes_fd - compute the Jacobian via finite differences (slow)

1252:    Level: intermediate

1254:    Notes:
1255:       SNES supports three approaches for computing (approximate) Jacobians: user provided via SNESSetJacobian(), matrix free, and computing explictly with
1256:       finite differences and coloring using MatFDColoring. It is also possible to use automatic differentiation and the MatFDColoring object.

1258: .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF(), SNESComputeJacobianDefaultColor()
1259: @*/
1260: PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1261: {
1266:   snes->mf          = mf_operator ? PETSC_TRUE : mf;
1267:   snes->mf_operator = mf_operator;
1268:   return(0);
1269: }

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

1274:    Collective on SNES

1276:    Input Parameter:
1277: .  snes - SNES context

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

1283:    Options Database:
1284: + -snes_mf - use matrix free for both the mat and pmat operator
1285: - -snes_mf_operator - use matrix free only for the mat operator

1287:    Level: intermediate

1289: .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
1290: @*/
1291: PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1292: {
1295:   if (mf)          *mf          = snes->mf;
1296:   if (mf_operator) *mf_operator = snes->mf_operator;
1297:   return(0);
1298: }

1300: /*@
1301:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1302:    at this time.

1304:    Not Collective

1306:    Input Parameter:
1307: .  snes - SNES context

1309:    Output Parameter:
1310: .  iter - iteration number

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

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

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

1328:    Level: intermediate

1330: .seealso:   SNESGetLinearSolveIterations()
1331: @*/
1332: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1333: {
1337:   *iter = snes->iter;
1338:   return(0);
1339: }

1341: /*@
1342:    SNESSetIterationNumber - Sets the current iteration number.

1344:    Not Collective

1346:    Input Parameter:
1347: +  snes - SNES context
1348: -  iter - iteration number

1350:    Level: developer

1352: .seealso:   SNESGetLinearSolveIterations()
1353: @*/
1354: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1355: {

1360:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1361:   snes->iter = iter;
1362:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1363:   return(0);
1364: }

1366: /*@
1367:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1368:    attempted by the nonlinear solver.

1370:    Not Collective

1372:    Input Parameter:
1373: .  snes - SNES context

1375:    Output Parameter:
1376: .  nfails - number of unsuccessful steps attempted

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

1381:    Level: intermediate

1383: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1384:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1385: @*/
1386: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1387: {
1391:   *nfails = snes->numFailures;
1392:   return(0);
1393: }

1395: /*@
1396:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1397:    attempted by the nonlinear solver before it gives up.

1399:    Not Collective

1401:    Input Parameters:
1402: +  snes     - SNES context
1403: -  maxFails - maximum of unsuccessful steps

1405:    Level: intermediate

1407: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1408:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1409: @*/
1410: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1411: {
1414:   snes->maxFailures = maxFails;
1415:   return(0);
1416: }

1418: /*@
1419:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1420:    attempted by the nonlinear solver before it gives up.

1422:    Not Collective

1424:    Input Parameter:
1425: .  snes     - SNES context

1427:    Output Parameter:
1428: .  maxFails - maximum of unsuccessful steps

1430:    Level: intermediate

1432: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1433:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

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

1445: /*@
1446:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1447:      done by SNES.

1449:    Not Collective

1451:    Input Parameter:
1452: .  snes     - SNES context

1454:    Output Parameter:
1455: .  nfuncs - number of evaluations

1457:    Level: intermediate

1459:    Notes:
1460:     Reset every time SNESSolve is called unless SNESSetCountersReset() is used.

1462: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1463: @*/
1464: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1465: {
1469:   *nfuncs = snes->nfuncs;
1470:   return(0);
1471: }

1473: /*@
1474:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1475:    linear solvers.

1477:    Not Collective

1479:    Input Parameter:
1480: .  snes - SNES context

1482:    Output Parameter:
1483: .  nfails - number of failed solves

1485:    Level: intermediate

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

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

1493: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1494: @*/
1495: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1496: {
1500:   *nfails = snes->numLinearSolveFailures;
1501:   return(0);
1502: }

1504: /*@
1505:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1506:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1508:    Logically Collective on SNES

1510:    Input Parameters:
1511: +  snes     - SNES context
1512: -  maxFails - maximum allowed linear solve failures

1514:    Level: intermediate

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

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

1522: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1523: @*/
1524: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1525: {
1529:   snes->maxLinearSolveFailures = maxFails;
1530:   return(0);
1531: }

1533: /*@
1534:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1535:      are allowed before SNES terminates

1537:    Not Collective

1539:    Input Parameter:
1540: .  snes     - SNES context

1542:    Output Parameter:
1543: .  maxFails - maximum of unsuccessful solves allowed

1545:    Level: intermediate

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

1550: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1551: @*/
1552: PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1553: {
1557:   *maxFails = snes->maxLinearSolveFailures;
1558:   return(0);
1559: }

1561: /*@
1562:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1563:    used by the nonlinear solver.

1565:    Not Collective

1567:    Input Parameter:
1568: .  snes - SNES context

1570:    Output Parameter:
1571: .  lits - number of linear iterations

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

1576:    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
1577:    then call KSPGetIterationNumber() after the failed solve.

1579:    Level: intermediate

1581: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1582: @*/
1583: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1584: {
1588:   *lits = snes->linear_its;
1589:   return(0);
1590: }

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

1596:    Logically Collective on SNES

1598:    Input Parameter:
1599: +  snes - SNES context
1600: -  reset - whether to reset the counters or not

1602:    Notes:
1603:    This defaults to PETSC_TRUE

1605:    Level: developer

1607: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1608: @*/
1609: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1610: {
1614:   snes->counters_reset = reset;
1615:   return(0);
1616: }


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

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

1624:    Input Parameters:
1625: +  snes - the SNES context
1626: -  ksp - the KSP context

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

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

1635:    Level: developer

1637: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1638: @*/
1639: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1640: {

1647:   PetscObjectReference((PetscObject)ksp);
1648:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1649:   snes->ksp = ksp;
1650:   return(0);
1651: }

1653: /* -----------------------------------------------------------*/
1654: /*@
1655:    SNESCreate - Creates a nonlinear solver context.

1657:    Collective

1659:    Input Parameters:
1660: .  comm - MPI communicator

1662:    Output Parameter:
1663: .  outsnes - the new SNES context

1665:    Options Database Keys:
1666: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1667:                and no preconditioning matrix
1668: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1669:                products, and a user-provided preconditioning matrix
1670:                as set by SNESSetJacobian()
1671: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1673:    Level: beginner

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

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

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

1687: @*/
1688: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1689: {
1691:   SNES           snes;
1692:   SNESKSPEW      *kctx;

1696:   *outsnes = NULL;
1697:   SNESInitializePackage();

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

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

1763:   snes->mf          = PETSC_FALSE;
1764:   snes->mf_operator = PETSC_FALSE;
1765:   snes->mf_version  = 1;

1767:   snes->numLinearSolveFailures = 0;
1768:   snes->maxLinearSolveFailures = 1;

1770:   snes->vizerotolerance = 1.e-8;
1771: #if defined(PETSC_USE_DEBUG)
1772:   snes->checkjacdomainerror = PETSC_TRUE;
1773: #else
1774:   snes->checkjacdomainerror = PETSC_FALSE;
1775: #endif

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

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

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

1796:   *outsnes = snes;
1797:   return(0);
1798: }

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

1803:      Synopsis:
1804:      #include "petscsnes.h"
1805:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1807:      Collective on snes

1809:      Input Parameters:
1810: +     snes - the SNES context
1811: .     x    - state at which to evaluate residual
1812: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1814:      Output Parameter:
1815: .     f  - vector to put residual (function value)

1817:    Level: intermediate

1819: .seealso:   SNESSetFunction(), SNESGetFunction()
1820: M*/

1822: /*@C
1823:    SNESSetFunction - Sets the function evaluation routine and function
1824:    vector for use by the SNES routines in solving systems of nonlinear
1825:    equations.

1827:    Logically Collective on SNES

1829:    Input Parameters:
1830: +  snes - the SNES context
1831: .  r - vector to store function value
1832: .  f - function evaluation routine; see SNESFunction for calling sequence details
1833: -  ctx - [optional] user-defined context for private data for the
1834:          function evaluation routine (may be NULL)

1836:    Notes:
1837:    The Newton-like methods typically solve linear systems of the form
1838: $      f'(x) x = -f(x),
1839:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1841:    Level: beginner

1843: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1844: @*/
1845: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1846: {
1848:   DM             dm;

1852:   if (r) {
1855:     PetscObjectReference((PetscObject)r);
1856:     VecDestroy(&snes->vec_func);

1858:     snes->vec_func = r;
1859:   }
1860:   SNESGetDM(snes,&dm);
1861:   DMSNESSetFunction(dm,f,ctx);
1862:   return(0);
1863: }


1866: /*@C
1867:    SNESSetInitialFunction - Sets the function vector to be used as the
1868:    function norm at the initialization of the method.  In some
1869:    instances, the user has precomputed the function before calling
1870:    SNESSolve.  This function allows one to avoid a redundant call
1871:    to SNESComputeFunction in that case.

1873:    Logically Collective on SNES

1875:    Input Parameters:
1876: +  snes - the SNES context
1877: -  f - vector to store function value

1879:    Notes:
1880:    This should not be modified during the solution procedure.

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

1884:    Level: developer

1886: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1887: @*/
1888: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1889: {
1891:   Vec            vec_func;

1897:   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1898:     snes->vec_func_init_set = PETSC_FALSE;
1899:     return(0);
1900:   }
1901:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1902:   VecCopy(f, vec_func);

1904:   snes->vec_func_init_set = PETSC_TRUE;
1905:   return(0);
1906: }

1908: /*@
1909:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1910:    of the SNES method.

1912:    Logically Collective on SNES

1914:    Input Parameters:
1915: +  snes - the SNES context
1916: -  normschedule - the frequency of norm computation

1918:    Options Database Key:
1919: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1930:    Level: developer

1932: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1933: @*/
1934: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1935: {
1938:   snes->normschedule = normschedule;
1939:   return(0);
1940: }


1943: /*@
1944:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1945:    of the SNES method.

1947:    Logically Collective on SNES

1949:    Input Parameters:
1950: +  snes - the SNES context
1951: -  normschedule - the type of the norm used

1953:    Level: advanced

1955: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1956: @*/
1957: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1958: {
1961:   *normschedule = snes->normschedule;
1962:   return(0);
1963: }


1966: /*@
1967:   SNESSetFunctionNorm - Sets the last computed residual norm.

1969:   Logically Collective on SNES

1971:   Input Parameters:
1972: + snes - the SNES context

1974: - normschedule - the frequency of norm computation

1976:   Level: developer

1978: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1979: @*/
1980: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1981: {
1984:   snes->norm = norm;
1985:   return(0);
1986: }

1988: /*@
1989:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1991:   Not Collective

1993:   Input Parameter:
1994: . snes - the SNES context

1996:   Output Parameter:
1997: . norm - the last computed residual norm

1999:   Level: developer

2001: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2002: @*/
2003: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
2004: {
2008:   *norm = snes->norm;
2009:   return(0);
2010: }

2012: /*@
2013:   SNESGetUpdateNorm - Gets the last computed norm of the Newton update

2015:   Not Collective

2017:   Input Parameter:
2018: . snes - the SNES context

2020:   Output Parameter:
2021: . ynorm - the last computed update norm

2023:   Level: developer

2025: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm()
2026: @*/
2027: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2028: {
2032:   *ynorm = snes->ynorm;
2033:   return(0);
2034: }

2036: /*@
2037:   SNESGetSolutionNorm - Gets the last computed norm of the solution

2039:   Not Collective

2041:   Input Parameter:
2042: . snes - the SNES context

2044:   Output Parameter:
2045: . xnorm - the last computed solution norm

2047:   Level: developer

2049: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm(), SNESGetUpdateNorm()
2050: @*/
2051: PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2052: {
2056:   *xnorm = snes->xnorm;
2057:   return(0);
2058: }

2060: /*@C
2061:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
2062:    of the SNES method.

2064:    Logically Collective on SNES

2066:    Input Parameters:
2067: +  snes - the SNES context
2068: -  normschedule - the frequency of norm computation

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

2079:    Level: developer

2081: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2082: @*/
2083: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
2084: {
2087:   snes->functype = type;
2088:   return(0);
2089: }


2092: /*@C
2093:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
2094:    of the SNES method.

2096:    Logically Collective on SNES

2098:    Input Parameters:
2099: +  snes - the SNES context
2100: -  normschedule - the type of the norm used

2102:    Level: advanced

2104: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
2105: @*/
2106: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
2107: {
2110:   *type = snes->functype;
2111:   return(0);
2112: }

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

2117:      Synopsis:
2118:  #include <petscsnes.h>
2119: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

2121:      Collective on snes

2123:      Input Parameters:
2124: +  X   - solution vector
2125: .  B   - RHS vector
2126: -  ctx - optional user-defined Gauss-Seidel context

2128:      Output Parameter:
2129: .  X   - solution vector

2131:    Level: intermediate

2133: .seealso:   SNESSetNGS(), SNESGetNGS()
2134: M*/

2136: /*@C
2137:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2138:    use with composed nonlinear solvers.

2140:    Input Parameters:
2141: +  snes   - the SNES context
2142: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
2143: -  ctx    - [optional] user-defined context for private data for the
2144:             smoother evaluation routine (may be NULL)

2146:    Notes:
2147:    The NGS routines are used by the composed nonlinear solver to generate
2148:     a problem appropriate update to the solution, particularly FAS.

2150:    Level: intermediate

2152: .seealso: SNESGetFunction(), SNESComputeNGS()
2153: @*/
2154: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
2155: {
2157:   DM             dm;

2161:   SNESGetDM(snes,&dm);
2162:   DMSNESSetNGS(dm,f,ctx);
2163:   return(0);
2164: }

2166: PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
2167: {
2169:   DM             dm;
2170:   DMSNES         sdm;

2173:   SNESGetDM(snes,&dm);
2174:   DMGetDMSNES(dm,&sdm);
2175:   if (!sdm->ops->computepfunction) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");
2176:   if (!sdm->ops->computepjacobian) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2177:   /*  A(x)*x - b(x) */
2178:   PetscStackPush("SNES Picard user function");
2179:   (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
2180:   PetscStackPop;
2181:   PetscStackPush("SNES Picard user Jacobian");
2182:   (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
2183:   PetscStackPop;
2184:   VecScale(f,-1.0);
2185:   MatMultAdd(snes->jacobian,x,f,f);
2186:   return(0);
2187: }

2189: PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
2190: {
2192:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2193:   return(0);
2194: }

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

2199:    Logically Collective on SNES

2201:    Input Parameters:
2202: +  snes - the SNES context
2203: .  r - vector to store function value
2204: .  b - function evaluation routine
2205: .  Amat - matrix with which A(x) x - b(x) is to be computed
2206: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2207: .  J  - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
2208: -  ctx - [optional] user-defined context for private data for the
2209:          function evaluation routine (may be NULL)

2211:    Notes:
2212:     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
2213:     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.

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

2217: $     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}
2218: $     Note that when an exact solver is used this corresponds to the "classic" Picard A(x^{n}) x^{n+1} = b(x^{n}) iteration.

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

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

2225:    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
2226:    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
2227:    different please contact us at petsc-dev@mcs.anl.gov and we'll have an entirely new argument :-).

2229:    Level: intermediate

2231: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2232: @*/
2233: 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)
2234: {
2236:   DM             dm;

2240:   SNESGetDM(snes, &dm);
2241:   DMSNESSetPicard(dm,b,J,ctx);
2242:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2243:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2244:   return(0);
2245: }

2247: /*@C
2248:    SNESGetPicard - Returns the context for the Picard iteration

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

2252:    Input Parameter:
2253: .  snes - the SNES context

2255:    Output Parameter:
2256: +  r - the function (or NULL)
2257: .  f - the function (or NULL); see SNESFunction for calling sequence details
2258: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2259: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2260: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2261: -  ctx - the function context (or NULL)

2263:    Level: advanced

2265: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2266: @*/
2267: 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)
2268: {
2270:   DM             dm;

2274:   SNESGetFunction(snes,r,NULL,NULL);
2275:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2276:   SNESGetDM(snes,&dm);
2277:   DMSNESGetPicard(dm,f,J,ctx);
2278:   return(0);
2279: }

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

2284:    Logically Collective on SNES

2286:    Input Parameters:
2287: +  snes - the SNES context
2288: .  func - function evaluation routine
2289: -  ctx - [optional] user-defined context for private data for the
2290:          function evaluation routine (may be NULL)

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

2295: .  f - function vector
2296: -  ctx - optional user-defined function context

2298:    Level: intermediate

2300: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2301: @*/
2302: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2303: {
2306:   if (func) snes->ops->computeinitialguess = func;
2307:   if (ctx)  snes->initialguessP            = ctx;
2308:   return(0);
2309: }

2311: /* --------------------------------------------------------------- */
2312: /*@C
2313:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2314:    it assumes a zero right hand side.

2316:    Logically Collective on SNES

2318:    Input Parameter:
2319: .  snes - the SNES context

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

2324:    Level: intermediate

2326: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2327: @*/
2328: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2329: {
2333:   *rhs = snes->vec_rhs;
2334:   return(0);
2335: }

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

2340:    Collective on SNES

2342:    Input Parameters:
2343: +  snes - the SNES context
2344: -  x - input vector

2346:    Output Parameter:
2347: .  y - function vector, as set by SNESSetFunction()

2349:    Notes:
2350:    SNESComputeFunction() is typically used within nonlinear solvers
2351:    implementations, so most users would not generally call this routine
2352:    themselves.

2354:    Level: developer

2356: .seealso: SNESSetFunction(), SNESGetFunction()
2357: @*/
2358: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2359: {
2361:   DM             dm;
2362:   DMSNES         sdm;

2370:   VecValidValues(x,2,PETSC_TRUE);

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

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

2408:    Collective on SNES

2410:    Input Parameters:
2411: +  snes - the SNES context
2412: .  x - input vector
2413: -  b - rhs vector

2415:    Output Parameter:
2416: .  x - new solution vector

2418:    Notes:
2419:    SNESComputeNGS() is typically used within composed nonlinear solver
2420:    implementations, so most users would not generally call this routine
2421:    themselves.

2423:    Level: developer

2425: .seealso: SNESSetNGS(), SNESComputeFunction()
2426: @*/
2427: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2428: {
2430:   DM             dm;
2431:   DMSNES         sdm;

2439:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2440:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2441:   SNESGetDM(snes,&dm);
2442:   DMGetDMSNES(dm,&sdm);
2443:   if (sdm->ops->computegs) {
2444:     if (b) {VecLockReadPush(b);}
2445:     PetscStackPush("SNES user NGS");
2446:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2447:     PetscStackPop;
2448:     if (b) {VecLockReadPop(b);}
2449:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2450:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2451:   return(0);
2452: }

2454: PetscErrorCode SNESTestJacobian(SNES snes)
2455: {
2456:   Mat               A,B,C,D,jacobian;
2457:   Vec               x = snes->vec_sol,f = snes->vec_func;
2458:   PetscErrorCode    ierr;
2459:   PetscReal         nrm,gnorm;
2460:   PetscReal         threshold = 1.e-5;
2461:   MatType           mattype;
2462:   PetscInt          m,n,M,N;
2463:   void              *functx;
2464:   PetscBool         complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg,istranspose;
2465:   PetscViewer       viewer,mviewer;
2466:   MPI_Comm          comm;
2467:   PetscInt          tabs;
2468:   static PetscBool  directionsprinted = PETSC_FALSE;
2469:   PetscViewerFormat format;

2472:   PetscObjectOptionsBegin((PetscObject)snes);
2473:   PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test);
2474:   PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL);
2475:   PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print);
2476:   if (!complete_print) {
2477:     PetscOptionsDeprecated("-snes_test_jacobian_display","-snes_test_jacobian_view","3.13",NULL);
2478:     PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print);
2479:   }
2480:   /* for compatibility with PETSc 3.9 and older. */
2481:   PetscOptionsDeprecated("-snes_test_jacobian_display_threshold","-snes_test_jacobian","3.13","-snes_test_jacobian accepts an optional threshold (since v3.10)");
2482:   PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print);
2483:   PetscOptionsEnd();
2484:   if (!test) return(0);

2486:   PetscObjectGetComm((PetscObject)snes,&comm);
2487:   PetscViewerASCIIGetStdout(comm,&viewer);
2488:   PetscViewerASCIIGetTab(viewer, &tabs);
2489:   PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);
2490:   PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n");
2491:   if (!complete_print && !directionsprinted) {
2492:     PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n");
2493:     PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n");
2494:   }
2495:   if (!directionsprinted) {
2496:     PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n");
2497:     PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n");
2498:     directionsprinted = PETSC_TRUE;
2499:   }
2500:   if (complete_print) {
2501:     PetscViewerPushFormat(mviewer,format);
2502:   }

2504:   PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg);
2505:   if (!flg) jacobian = snes->jacobian;
2506:   else jacobian = snes->jacobian_pre;

2508:   if (!x) {
2509:     MatCreateVecs(jacobian, &x, NULL);
2510:   } else {
2511:     PetscObjectReference((PetscObject) x);
2512:   }
2513:   if (!f) {
2514:     VecDuplicate(x, &f);
2515:   } else {
2516:     PetscObjectReference((PetscObject) f);
2517:   }
2518:   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2519:   SNESComputeFunction(snes,x,f);
2520:   VecDestroy(&f);
2521:   PetscObjectTypeCompare((PetscObject)snes,SNESKSPTRANSPOSEONLY,&istranspose);
2522:   while (jacobian) {
2523:     Mat JT = NULL, Jsave = NULL;

2525:     if (istranspose) {
2526:       MatCreateTranspose(jacobian,&JT);
2527:       Jsave = jacobian;
2528:       jacobian = JT;
2529:     }
2530:     PetscObjectBaseTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPISBAIJ,"");
2531:     if (flg) {
2532:       A    = jacobian;
2533:       PetscObjectReference((PetscObject)A);
2534:     } else {
2535:       MatComputeOperator(jacobian,MATAIJ,&A);
2536:     }

2538:     MatGetType(A,&mattype);
2539:     MatGetSize(A,&M,&N);
2540:     MatGetLocalSize(A,&m,&n);
2541:     MatCreate(PetscObjectComm((PetscObject)A),&B);
2542:     MatSetType(B,mattype);
2543:     MatSetSizes(B,m,n,M,N);
2544:     MatSetBlockSizesFromMats(B,A,A);
2545:     MatSetUp(B);
2546:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2548:     SNESGetFunction(snes,NULL,NULL,&functx);
2549:     SNESComputeJacobianDefault(snes,x,B,B,functx);

2551:     MatDuplicate(B,MAT_COPY_VALUES,&D);
2552:     MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2553:     MatNorm(D,NORM_FROBENIUS,&nrm);
2554:     MatNorm(A,NORM_FROBENIUS,&gnorm);
2555:     MatDestroy(&D);
2556:     if (!gnorm) gnorm = 1; /* just in case */
2557:     PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm);

2559:     if (complete_print) {
2560:       PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n");
2561:       MatView(A,mviewer);
2562:       PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n");
2563:       MatView(B,mviewer);
2564:     }

2566:     if (threshold_print || complete_print) {
2567:       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2568:       PetscScalar       *cvals;
2569:       const PetscInt    *bcols;
2570:       const PetscScalar *bvals;

2572:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2573:       MatSetType(C,mattype);
2574:       MatSetSizes(C,m,n,M,N);
2575:       MatSetBlockSizesFromMats(C,A,A);
2576:       MatSetUp(C);
2577:       MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2579:       MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2580:       MatGetOwnershipRange(B,&Istart,&Iend);

2582:       for (row = Istart; row < Iend; row++) {
2583:         MatGetRow(B,row,&bncols,&bcols,&bvals);
2584:         PetscMalloc2(bncols,&ccols,bncols,&cvals);
2585:         for (j = 0, cncols = 0; j < bncols; j++) {
2586:           if (PetscAbsScalar(bvals[j]) > threshold) {
2587:             ccols[cncols] = bcols[j];
2588:             cvals[cncols] = bvals[j];
2589:             cncols += 1;
2590:           }
2591:         }
2592:         if (cncols) {
2593:           MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES);
2594:         }
2595:         MatRestoreRow(B,row,&bncols,&bcols,&bvals);
2596:         PetscFree2(ccols,cvals);
2597:       }
2598:       MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2599:       MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
2600:       PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold);
2601:       MatView(C,complete_print ? mviewer : viewer);
2602:       MatDestroy(&C);
2603:     }
2604:     MatDestroy(&A);
2605:     MatDestroy(&B);
2606:     MatDestroy(&JT);
2607:     if (Jsave) jacobian = Jsave;
2608:     if (jacobian != snes->jacobian_pre) {
2609:       jacobian = snes->jacobian_pre;
2610:       PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n");
2611:     }
2612:     else jacobian = NULL;
2613:   }
2614:   VecDestroy(&x);
2615:   if (complete_print) {
2616:     PetscViewerPopFormat(mviewer);
2617:   }
2618:   if (mviewer) { PetscViewerDestroy(&mviewer); }
2619:   PetscViewerASCIISetTab(viewer,tabs);
2620:   return(0);
2621: }

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

2626:    Collective on SNES

2628:    Input Parameters:
2629: +  snes - the SNES context
2630: -  x - input vector

2632:    Output Parameters:
2633: +  A - Jacobian matrix
2634: -  B - optional preconditioning matrix

2636:   Options Database Keys:
2637: +    -snes_lag_preconditioner <lag>
2638: .    -snes_lag_jacobian <lag>
2639: .    -snes_test_jacobian <optional threshold> - compare the user provided Jacobian with one compute via finite differences to check for errors.  If a threshold is given, display only those entries whose difference is greater than the threshold.
2640: .    -snes_test_jacobian_view - 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
2641: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2642: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2643: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2644: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2645: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2646: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2647: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2648: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2649: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2650: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2651: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2654:    Notes:
2655:    Most users should not need to explicitly call this routine, as it
2656:    is used internally within the nonlinear solvers.

2658:    Developer Notes:
2659:     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
2660:       for with the SNESType of test that has been removed.

2662:    Level: developer

2664: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2665: @*/
2666: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2667: {
2669:   PetscBool      flag;
2670:   DM             dm;
2671:   DMSNES         sdm;
2672:   KSP            ksp;

2678:   VecValidValues(X,2,PETSC_TRUE);
2679:   SNESGetDM(snes,&dm);
2680:   DMGetDMSNES(dm,&sdm);

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

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

2686:   if (snes->lagjacobian == -2) {
2687:     snes->lagjacobian = -1;

2689:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2690:   } else if (snes->lagjacobian == -1) {
2691:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2692:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2693:     if (flag) {
2694:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2695:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2696:     }
2697:     return(0);
2698:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2699:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2700:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2701:     if (flag) {
2702:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2703:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2704:     }
2705:     return(0);
2706:   }
2707:   if (snes->npc && snes->npcside== PC_LEFT) {
2708:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2709:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2710:     return(0);
2711:   }

2713:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2714:   VecLockReadPush(X);
2715:   PetscStackPush("SNES user Jacobian function");
2716:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2717:   PetscStackPop;
2718:   VecLockReadPop(X);
2719:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

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

2724:   /* the next line ensures that snes->ksp exists */
2725:   SNESGetKSP(snes,&ksp);
2726:   if (snes->lagpreconditioner == -2) {
2727:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2728:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2729:     snes->lagpreconditioner = -1;
2730:   } else if (snes->lagpreconditioner == -1) {
2731:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2732:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2733:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2734:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2735:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2736:   } else {
2737:     PetscInfo(snes,"Rebuilding preconditioner\n");
2738:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2739:   }

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

2817:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2818:       MatColoringCreate(Bfd,&coloring);
2819:       MatColoringSetType(coloring,MATCOLORINGSL);
2820:       MatColoringSetFromOptions(coloring);
2821:       MatColoringApply(coloring,&iscoloring);
2822:       MatColoringDestroy(&coloring);
2823:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2824:       MatFDColoringSetFromOptions(matfdcoloring);
2825:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2826:       ISColoringDestroy(&iscoloring);

2828:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2829:       SNESGetFunction(snes,NULL,&func,&funcctx);
2830:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2831:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2832:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2833:       MatFDColoringSetFromOptions(matfdcoloring);
2834:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2835:       MatFDColoringDestroy(&matfdcoloring);

2837:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2838:       if (flag_draw || flag_contour) {
2839:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2840:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2841:       } else vdraw = NULL;
2842:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2843:       if (flag_display) {MatView(B,vstdout);}
2844:       if (vdraw) {MatView(B,vdraw);}
2845:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2846:       if (flag_display) {MatView(Bfd,vstdout);}
2847:       if (vdraw) {MatView(Bfd,vdraw);}
2848:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2849:       MatNorm(Bfd,NORM_1,&norm1);
2850:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2851:       MatNorm(Bfd,NORM_MAX,&normmax);
2852:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2853:       if (flag_display) {MatView(Bfd,vstdout);}
2854:       if (vdraw) {              /* Always use contour for the difference */
2855:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2856:         MatView(Bfd,vdraw);
2857:         PetscViewerPopFormat(vdraw);
2858:       }
2859:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2861:       if (flag_threshold) {
2862:         PetscInt bs,rstart,rend,i;
2863:         MatGetBlockSize(B,&bs);
2864:         MatGetOwnershipRange(B,&rstart,&rend);
2865:         for (i=rstart; i<rend; i++) {
2866:           const PetscScalar *ba,*ca;
2867:           const PetscInt    *bj,*cj;
2868:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2869:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2870:           MatGetRow(B,i,&bn,&bj,&ba);
2871:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2872:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2873:           for (j=0; j<bn; j++) {
2874:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2875:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2876:               maxentrycol = bj[j];
2877:               maxentry    = PetscRealPart(ba[j]);
2878:             }
2879:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2880:               maxdiffcol = bj[j];
2881:               maxdiff    = PetscRealPart(ca[j]);
2882:             }
2883:             if (rdiff > maxrdiff) {
2884:               maxrdiffcol = bj[j];
2885:               maxrdiff    = rdiff;
2886:             }
2887:           }
2888:           if (maxrdiff > 1) {
2889:             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);
2890:             for (j=0; j<bn; j++) {
2891:               PetscReal rdiff;
2892:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2893:               if (rdiff > 1) {
2894:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2895:               }
2896:             }
2897:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2898:           }
2899:           MatRestoreRow(B,i,&bn,&bj,&ba);
2900:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2901:         }
2902:       }
2903:       PetscViewerDestroy(&vdraw);
2904:       MatDestroy(&Bfd);
2905:     }
2906:   }
2907:   return(0);
2908: }

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

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

2917:      Collective on snes

2919:     Input Parameters:
2920: +  x - input vector, the Jacobian is to be computed at this value
2921: -  ctx - [optional] user-defined Jacobian context

2923:     Output Parameters:
2924: +  Amat - the matrix that defines the (approximate) Jacobian
2925: -  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.

2927:    Level: intermediate

2929: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2930: M*/

2932: /*@C
2933:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2934:    location to store the matrix.

2936:    Logically Collective on SNES

2938:    Input Parameters:
2939: +  snes - the SNES context
2940: .  Amat - the matrix that defines the (approximate) Jacobian
2941: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2942: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2943: -  ctx - [optional] user-defined context for private data for the
2944:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2946:    Notes:
2947:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2948:    each matrix.

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

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

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

2959:    Level: beginner

2961: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
2962:           SNESSetPicard(), SNESJacobianFunction
2963: @*/
2964: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2965: {
2967:   DM             dm;

2975:   SNESGetDM(snes,&dm);
2976:   DMSNESSetJacobian(dm,J,ctx);
2977:   if (Amat) {
2978:     PetscObjectReference((PetscObject)Amat);
2979:     MatDestroy(&snes->jacobian);

2981:     snes->jacobian = Amat;
2982:   }
2983:   if (Pmat) {
2984:     PetscObjectReference((PetscObject)Pmat);
2985:     MatDestroy(&snes->jacobian_pre);

2987:     snes->jacobian_pre = Pmat;
2988:   }
2989:   return(0);
2990: }

2992: /*@C
2993:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2994:    provided context for evaluating the Jacobian.

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

2998:    Input Parameter:
2999: .  snes - the nonlinear solver context

3001:    Output Parameters:
3002: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
3003: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
3004: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
3005: -  ctx - location to stash Jacobian ctx (or NULL)

3007:    Level: advanced

3009: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
3010: @*/
3011: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
3012: {
3014:   DM             dm;
3015:   DMSNES         sdm;

3019:   if (Amat) *Amat = snes->jacobian;
3020:   if (Pmat) *Pmat = snes->jacobian_pre;
3021:   SNESGetDM(snes,&dm);
3022:   DMGetDMSNES(dm,&sdm);
3023:   if (J) *J = sdm->ops->computejacobian;
3024:   if (ctx) *ctx = sdm->jacobianctx;
3025:   return(0);
3026: }

3028: /*@
3029:    SNESSetUp - Sets up the internal data structures for the later use
3030:    of a nonlinear solver.

3032:    Collective on SNES

3034:    Input Parameters:
3035: .  snes - the SNES context

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

3044:    Level: advanced

3046: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
3047: @*/
3048: PetscErrorCode  SNESSetUp(SNES snes)
3049: {
3051:   DM             dm;
3052:   DMSNES         sdm;
3053:   SNESLineSearch linesearch, pclinesearch;
3054:   void           *lsprectx,*lspostctx;
3055:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
3056:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
3057:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
3058:   Vec            f,fpc;
3059:   void           *funcctx;
3060:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
3061:   void           *jacctx,*appctx;
3062:   Mat            j,jpre;

3066:   if (snes->setupcalled) return(0);
3067:   PetscLogEventBegin(SNES_Setup,snes,0,0,0);

3069:   if (!((PetscObject)snes)->type_name) {
3070:     SNESSetType(snes,SNESNEWTONLS);
3071:   }

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

3075:   SNESGetDM(snes,&dm);
3076:   DMGetDMSNES(dm,&sdm);
3077:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
3078:   if (!sdm->ops->computejacobian) {
3079:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
3080:   }
3081:   if (!snes->vec_func) {
3082:     DMCreateGlobalVector(dm,&snes->vec_func);
3083:   }

3085:   if (!snes->ksp) {
3086:     SNESGetKSP(snes, &snes->ksp);
3087:   }

3089:   if (snes->linesearch) {
3090:     SNESGetLineSearch(snes, &snes->linesearch);
3091:     SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);
3092:   }

3094:   if (snes->npc && (snes->npcside== PC_LEFT)) {
3095:     snes->mf          = PETSC_TRUE;
3096:     snes->mf_operator = PETSC_FALSE;
3097:   }

3099:   if (snes->npc) {
3100:     /* copy the DM over */
3101:     SNESGetDM(snes,&dm);
3102:     SNESSetDM(snes->npc,dm);

3104:     SNESGetFunction(snes,&f,&func,&funcctx);
3105:     VecDuplicate(f,&fpc);
3106:     SNESSetFunction(snes->npc,fpc,func,funcctx);
3107:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
3108:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
3109:     SNESGetApplicationContext(snes,&appctx);
3110:     SNESSetApplicationContext(snes->npc,appctx);
3111:     VecDestroy(&fpc);

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

3116:     /* default to 1 iteration */
3117:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
3118:     if (snes->npcside==PC_RIGHT) {
3119:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
3120:     } else {
3121:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
3122:     }
3123:     SNESSetFromOptions(snes->npc);

3125:     /* copy the line search context over */
3126:     if (snes->linesearch && snes->npc->linesearch) {
3127:       SNESGetLineSearch(snes,&linesearch);
3128:       SNESGetLineSearch(snes->npc,&pclinesearch);
3129:       SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
3130:       SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
3131:       SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
3132:       SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
3133:       PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
3134:     }
3135:   }
3136:   if (snes->mf) {
3137:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
3138:   }
3139:   if (snes->ops->usercompute && !snes->user) {
3140:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
3141:   }

3143:   snes->jac_iter = 0;
3144:   snes->pre_iter = 0;

3146:   if (snes->ops->setup) {
3147:     (*snes->ops->setup)(snes);
3148:   }

3150:   if (snes->npc && (snes->npcside== PC_LEFT)) {
3151:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3152:       if (snes->linesearch){
3153:         SNESGetLineSearch(snes,&linesearch);
3154:         SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
3155:       }
3156:     }
3157:   }
3158:   PetscLogEventEnd(SNES_Setup,snes,0,0,0);
3159:   snes->setupcalled = PETSC_TRUE;
3160:   return(0);
3161: }

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

3166:    Collective on SNES

3168:    Input Parameter:
3169: .  snes - iterative context obtained from SNESCreate()

3171:    Level: intermediate

3173:    Notes:
3174:     Also calls the Section 1.5 Writing Application Codes with PETSc context destroy routine set with SNESSetComputeApplicationContext()

3176: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
3177: @*/
3178: PetscErrorCode  SNESReset(SNES snes)
3179: {

3184:   if (snes->ops->userdestroy && snes->user) {
3185:     (*snes->ops->userdestroy)((void**)&snes->user);
3186:     snes->user = NULL;
3187:   }
3188:   if (snes->npc) {
3189:     SNESReset(snes->npc);
3190:   }

3192:   if (snes->ops->reset) {
3193:     (*snes->ops->reset)(snes);
3194:   }
3195:   if (snes->ksp) {
3196:     KSPReset(snes->ksp);
3197:   }

3199:   if (snes->linesearch) {
3200:     SNESLineSearchReset(snes->linesearch);
3201:   }

3203:   VecDestroy(&snes->vec_rhs);
3204:   VecDestroy(&snes->vec_sol);
3205:   VecDestroy(&snes->vec_sol_update);
3206:   VecDestroy(&snes->vec_func);
3207:   MatDestroy(&snes->jacobian);
3208:   MatDestroy(&snes->jacobian_pre);
3209:   VecDestroyVecs(snes->nwork,&snes->work);
3210:   VecDestroyVecs(snes->nvwork,&snes->vwork);

3212:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3214:   snes->nwork       = snes->nvwork = 0;
3215:   snes->setupcalled = PETSC_FALSE;
3216:   return(0);
3217: }

3219: /*@
3220:    SNESDestroy - Destroys the nonlinear solver context that was created
3221:    with SNESCreate().

3223:    Collective on SNES

3225:    Input Parameter:
3226: .  snes - the SNES context

3228:    Level: beginner

3230: .seealso: SNESCreate(), SNESSolve()
3231: @*/
3232: PetscErrorCode  SNESDestroy(SNES *snes)
3233: {

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

3241:   SNESReset((*snes));
3242:   SNESDestroy(&(*snes)->npc);

3244:   /* if memory was published with SAWs then destroy it */
3245:   PetscObjectSAWsViewOff((PetscObject)*snes);
3246:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

3248:   if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
3249:   DMDestroy(&(*snes)->dm);
3250:   KSPDestroy(&(*snes)->ksp);
3251:   SNESLineSearchDestroy(&(*snes)->linesearch);

3253:   PetscFree((*snes)->kspconvctx);
3254:   if ((*snes)->ops->convergeddestroy) {
3255:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
3256:   }
3257:   if ((*snes)->conv_hist_alloc) {
3258:     PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its);
3259:   }
3260:   SNESMonitorCancel((*snes));
3261:   PetscHeaderDestroy(snes);
3262:   return(0);
3263: }

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

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

3270:    Logically Collective on SNES

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

3277:    Options Database Keys:
3278: .    -snes_lag_preconditioner <lag>

3280:    Notes:
3281:    The default is 1
3282:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3283:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

3285:    Level: intermediate

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

3289: @*/
3290: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3291: {
3294:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3295:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3297:   snes->lagpreconditioner = lag;
3298:   return(0);
3299: }

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

3304:    Logically Collective on SNES

3306:    Input Parameters:
3307: +  snes - the SNES context
3308: -  steps - the number of refinements to do, defaults to 0

3310:    Options Database Keys:
3311: .    -snes_grid_sequence <steps>

3313:    Level: intermediate

3315:    Notes:
3316:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

3320: @*/
3321: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3322: {
3326:   snes->gridsequence = steps;
3327:   return(0);
3328: }

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

3333:    Logically Collective on SNES

3335:    Input Parameter:
3336: .  snes - the SNES context

3338:    Output Parameter:
3339: .  steps - the number of refinements to do, defaults to 0

3341:    Options Database Keys:
3342: .    -snes_grid_sequence <steps>

3344:    Level: intermediate

3346:    Notes:
3347:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

3351: @*/
3352: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3353: {
3356:   *steps = snes->gridsequence;
3357:   return(0);
3358: }

3360: /*@
3361:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3363:    Not Collective

3365:    Input Parameter:
3366: .  snes - the SNES context

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

3372:    Options Database Keys:
3373: .    -snes_lag_preconditioner <lag>

3375:    Notes:
3376:    The default is 1
3377:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3379:    Level: intermediate

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

3383: @*/
3384: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3385: {
3388:   *lag = snes->lagpreconditioner;
3389:   return(0);
3390: }

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

3396:    Logically Collective on SNES

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

3403:    Options Database Keys:
3404: .    -snes_lag_jacobian <lag>

3406:    Notes:
3407:    The default is 1
3408:    The Jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3409:    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
3410:    at the next Newton step but never again (unless it is reset to another value)

3412:    Level: intermediate

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

3416: @*/
3417: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3418: {
3421:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3422:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3424:   snes->lagjacobian = lag;
3425:   return(0);
3426: }

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

3431:    Not Collective

3433:    Input Parameter:
3434: .  snes - the SNES context

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

3440:    Options Database Keys:
3441: .    -snes_lag_jacobian <lag>

3443:    Notes:
3444:    The default is 1
3445:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3447:    Level: intermediate

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

3451: @*/
3452: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3453: {
3456:   *lag = snes->lagjacobian;
3457:   return(0);
3458: }

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

3463:    Logically collective on SNES

3465:    Input Parameter:
3466: +  snes - the SNES context
3467: -   flg - jacobian lagging persists if true

3469:    Options Database Keys:
3470: .    -snes_lag_jacobian_persists <flg>

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

3477:    Level: developer

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

3481: @*/
3482: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3483: {
3487:   snes->lagjac_persist = flg;
3488:   return(0);
3489: }

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

3494:    Logically Collective on SNES

3496:    Input Parameter:
3497: +  snes - the SNES context
3498: -   flg - preconditioner lagging persists if true

3500:    Options Database Keys:
3501: .    -snes_lag_jacobian_persists <flg>

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

3508:    Level: developer

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

3512: @*/
3513: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3514: {
3518:   snes->lagpre_persist = flg;
3519:   return(0);
3520: }

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

3525:    Logically Collective on SNES

3527:    Input Parameters:
3528: +  snes - the SNES context
3529: -  force - PETSC_TRUE require at least one iteration

3531:    Options Database Keys:
3532: .    -snes_force_iteration <force> - Sets forcing an iteration

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

3537:    Level: intermediate

3539: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3540: @*/
3541: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3542: {
3545:   snes->forceiteration = force;
3546:   return(0);
3547: }

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

3552:    Logically Collective on SNES

3554:    Input Parameters:
3555: .  snes - the SNES context

3557:    Output Parameter:
3558: .  force - PETSC_TRUE requires at least one iteration.

3560:    Level: intermediate

3562: .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3563: @*/
3564: PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
3565: {
3568:   *force = snes->forceiteration;
3569:   return(0);
3570: }

3572: /*@
3573:    SNESSetTolerances - Sets various parameters used in convergence tests.

3575:    Logically Collective on SNES

3577:    Input Parameters:
3578: +  snes - the SNES context
3579: .  abstol - absolute convergence tolerance
3580: .  rtol - relative convergence tolerance
3581: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3582: .  maxit - maximum number of iterations
3583: -  maxf - maximum number of function evaluations (-1 indicates no limit)

3585:    Options Database Keys:
3586: +    -snes_atol <abstol> - Sets abstol
3587: .    -snes_rtol <rtol> - Sets rtol
3588: .    -snes_stol <stol> - Sets stol
3589: .    -snes_max_it <maxit> - Sets maxit
3590: -    -snes_max_funcs <maxf> - Sets maxf

3592:    Notes:
3593:    The default maximum number of iterations is 50.
3594:    The default maximum number of function evaluations is 1000.

3596:    Level: intermediate

3598: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3599: @*/
3600: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3601: {

3610:   if (abstol != PETSC_DEFAULT) {
3611:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3612:     snes->abstol = abstol;
3613:   }
3614:   if (rtol != PETSC_DEFAULT) {
3615:     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);
3616:     snes->rtol = rtol;
3617:   }
3618:   if (stol != PETSC_DEFAULT) {
3619:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3620:     snes->stol = stol;
3621:   }
3622:   if (maxit != PETSC_DEFAULT) {
3623:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3624:     snes->max_its = maxit;
3625:   }
3626:   if (maxf != PETSC_DEFAULT) {
3627:     if (maxf < -1) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be -1 or nonnegative",maxf);
3628:     snes->max_funcs = maxf;
3629:   }
3630:   snes->tolerancesset = PETSC_TRUE;
3631:   return(0);
3632: }

3634: /*@
3635:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3637:    Logically Collective on SNES

3639:    Input Parameters:
3640: +  snes - the SNES context
3641: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3643:    Options Database Keys:
3644: .    -snes_divergence_tolerance <divtol> - Sets divtol

3646:    Notes:
3647:    The default divergence tolerance is 1e4.

3649:    Level: intermediate

3651: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3652: @*/
3653: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3654: {

3659:   if (divtol != PETSC_DEFAULT) {
3660:     snes->divtol = divtol;
3661:   }
3662:   else {
3663:     snes->divtol = 1.0e4;
3664:   }
3665:   return(0);
3666: }

3668: /*@
3669:    SNESGetTolerances - Gets various parameters used in convergence tests.

3671:    Not Collective

3673:    Input Parameters:
3674: +  snes - the SNES context
3675: .  atol - absolute convergence tolerance
3676: .  rtol - relative convergence tolerance
3677: .  stol -  convergence tolerance in terms of the norm
3678:            of the change in the solution between steps
3679: .  maxit - maximum number of iterations
3680: -  maxf - maximum number of function evaluations

3682:    Notes:
3683:    The user can specify NULL for any parameter that is not needed.

3685:    Level: intermediate

3687: .seealso: SNESSetTolerances()
3688: @*/
3689: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3690: {
3693:   if (atol)  *atol  = snes->abstol;
3694:   if (rtol)  *rtol  = snes->rtol;
3695:   if (stol)  *stol  = snes->stol;
3696:   if (maxit) *maxit = snes->max_its;
3697:   if (maxf)  *maxf  = snes->max_funcs;
3698:   return(0);
3699: }

3701: /*@
3702:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3704:    Not Collective

3706:    Input Parameters:
3707: +  snes - the SNES context
3708: -  divtol - divergence tolerance

3710:    Level: intermediate

3712: .seealso: SNESSetDivergenceTolerance()
3713: @*/
3714: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3715: {
3718:   if (divtol) *divtol = snes->divtol;
3719:   return(0);
3720: }

3722: /*@
3723:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3725:    Logically Collective on SNES

3727:    Input Parameters:
3728: +  snes - the SNES context
3729: -  tol - tolerance

3731:    Options Database Key:
3732: .  -snes_trtol <tol> - Sets tol

3734:    Level: intermediate

3736: .seealso: SNESSetTolerances()
3737: @*/
3738: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3739: {
3743:   snes->deltatol = tol;
3744:   return(0);
3745: }

3747: /*
3748:    Duplicate the lg monitors for SNES from KSP; for some reason with
3749:    dynamic libraries things don't work under Sun4 if we just use
3750:    macros instead of functions
3751: */
3752: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3753: {

3758:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3759:   return(0);
3760: }

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

3767:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3768:   return(0);
3769: }

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

3773: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3774: {
3775:   PetscDrawLG      lg;
3776:   PetscErrorCode   ierr;
3777:   PetscReal        x,y,per;
3778:   PetscViewer      v = (PetscViewer)monctx;
3779:   static PetscReal prev; /* should be in the context */
3780:   PetscDraw        draw;

3784:   PetscViewerDrawGetDrawLG(v,0,&lg);
3785:   if (!n) {PetscDrawLGReset(lg);}
3786:   PetscDrawLGGetDraw(lg,&draw);
3787:   PetscDrawSetTitle(draw,"Residual norm");
3788:   x    = (PetscReal)n;
3789:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3790:   else y = -15.0;
3791:   PetscDrawLGAddPoint(lg,&x,&y);
3792:   if (n < 20 || !(n % 5) || snes->reason) {
3793:     PetscDrawLGDraw(lg);
3794:     PetscDrawLGSave(lg);
3795:   }

3797:   PetscViewerDrawGetDrawLG(v,1,&lg);
3798:   if (!n) {PetscDrawLGReset(lg);}
3799:   PetscDrawLGGetDraw(lg,&draw);
3800:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3801:    SNESMonitorRange_Private(snes,n,&per);
3802:   x    = (PetscReal)n;
3803:   y    = 100.0*per;
3804:   PetscDrawLGAddPoint(lg,&x,&y);
3805:   if (n < 20 || !(n % 5) || snes->reason) {
3806:     PetscDrawLGDraw(lg);
3807:     PetscDrawLGSave(lg);
3808:   }

3810:   PetscViewerDrawGetDrawLG(v,2,&lg);
3811:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3812:   PetscDrawLGGetDraw(lg,&draw);
3813:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3814:   x    = (PetscReal)n;
3815:   y    = (prev - rnorm)/prev;
3816:   PetscDrawLGAddPoint(lg,&x,&y);
3817:   if (n < 20 || !(n % 5) || snes->reason) {
3818:     PetscDrawLGDraw(lg);
3819:     PetscDrawLGSave(lg);
3820:   }

3822:   PetscViewerDrawGetDrawLG(v,3,&lg);
3823:   if (!n) {PetscDrawLGReset(lg);}
3824:   PetscDrawLGGetDraw(lg,&draw);
3825:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3826:   x    = (PetscReal)n;
3827:   y    = (prev - rnorm)/(prev*per);
3828:   if (n > 2) { /*skip initial crazy value */
3829:     PetscDrawLGAddPoint(lg,&x,&y);
3830:   }
3831:   if (n < 20 || !(n % 5) || snes->reason) {
3832:     PetscDrawLGDraw(lg);
3833:     PetscDrawLGSave(lg);
3834:   }
3835:   prev = rnorm;
3836:   return(0);
3837: }

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

3842:    Collective on SNES

3844:    Input Parameters:
3845: +  snes - nonlinear solver context obtained from SNESCreate()
3846: .  iter - iteration number
3847: -  rnorm - relative norm of the residual

3849:    Notes:
3850:    This routine is called by the SNES implementations.
3851:    It does not typically need to be called by the user.

3853:    Level: developer

3855: .seealso: SNESMonitorSet()
3856: @*/
3857: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3858: {
3860:   PetscInt       i,n = snes->numbermonitors;

3863:   VecLockReadPush(snes->vec_sol);
3864:   for (i=0; i<n; i++) {
3865:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3866:   }
3867:   VecLockReadPop(snes->vec_sol);
3868:   return(0);
3869: }

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

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

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

3880:      Collective on snes

3882:     Input Parameters:
3883: +    snes - the SNES context
3884: .    its - iteration number
3885: .    norm - 2-norm function value (may be estimated)
3886: -    mctx - [optional] monitoring context

3888:    Level: advanced

3890: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3891: M*/

3893: /*@C
3894:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3895:    iteration of the nonlinear solver to display the iteration's
3896:    progress.

3898:    Logically Collective on SNES

3900:    Input Parameters:
3901: +  snes - the SNES context
3902: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3903: .  mctx - [optional] user-defined context for private data for the
3904:           monitor routine (use NULL if no context is desired)
3905: -  monitordestroy - [optional] routine that frees monitor context
3906:           (may be NULL)

3908:    Options Database Keys:
3909: +    -snes_monitor        - sets SNESMonitorDefault()
3910: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3911:                             uses SNESMonitorLGCreate()
3912: -    -snes_monitor_cancel - cancels all monitors that have
3913:                             been hardwired into a code by
3914:                             calls to SNESMonitorSet(), but
3915:                             does not cancel those set via
3916:                             the options database.

3918:    Notes:
3919:    Several different monitoring routines may be set by calling
3920:    SNESMonitorSet() multiple times; all will be called in the
3921:    order in which they were set.

3923:    Fortran Notes:
3924:     Only a single monitor function can be set for each SNES object

3926:    Level: intermediate

3928: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3929: @*/
3930: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3931: {
3932:   PetscInt       i;
3934:   PetscBool      identical;

3938:   for (i=0; i<snes->numbermonitors;i++) {
3939:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3940:     if (identical) return(0);
3941:   }
3942:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3943:   snes->monitor[snes->numbermonitors]          = f;
3944:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3945:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3946:   return(0);
3947: }

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

3952:    Logically Collective on SNES

3954:    Input Parameters:
3955: .  snes - the SNES context

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

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

3965:    Level: intermediate

3967: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3968: @*/
3969: PetscErrorCode  SNESMonitorCancel(SNES snes)
3970: {
3972:   PetscInt       i;

3976:   for (i=0; i<snes->numbermonitors; i++) {
3977:     if (snes->monitordestroy[i]) {
3978:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3979:     }
3980:   }
3981:   snes->numbermonitors = 0;
3982:   return(0);
3983: }

3985: /*MC
3986:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3992:      Collective on snes

3994:     Input Parameters:
3995: +    snes - the SNES context
3996: .    it - current iteration (0 is the first and is before any Newton step)
3997: .    xnorm - 2-norm of current iterate
3998: .    gnorm - 2-norm of current step
3999: .    f - 2-norm of function
4000: -    cctx - [optional] convergence context

4002:     Output Parameter:
4003: .    reason - reason for convergence/divergence, only needs to be set when convergence or divergence is detected

4005:    Level: intermediate

4007: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
4008: M*/

4010: /*@C
4011:    SNESSetConvergenceTest - Sets the function that is to be used
4012:    to test for convergence of the nonlinear iterative solution.

4014:    Logically Collective on SNES

4016:    Input Parameters:
4017: +  snes - the SNES context
4018: .  SNESConvergenceTestFunction - routine to test for convergence
4019: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
4020: -  destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)

4022:    Level: advanced

4024: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
4025: @*/
4026: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
4027: {

4032:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
4033:   if (snes->ops->convergeddestroy) {
4034:     (*snes->ops->convergeddestroy)(snes->cnvP);
4035:   }
4036:   snes->ops->converged        = SNESConvergenceTestFunction;
4037:   snes->ops->convergeddestroy = destroy;
4038:   snes->cnvP                  = cctx;
4039:   return(0);
4040: }

4042: /*@
4043:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

4045:    Not Collective

4047:    Input Parameter:
4048: .  snes - the SNES context

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

4054:    Options Database:
4055: .   -snes_converged_reason - prints the reason to standard out

4057:    Level: intermediate

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

4062: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
4063: @*/
4064: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4065: {
4069:   *reason = snes->reason;
4070:   return(0);
4071: }

4073: /*@
4074:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

4076:    Not Collective

4078:    Input Parameters:
4079: +  snes - the SNES context
4080: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4081:             manual pages for the individual convergence tests for complete lists

4083:    Level: intermediate

4085: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
4086: @*/
4087: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
4088: {
4091:   snes->reason = reason;
4092:   return(0);
4093: }

4095: /*@
4096:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

4098:    Logically Collective on SNES

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

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

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

4116:    Level: intermediate

4118: .seealso: SNESGetConvergenceHistory()

4120: @*/
4121: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4122: {

4129:   if (!a) {
4130:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
4131:     PetscCalloc2(na,&a,na,&its);
4132:     snes->conv_hist_alloc = PETSC_TRUE;
4133:   }
4134:   snes->conv_hist       = a;
4135:   snes->conv_hist_its   = its;
4136:   snes->conv_hist_max   = na;
4137:   snes->conv_hist_len   = 0;
4138:   snes->conv_hist_reset = reset;
4139:   return(0);
4140: }

4142: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4143: #include <engine.h>   /* MATLAB include file */
4144: #include <mex.h>      /* MATLAB include file */

4146: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4147: {
4148:   mxArray   *mat;
4149:   PetscInt  i;
4150:   PetscReal *ar;

4153:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4154:   ar  = (PetscReal*) mxGetData(mat);
4155:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4156:   PetscFunctionReturn(mat);
4157: }
4158: #endif

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

4163:    Not Collective

4165:    Input Parameter:
4166: .  snes - iterative context obtained from SNESCreate()

4168:    Output Parameters:
4169: +  a   - array to hold history
4170: .  its - integer array holds the number of linear iterations (or
4171:          negative if not converged) for each solve.
4172: -  na  - size of a and its

4174:    Notes:
4175:     The calling sequence for this routine in Fortran is
4176: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

4182:    Level: intermediate

4184: .seealso: SNESSetConvergencHistory()

4186: @*/
4187: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4188: {
4191:   if (a)   *a   = snes->conv_hist;
4192:   if (its) *its = snes->conv_hist_its;
4193:   if (na)  *na  = snes->conv_hist_len;
4194:   return(0);
4195: }

4197: /*@C
4198:   SNESSetUpdate - Sets the general-purpose update function called
4199:   at the beginning of every iteration of the nonlinear solve. Specifically
4200:   it is called just before the Jacobian is "evaluated".

4202:   Logically Collective on SNES

4204:   Input Parameters:
4205: + snes - The nonlinear solver context
4206: - func - The function

4208:   Calling sequence of func:
4209: $ func (SNES snes, PetscInt step);

4211: . step - The current step of the iteration

4213:   Level: advanced

4215:   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()
4216:         This is not used by most users.

4218: .seealso SNESSetJacobian(), SNESSolve()
4219: @*/
4220: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4221: {
4224:   snes->ops->update = func;
4225:   return(0);
4226: }

4228: /*
4229:    SNESScaleStep_Private - Scales a step so that its length is less than the
4230:    positive parameter delta.

4232:     Input Parameters:
4233: +   snes - the SNES context
4234: .   y - approximate solution of linear system
4235: .   fnorm - 2-norm of current function
4236: -   delta - trust region size

4238:     Output Parameters:
4239: +   gpnorm - predicted function norm at the new point, assuming local
4240:     linearization.  The value is zero if the step lies within the trust
4241:     region, and exceeds zero otherwise.
4242: -   ynorm - 2-norm of the step

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

4248: */
4249: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4250: {
4251:   PetscReal      nrm;
4252:   PetscScalar    cnorm;


4260:   VecNorm(y,NORM_2,&nrm);
4261:   if (nrm > *delta) {
4262:     nrm     = *delta/nrm;
4263:     *gpnorm = (1.0 - nrm)*(*fnorm);
4264:     cnorm   = nrm;
4265:     VecScale(y,cnorm);
4266:     *ynorm  = *delta;
4267:   } else {
4268:     *gpnorm = 0.0;
4269:     *ynorm  = nrm;
4270:   }
4271:   return(0);
4272: }

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

4277:    Collective on SNES

4279:    Parameter:
4280: +  snes - iterative context obtained from SNESCreate()
4281: -  viewer - the viewer to display the reason


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

4287:    Level: beginner

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

4291: @*/
4292: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
4293: {
4294:   PetscViewerFormat format;
4295:   PetscBool         isAscii;
4296:   PetscErrorCode    ierr;

4299:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
4300:   if (isAscii) {
4301:     PetscViewerGetFormat(viewer, &format);
4302:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
4303:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4304:       DM                dm;
4305:       Vec               u;
4306:       PetscDS           prob;
4307:       PetscInt          Nf, f;
4308:       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4309:       void            **exactCtx;
4310:       PetscReal         error;

4312:       SNESGetDM(snes, &dm);
4313:       SNESGetSolution(snes, &u);
4314:       DMGetDS(dm, &prob);
4315:       PetscDSGetNumFields(prob, &Nf);
4316:       PetscMalloc2(Nf, &exactSol, Nf, &exactCtx);
4317:       for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]);}
4318:       DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error);
4319:       PetscFree2(exactSol, exactCtx);
4320:       if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
4321:       else                 {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
4322:     }
4323:     if (snes->reason > 0) {
4324:       if (((PetscObject) snes)->prefix) {
4325:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4326:       } else {
4327:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4328:       }
4329:     } else {
4330:       if (((PetscObject) snes)->prefix) {
4331:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4332:       } else {
4333:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4334:       }
4335:     }
4336:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4337:   }
4338:   return(0);
4339: }

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

4344:   Collective on SNES

4346:   Input Parameters:
4347: . snes   - the SNES object

4349:   Level: intermediate

4351: @*/
4352: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
4353: {
4354:   PetscErrorCode    ierr;
4355:   PetscViewer       viewer;
4356:   PetscBool         flg;
4357:   static PetscBool  incall = PETSC_FALSE;
4358:   PetscViewerFormat format;

4361:   if (incall) return(0);
4362:   incall = PETSC_TRUE;
4363:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4364:   if (flg) {
4365:     PetscViewerPushFormat(viewer,format);
4366:     SNESReasonView(snes,viewer);
4367:     PetscViewerPopFormat(viewer);
4368:     PetscViewerDestroy(&viewer);
4369:   }
4370:   incall = PETSC_FALSE;
4371:   return(0);
4372: }

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

4378:    Collective on SNES

4380:    Input Parameters:
4381: +  snes - the SNES context
4382: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4383: -  x - the solution vector.

4385:    Notes:
4386:    The user should initialize the vector,x, with the initial guess
4387:    for the nonlinear solve prior to calling SNESSolve.  In particular,
4388:    to employ an initial guess of zero, the user should explicitly set
4389:    this vector to zero by calling VecSet().

4391:    Level: beginner

4393: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4394: @*/
4395: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4396: {
4397:   PetscErrorCode    ierr;
4398:   PetscBool         flg;
4399:   PetscInt          grid;
4400:   Vec               xcreated = NULL;
4401:   DM                dm;


4410:   /* High level operations using the nonlinear solver */
4411:   {
4412:     PetscViewer       viewer;
4413:     PetscViewerFormat format;
4414:     PetscInt          num;
4415:     PetscBool         flg;
4416:     static PetscBool  incall = PETSC_FALSE;

4418:     if (!incall) {
4419:       /* Estimate the convergence rate of the discretization */
4420:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4421:       if (flg) {
4422:         PetscConvEst conv;
4423:         DM           dm;
4424:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4425:         PetscInt     Nf;

4427:         incall = PETSC_TRUE;
4428:         SNESGetDM(snes, &dm);
4429:         DMGetNumFields(dm, &Nf);
4430:         PetscCalloc1(Nf, &alpha);
4431:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4432:         PetscConvEstSetSolver(conv, (PetscObject) snes);
4433:         PetscConvEstSetFromOptions(conv);
4434:         PetscConvEstSetUp(conv);
4435:         PetscConvEstGetConvRate(conv, alpha);
4436:         PetscViewerPushFormat(viewer, format);
4437:         PetscConvEstRateView(conv, alpha, viewer);
4438:         PetscViewerPopFormat(viewer);
4439:         PetscViewerDestroy(&viewer);
4440:         PetscConvEstDestroy(&conv);
4441:         PetscFree(alpha);
4442:         incall = PETSC_FALSE;
4443:       }
4444:       /* Adaptively refine the initial grid */
4445:       num  = 1;
4446:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);
4447:       if (flg) {
4448:         DMAdaptor adaptor;

4450:         incall = PETSC_TRUE;
4451:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4452:         DMAdaptorSetSolver(adaptor, snes);
4453:         DMAdaptorSetSequenceLength(adaptor, num);
4454:         DMAdaptorSetFromOptions(adaptor);
4455:         DMAdaptorSetUp(adaptor);
4456:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4457:         DMAdaptorDestroy(&adaptor);
4458:         incall = PETSC_FALSE;
4459:       }
4460:       /* Use grid sequencing to adapt */
4461:       num  = 0;
4462:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4463:       if (num) {
4464:         DMAdaptor adaptor;

4466:         incall = PETSC_TRUE;
4467:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4468:         DMAdaptorSetSolver(adaptor, snes);
4469:         DMAdaptorSetSequenceLength(adaptor, num);
4470:         DMAdaptorSetFromOptions(adaptor);
4471:         DMAdaptorSetUp(adaptor);
4472:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4473:         DMAdaptorDestroy(&adaptor);
4474:         incall = PETSC_FALSE;
4475:       }
4476:     }
4477:   }
4478:   if (!x) {
4479:     SNESGetDM(snes,&dm);
4480:     DMCreateGlobalVector(dm,&xcreated);
4481:     x    = xcreated;
4482:   }
4483:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4488:     /* set solution vector */
4489:     if (!grid) {PetscObjectReference((PetscObject)x);}
4490:     VecDestroy(&snes->vec_sol);
4491:     snes->vec_sol = x;
4492:     SNESGetDM(snes,&dm);

4494:     /* set affine vector if provided */
4495:     if (b) { PetscObjectReference((PetscObject)b); }
4496:     VecDestroy(&snes->vec_rhs);
4497:     snes->vec_rhs = b;

4499:     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");
4500:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4501:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4502:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4503:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4504:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4505:     }
4506:     DMShellSetGlobalVector(dm,snes->vec_sol);
4507:     SNESSetUp(snes);

4509:     if (!grid) {
4510:       if (snes->ops->computeinitialguess) {
4511:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4512:       }
4513:     }

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

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

4524:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4525:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4531:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4532:     if (snes->reason < 0) break;
4533:     if (grid <  snes->gridsequence) {
4534:       DM  fine;
4535:       Vec xnew;
4536:       Mat interp;

4538:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4539:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4540:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4541:       DMCreateGlobalVector(fine,&xnew);
4542:       MatInterpolate(interp,x,xnew);
4543:       DMInterpolate(snes->dm,interp,fine);
4544:       MatDestroy(&interp);
4545:       x    = xnew;

4547:       SNESReset(snes);
4548:       SNESSetDM(snes,fine);
4549:       SNESResetFromOptions(snes);
4550:       DMDestroy(&fine);
4551:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4552:     }
4553:   }
4554:   SNESViewFromOptions(snes,NULL,"-snes_view");
4555:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");
4556:   DMMonitor(snes->dm);

4558:   VecDestroy(&xcreated);
4559:   PetscObjectSAWsBlock((PetscObject)snes);
4560:   return(0);
4561: }

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

4565: /*@C
4566:    SNESSetType - Sets the method for the nonlinear solver.

4568:    Collective on SNES

4570:    Input Parameters:
4571: +  snes - the SNES context
4572: -  type - a known method

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

4578:    Notes:
4579:    See "petsc/include/petscsnes.h" for available methods (for instance)
4580: +    SNESNEWTONLS - Newton's method with line search
4581:      (systems of nonlinear equations)
4582: -    SNESNEWTONTR - Newton's method with trust region
4583:      (systems of nonlinear equations)

4585:   Normally, it is best to use the SNESSetFromOptions() command and then
4586:   set the SNES solver type from the options database rather than by using
4587:   this routine.  Using the options database provides the user with
4588:   maximum flexibility in evaluating the many nonlinear solvers.
4589:   The SNESSetType() routine is provided for those situations where it
4590:   is necessary to set the nonlinear solver independently of the command
4591:   line or options database.  This might be the case, for example, when
4592:   the choice of solver changes during the execution of the program,
4593:   and the user's Section 1.5 Writing Application Codes with PETSc is taking responsibility for choosing the
4594:   appropriate method.

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

4600:   Level: intermediate

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

4604: @*/
4605: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4606: {
4607:   PetscErrorCode ierr,(*r)(SNES);
4608:   PetscBool      match;


4614:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4615:   if (match) return(0);

4617:   PetscFunctionListFind(SNESList,type,&r);
4618:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4619:   /* Destroy the previous private SNES context */
4620:   if (snes->ops->destroy) {
4621:     (*(snes)->ops->destroy)(snes);
4622:     snes->ops->destroy = NULL;
4623:   }
4624:   /* Reinitialize function pointers in SNESOps structure */
4625:   snes->ops->setup          = 0;
4626:   snes->ops->solve          = 0;
4627:   snes->ops->view           = 0;
4628:   snes->ops->setfromoptions = 0;
4629:   snes->ops->destroy        = 0;

4631:   /* It may happen the user has customized the line search before calling SNESSetType */
4632:   if (((PetscObject)snes)->type_name) {
4633:     SNESLineSearchDestroy(&snes->linesearch);
4634:   }

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

4639:   PetscObjectChangeTypeName((PetscObject)snes,type);
4640:   (*r)(snes);
4641:   return(0);
4642: }

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

4647:    Not Collective

4649:    Input Parameter:
4650: .  snes - nonlinear solver context

4652:    Output Parameter:
4653: .  type - SNES method (a character string)

4655:    Level: intermediate

4657: @*/
4658: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4659: {
4663:   *type = ((PetscObject)snes)->type_name;
4664:   return(0);
4665: }

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

4670:   Logically Collective on SNES

4672:   Input Parameters:
4673: + snes - the SNES context obtained from SNESCreate()
4674: - u    - the solution vector

4676:   Level: beginner

4678: @*/
4679: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4680: {
4681:   DM             dm;

4687:   PetscObjectReference((PetscObject) u);
4688:   VecDestroy(&snes->vec_sol);

4690:   snes->vec_sol = u;

4692:   SNESGetDM(snes, &dm);
4693:   DMShellSetGlobalVector(dm, u);
4694:   return(0);
4695: }

4697: /*@
4698:    SNESGetSolution - Returns the vector where the approximate solution is
4699:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4703:    Input Parameter:
4704: .  snes - the SNES context

4706:    Output Parameter:
4707: .  x - the solution

4709:    Level: intermediate

4711: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4712: @*/
4713: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4714: {
4718:   *x = snes->vec_sol;
4719:   return(0);
4720: }

4722: /*@
4723:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4724:    stored.

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

4728:    Input Parameter:
4729: .  snes - the SNES context

4731:    Output Parameter:
4732: .  x - the solution update

4734:    Level: advanced

4736: .seealso: SNESGetSolution(), SNESGetFunction()
4737: @*/
4738: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4739: {
4743:   *x = snes->vec_sol_update;
4744:   return(0);
4745: }

4747: /*@C
4748:    SNESGetFunction - Returns the vector where the function is stored.

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

4752:    Input Parameter:
4753: .  snes - the SNES context

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

4760:    Level: advanced

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

4764: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4765: @*/
4766: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4767: {
4769:   DM             dm;

4773:   if (r) {
4774:     if (!snes->vec_func) {
4775:       if (snes->vec_rhs) {
4776:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4777:       } else if (snes->vec_sol) {
4778:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4779:       } else if (snes->dm) {
4780:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4781:       }
4782:     }
4783:     *r = snes->vec_func;
4784:   }
4785:   SNESGetDM(snes,&dm);
4786:   DMSNESGetFunction(dm,f,ctx);
4787:   return(0);
4788: }

4790: /*@C
4791:    SNESGetNGS - Returns the NGS function and context.

4793:    Input Parameter:
4794: .  snes - the SNES context

4796:    Output Parameter:
4797: +  f - the function (or NULL) see SNESNGSFunction for details
4798: -  ctx    - the function context (or NULL)

4800:    Level: advanced

4802: .seealso: SNESSetNGS(), SNESGetFunction()
4803: @*/

4805: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4806: {
4808:   DM             dm;

4812:   SNESGetDM(snes,&dm);
4813:   DMSNESGetNGS(dm,f,ctx);
4814:   return(0);
4815: }

4817: /*@C
4818:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4819:    SNES options in the database.

4821:    Logically Collective on SNES

4823:    Input Parameter:
4824: +  snes - the SNES context
4825: -  prefix - the prefix to prepend to all option names

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

4831:    Level: advanced

4833: .seealso: SNESSetFromOptions()
4834: @*/
4835: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4836: {

4841:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4842:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4843:   if (snes->linesearch) {
4844:     SNESGetLineSearch(snes,&snes->linesearch);
4845:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4846:   }
4847:   KSPSetOptionsPrefix(snes->ksp,prefix);
4848:   return(0);
4849: }

4851: /*@C
4852:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4853:    SNES options in the database.

4855:    Logically Collective on SNES

4857:    Input Parameters:
4858: +  snes - the SNES context
4859: -  prefix - the prefix to prepend to all option names

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

4865:    Level: advanced

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

4875:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4876:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4877:   if (snes->linesearch) {
4878:     SNESGetLineSearch(snes,&snes->linesearch);
4879:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4880:   }
4881:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4882:   return(0);
4883: }

4885: /*@C
4886:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4887:    SNES options in the database.

4889:    Not Collective

4891:    Input Parameter:
4892: .  snes - the SNES context

4894:    Output Parameter:
4895: .  prefix - pointer to the prefix string used

4897:    Notes:
4898:     On the fortran side, the user should pass in a string 'prefix' of
4899:    sufficient length to hold the prefix.

4901:    Level: advanced

4903: .seealso: SNESAppendOptionsPrefix()
4904: @*/
4905: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4906: {

4911:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4912:   return(0);
4913: }


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

4919:    Not collective

4921:    Input Parameters:
4922: +  name_solver - name of a new user-defined solver
4923: -  routine_create - routine to create method context

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

4928:    Sample usage:
4929: .vb
4930:    SNESRegister("my_solver",MySolverCreate);
4931: .ve

4933:    Then, your solver can be chosen with the procedural interface via
4934: $     SNESSetType(snes,"my_solver")
4935:    or at runtime via the option
4936: $     -snes_type my_solver

4938:    Level: advanced

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

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

4944:   Level: advanced
4945: @*/
4946: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4947: {

4951:   SNESInitializePackage();
4952:   PetscFunctionListAdd(&SNESList,sname,function);
4953:   return(0);
4954: }

4956: PetscErrorCode  SNESTestLocalMin(SNES snes)
4957: {
4959:   PetscInt       N,i,j;
4960:   Vec            u,uh,fh;
4961:   PetscScalar    value;
4962:   PetscReal      norm;

4965:   SNESGetSolution(snes,&u);
4966:   VecDuplicate(u,&uh);
4967:   VecDuplicate(u,&fh);

4969:   /* currently only works for sequential */
4970:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4971:   VecGetSize(u,&N);
4972:   for (i=0; i<N; i++) {
4973:     VecCopy(u,uh);
4974:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4975:     for (j=-10; j<11; j++) {
4976:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4977:       VecSetValue(uh,i,value,ADD_VALUES);
4978:       SNESComputeFunction(snes,uh,fh);
4979:       VecNorm(fh,NORM_2,&norm);
4980:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4981:       value = -value;
4982:       VecSetValue(uh,i,value,ADD_VALUES);
4983:     }
4984:   }
4985:   VecDestroy(&uh);
4986:   VecDestroy(&fh);
4987:   return(0);
4988: }

4990: /*@
4991:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4992:    computing relative tolerance for linear solvers within an inexact
4993:    Newton method.

4995:    Logically Collective on SNES

4997:    Input Parameters:
4998: +  snes - SNES context
4999: -  flag - PETSC_TRUE or PETSC_FALSE

5001:     Options Database:
5002: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
5003: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
5004: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
5005: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
5006: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
5007: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
5008: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
5009: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

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

5018:    Level: advanced

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

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

5035: /*@
5036:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
5037:    for computing relative tolerance for linear solvers within an
5038:    inexact Newton method.

5040:    Not Collective

5042:    Input Parameter:
5043: .  snes - SNES context

5045:    Output Parameter:
5046: .  flag - PETSC_TRUE or PETSC_FALSE

5048:    Notes:
5049:    Currently, the default is to use a constant relative tolerance for
5050:    the inner linear solvers.  Alternatively, one can use the
5051:    Eisenstat-Walker method, where the relative convergence tolerance
5052:    is reset at each Newton iteration according progress of the nonlinear
5053:    solver.

5055:    Level: advanced

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

5061: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
5062: @*/
5063: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
5064: {
5068:   *flag = snes->ksp_ewconv;
5069:   return(0);
5070: }

5072: /*@
5073:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5074:    convergence criteria for the linear solvers within an inexact
5075:    Newton method.

5077:    Logically Collective on SNES

5079:    Input Parameters:
5080: +    snes - SNES context
5081: .    version - version 1, 2 (default is 2) or 3
5082: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5083: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5084: .    gamma - multiplicative factor for version 2 rtol computation
5085:              (0 <= gamma2 <= 1)
5086: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5087: .    alpha2 - power for safeguard
5088: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5090:    Note:
5091:    Version 3 was contributed by Luis Chacon, June 2006.

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

5095:    Level: advanced

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

5102: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
5103: @*/
5104: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
5105: {
5106:   SNESKSPEW *kctx;

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

5120:   if (version != PETSC_DEFAULT)   kctx->version   = version;
5121:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
5122:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
5123:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
5124:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
5125:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
5126:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

5128:   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);
5129:   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);
5130:   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);
5131:   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);
5132:   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);
5133:   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);
5134:   return(0);
5135: }

5137: /*@
5138:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5139:    convergence criteria for the linear solvers within an inexact
5140:    Newton method.

5142:    Not Collective

5144:    Input Parameters:
5145:      snes - SNES context

5147:    Output Parameters:
5148: +    version - version 1, 2 (default is 2) or 3
5149: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5150: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5151: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5152: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5153: .    alpha2 - power for safeguard
5154: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5156:    Level: advanced

5158: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
5159: @*/
5160: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
5161: {
5162:   SNESKSPEW *kctx;

5166:   kctx = (SNESKSPEW*)snes->kspconvctx;
5167:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5168:   if (version)   *version   = kctx->version;
5169:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
5170:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
5171:   if (gamma)     *gamma     = kctx->gamma;
5172:   if (alpha)     *alpha     = kctx->alpha;
5173:   if (alpha2)    *alpha2    = kctx->alpha2;
5174:   if (threshold) *threshold = kctx->threshold;
5175:   return(0);
5176: }

5178:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5179: {
5181:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5182:   PetscReal      rtol  = PETSC_DEFAULT,stol;

5185:   if (!snes->ksp_ewconv) return(0);
5186:   if (!snes->iter) {
5187:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5188:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
5189:   }
5190:   else {
5191:     if (kctx->version == 1) {
5192:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
5193:       if (rtol < 0.0) rtol = -rtol;
5194:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5195:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5196:     } else if (kctx->version == 2) {
5197:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5198:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5199:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5200:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5201:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5202:       /* safeguard: avoid sharp decrease of rtol */
5203:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5204:       stol = PetscMax(rtol,stol);
5205:       rtol = PetscMin(kctx->rtol_0,stol);
5206:       /* safeguard: avoid oversolving */
5207:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5208:       stol = PetscMax(rtol,stol);
5209:       rtol = PetscMin(kctx->rtol_0,stol);
5210:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
5211:   }
5212:   /* safeguard: avoid rtol greater than one */
5213:   rtol = PetscMin(rtol,kctx->rtol_max);
5214:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
5215:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
5216:   return(0);
5217: }

5219: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5220: {
5222:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5223:   PCSide         pcside;
5224:   Vec            lres;

5227:   if (!snes->ksp_ewconv) return(0);
5228:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
5229:   kctx->norm_last = snes->norm;
5230:   if (kctx->version == 1) {
5231:     PC        pc;
5232:     PetscBool isNone;

5234:     KSPGetPC(ksp, &pc);
5235:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
5236:     KSPGetPCSide(ksp,&pcside);
5237:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
5238:       /* KSP residual is true linear residual */
5239:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
5240:     } else {
5241:       /* KSP residual is preconditioned residual */
5242:       /* compute true linear residual norm */
5243:       VecDuplicate(b,&lres);
5244:       MatMult(snes->jacobian,x,lres);
5245:       VecAYPX(lres,-1.0,b);
5246:       VecNorm(lres,NORM_2,&kctx->lresid_last);
5247:       VecDestroy(&lres);
5248:     }
5249:   }
5250:   return(0);
5251: }

5253: /*@
5254:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

5258:    Input Parameter:
5259: .  snes - the SNES context

5261:    Output Parameter:
5262: .  ksp - the KSP context

5264:    Notes:
5265:    The user can then directly manipulate the KSP context to set various
5266:    options, etc.  Likewise, the user can then extract and manipulate the
5267:    PC contexts as well.

5269:    Level: beginner

5271: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5272: @*/
5273: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
5274: {


5281:   if (!snes->ksp) {
5282:     PetscBool monitor = PETSC_FALSE;

5284:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
5285:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
5286:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

5291:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
5292:     if (monitor) {
5293:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
5294:     }
5295:     monitor = PETSC_FALSE;
5296:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
5297:     if (monitor) {
5298:       PetscObject *objs;
5299:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
5300:       objs[0] = (PetscObject) snes;
5301:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
5302:     }
5303:     PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options);
5304:   }
5305:   *ksp = snes->ksp;
5306:   return(0);
5307: }


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

5314:    Logically Collective on SNES

5316:    Input Parameters:
5317: +  snes - the nonlinear solver context
5318: -  dm - the dm, cannot be NULL

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

5325:    Level: intermediate

5327: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
5328: @*/
5329: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5330: {
5332:   KSP            ksp;
5333:   DMSNES         sdm;

5338:   PetscObjectReference((PetscObject)dm);
5339:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5340:     if (snes->dm->dmsnes && !dm->dmsnes) {
5341:       DMCopyDMSNES(snes->dm,dm);
5342:       DMGetDMSNES(snes->dm,&sdm);
5343:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5344:     }
5345:     DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5346:     DMDestroy(&snes->dm);
5347:   }
5348:   snes->dm     = dm;
5349:   snes->dmAuto = PETSC_FALSE;

5351:   SNESGetKSP(snes,&ksp);
5352:   KSPSetDM(ksp,dm);
5353:   KSPSetDMActive(ksp,PETSC_FALSE);
5354:   if (snes->npc) {
5355:     SNESSetDM(snes->npc, snes->dm);
5356:     SNESSetNPCSide(snes,snes->npcside);
5357:   }
5358:   return(0);
5359: }

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

5364:    Not Collective but DM obtained is parallel on SNES

5366:    Input Parameter:
5367: . snes - the preconditioner context

5369:    Output Parameter:
5370: .  dm - the dm

5372:    Level: intermediate

5374: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5375: @*/
5376: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5377: {

5382:   if (!snes->dm) {
5383:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5384:     snes->dmAuto = PETSC_TRUE;
5385:   }
5386:   *dm = snes->dm;
5387:   return(0);
5388: }

5390: /*@
5391:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5393:   Collective on SNES

5395:   Input Parameters:
5396: + snes - iterative context obtained from SNESCreate()
5397: - pc   - the preconditioner object

5399:   Notes:
5400:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5401:   to configure it using the API).

5403:   Level: developer

5405: .seealso: SNESGetNPC(), SNESHasNPC()
5406: @*/
5407: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5408: {

5415:   PetscObjectReference((PetscObject) pc);
5416:   SNESDestroy(&snes->npc);
5417:   snes->npc = pc;
5418:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5419:   return(0);
5420: }

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

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

5427:   Input Parameter:
5428: . snes - iterative context obtained from SNESCreate()

5430:   Output Parameter:
5431: . pc - preconditioner context

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

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

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

5442:   Level: developer

5444: .seealso: SNESSetNPC(), SNESHasNPC(), SNES, SNESCreate()
5445: @*/
5446: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5447: {
5449:   const char     *optionsprefix;

5454:   if (!snes->npc) {
5455:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5456:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5457:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5458:     SNESGetOptionsPrefix(snes,&optionsprefix);
5459:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5460:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5461:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5462:   }
5463:   *pc = snes->npc;
5464:   return(0);
5465: }

5467: /*@
5468:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5470:   Not Collective

5472:   Input Parameter:
5473: . snes - iterative context obtained from SNESCreate()

5475:   Output Parameter:
5476: . has_npc - whether the SNES has an NPC or not

5478:   Level: developer

5480: .seealso: SNESSetNPC(), SNESGetNPC()
5481: @*/
5482: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5483: {
5486:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5487:   return(0);
5488: }

5490: /*@
5491:     SNESSetNPCSide - Sets the preconditioning side.

5493:     Logically Collective on SNES

5495:     Input Parameter:
5496: .   snes - iterative context obtained from SNESCreate()

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

5505:     Options Database Keys:
5506: .   -snes_pc_side <right,left>

5508:     Notes:
5509:     SNESNRICHARDSON and SNESNCG only support left preconditioning.

5511:     Level: intermediate

5513: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5514: @*/
5515: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5516: {
5520:   snes->npcside= side;
5521:   return(0);
5522: }

5524: /*@
5525:     SNESGetNPCSide - Gets the preconditioning side.

5527:     Not Collective

5529:     Input Parameter:
5530: .   snes - iterative context obtained from SNESCreate()

5532:     Output Parameter:
5533: .   side - the preconditioning side, where side is one of
5534: .vb
5535:       PC_LEFT - left preconditioning
5536:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5537: .ve

5539:     Level: intermediate

5541: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5542: @*/
5543: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5544: {
5548:   *side = snes->npcside;
5549:   return(0);
5550: }

5552: /*@
5553:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5555:   Collective on SNES

5557:   Input Parameters:
5558: + snes - iterative context obtained from SNESCreate()
5559: - linesearch   - the linesearch object

5561:   Notes:
5562:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5563:   to configure it using the API).

5565:   Level: developer

5567: .seealso: SNESGetLineSearch()
5568: @*/
5569: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5570: {

5577:   PetscObjectReference((PetscObject) linesearch);
5578:   SNESLineSearchDestroy(&snes->linesearch);

5580:   snes->linesearch = linesearch;

5582:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5583:   return(0);
5584: }

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

5590:   Not Collective

5592:   Input Parameter:
5593: . snes - iterative context obtained from SNESCreate()

5595:   Output Parameter:
5596: . linesearch - linesearch context

5598:   Level: beginner

5600: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5601: @*/
5602: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5603: {
5605:   const char     *optionsprefix;

5610:   if (!snes->linesearch) {
5611:     SNESGetOptionsPrefix(snes, &optionsprefix);
5612:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5613:     SNESLineSearchSetSNES(snes->linesearch, snes);
5614:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5615:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5616:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5617:   }
5618:   *linesearch = snes->linesearch;
5619:   return(0);
5620: }