Actual source code: snes.c

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

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

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

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

 18:    Logically Collective on SNES

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

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

 27:    Level: intermediate

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

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

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

 47:    Not Collective

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

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

 55:    Level: intermediate

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

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

 71:    Logically Collective on SNES

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

 77:    Level: advanced

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

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

 92:    Logically Collective on SNES

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

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

100:    Level: advanced

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

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

116:    Logically Collective on SNES

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

121:    Level: advanced

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

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

137:    Logically Collective on SNES

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

142:    Level: advanced

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

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

159:    Logically Collective on SNES

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

165:    Level: advanced

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

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

180:    Logically Collective on SNES

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

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

188:    Level: advanced

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

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

204:    Logically Collective on SNES

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

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

212:    Level: advanced

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

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

228:    Logically Collective on SNES

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

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

236:    Level: advanced

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

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

252:   Collective on PetscViewer

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

259:    Level: intermediate

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

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

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

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

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

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

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

314:    Collective on SNES

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

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

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

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

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

339:    Collective on SNES

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

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

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

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

359:    Level: beginner

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

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

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

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

468:     PetscObjectGetComm((PetscObject)snes,&comm);
469:     MPI_Comm_rank(comm,&rank);
470:     if (!rank) {
471:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
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 routines (version 2)");
597: #endif
598:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, 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,NULL,NULL,NULL);
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,NULL,NULL,NULL);}
619:     } else {
620:       KSP       ksp;
621:       PC        pc;
622:       PetscBool match;

624:       SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,NULL);
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,NULL);
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 (!snes->jacobian && snes->mf) {
747:     Mat  J;
748:     void *functx;
749:     MatCreateSNESMF(snes,&J);
750:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
751:     MatSetFromOptions(J);
752:     SNESGetFunction(snes,NULL,NULL,&functx);
753:     SNESSetJacobian(snes,J,J,NULL,NULL);
754:     MatDestroy(&J);
755:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
756:     Mat J,B;
757:     MatCreateSNESMF(snes,&J);
758:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
759:     MatSetFromOptions(J);
760:     DMCreateMatrix(snes->dm,&B);
761:     /* sdm->computejacobian was already set to reach here */
762:     SNESSetJacobian(snes,J,B,NULL,NULL);
763:     MatDestroy(&J);
764:     MatDestroy(&B);
765:   } else if (!snes->jacobian_pre) {
766:     PetscErrorCode (*nspconstr)(DM, PetscInt, PetscInt, MatNullSpace *);
767:     PetscDS          prob;
768:     Mat              J, B;
769:     MatNullSpace     nullspace = NULL;
770:     PetscBool        hasPrec   = PETSC_FALSE;
771:     PetscInt         Nf;

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

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

800:    Collective on SNES

802:    Input Parameters:
803: +  snes - SNES object you wish to monitor
804: .  name - the monitor type one is seeking
805: .  help - message indicating what monitoring is done
806: .  manual - manual page for the monitor
807: .  monitor - the monitor function
808: -  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

810:    Level: developer

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

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

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

844:    Collective on SNES

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

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

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

892:    Notes:
893:    To see all options, run your program with the -help option or consult the users manual

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

899:    Level: beginner

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

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

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

939:   PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg);
940:   if (flg) {
941:     if (lag == -1) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Cannot set the lag to -1 from the command line since the preconditioner must be built as least once, perhaps you mean -2");
942:     SNESSetLagPreconditioner(snes,lag);
943:   }
944:   PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple SNES solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg);
945:   if (flg) {
946:     SNESSetLagPreconditionerPersists(snes,persist);
947:   }
948:   PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg);
949:   if (flg) {
950:     if (lag == -1) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_USER,"Cannot set the lag to -1 from the command line since the Jacobian must be built as least once, perhaps you mean -2");
951:     SNESSetLagJacobian(snes,lag);
952:   }
953:   PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple SNES solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg);
954:   if (flg) {
955:     SNESSetLagJacobianPersists(snes,persist);
956:   }

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

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

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

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

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

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

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

989:   flg  = PETSC_FALSE;
990:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
991:   if (set && flg) {SNESMonitorCancel(snes);}

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

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

1005:   PetscOptionsString("-snes_monitor_python","Use Python function","SNESMonitorSet",NULL,monfilename,sizeof(monfilename),&flg);
1006:   if (flg) {PetscPythonMonitorSet((PetscObject)snes,monfilename);}

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

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

1021:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
1022:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
1023:   }

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

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

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

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

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

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

1096:   for (i = 0; i < numberofsetfromoptions; i++) {
1097:     (*othersetfromoptions[i])(snes);
1098:   }

1100:   if (snes->ops->setfromoptions) {
1101:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
1102:   }

1104:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
1105:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
1106:   PetscOptionsEnd();

1108:   if (snes->linesearch) {
1109:     SNESGetLineSearch(snes, &snes->linesearch);
1110:     SNESLineSearchSetFromOptions(snes->linesearch);
1111:   }

1113:   if (snes->usesksp) {
1114:     if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
1115:     KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
1116:     KSPSetFromOptions(snes->ksp);
1117:   }

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

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

1135:    Collective on SNES

1137:    Input Parameter:
1138: .  snes - the SNES context

1140:    Level: beginner

1142: .seealso: SNESSetFromOptions(), SNESSetOptionsPrefix()
1143: @*/
1144: PetscErrorCode SNESResetFromOptions(SNES snes)
1145: {

1149:   if (snes->setfromoptionscalled) {SNESSetFromOptions(snes);}
1150:   return(0);
1151: }

1153: /*@C
1154:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1155:    the nonlinear solvers.

1157:    Logically Collective on SNES

1159:    Input Parameters:
1160: +  snes - the SNES context
1161: .  compute - function to compute the context
1162: -  destroy - function to destroy the context

1164:    Level: intermediate

1166:    Notes:
1167:    This function is currently not available from Fortran.

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

1180: /*@
1181:    SNESSetApplicationContext - Sets the optional user-defined context for
1182:    the nonlinear solvers.

1184:    Logically Collective on SNES

1186:    Input Parameters:
1187: +  snes - the SNES context
1188: -  usrP - optional user context

1190:    Level: intermediate

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

1196: .seealso: SNESGetApplicationContext()
1197: @*/
1198: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1199: {
1201:   KSP            ksp;

1205:   SNESGetKSP(snes,&ksp);
1206:   KSPSetApplicationContext(ksp,usrP);
1207:   snes->user = usrP;
1208:   return(0);
1209: }

1211: /*@
1212:    SNESGetApplicationContext - Gets the user-defined context for the
1213:    nonlinear solvers.

1215:    Not Collective

1217:    Input Parameter:
1218: .  snes - SNES context

1220:    Output Parameter:
1221: .  usrP - user context

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

1227:    Level: intermediate

1229: .seealso: SNESSetApplicationContext()
1230: @*/
1231: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1232: {
1235:   *(void**)usrP = snes->user;
1236:   return(0);
1237: }

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

1242:    Collective on SNES

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

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

1255:    Level: intermediate

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

1261: .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF(), SNESComputeJacobianDefaultColor()
1262: @*/
1263: PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1264: {
1269:   snes->mf          = mf_operator ? PETSC_TRUE : mf;
1270:   snes->mf_operator = mf_operator;
1271:   return(0);
1272: }

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

1277:    Collective on SNES

1279:    Input Parameter:
1280: .  snes - SNES context

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

1286:    Options Database:
1287: + -snes_mf - use matrix free for both the mat and pmat operator
1288: - -snes_mf_operator - use matrix free only for the mat operator

1290:    Level: intermediate

1292: .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
1293: @*/
1294: PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1295: {
1298:   if (mf)          *mf          = snes->mf;
1299:   if (mf_operator) *mf_operator = snes->mf_operator;
1300:   return(0);
1301: }

1303: /*@
1304:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1305:    at this time.

1307:    Not Collective

1309:    Input Parameter:
1310: .  snes - SNES context

1312:    Output Parameter:
1313: .  iter - iteration number

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

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

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

1331:    Level: intermediate

1333: .seealso:   SNESGetLinearSolveIterations()
1334: @*/
1335: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1336: {
1340:   *iter = snes->iter;
1341:   return(0);
1342: }

1344: /*@
1345:    SNESSetIterationNumber - Sets the current iteration number.

1347:    Not Collective

1349:    Input Parameter:
1350: +  snes - SNES context
1351: -  iter - iteration number

1353:    Level: developer

1355: .seealso:   SNESGetLinearSolveIterations()
1356: @*/
1357: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1358: {

1363:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1364:   snes->iter = iter;
1365:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1366:   return(0);
1367: }

1369: /*@
1370:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1371:    attempted by the nonlinear solver.

1373:    Not Collective

1375:    Input Parameter:
1376: .  snes - SNES context

1378:    Output Parameter:
1379: .  nfails - number of unsuccessful steps attempted

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

1384:    Level: intermediate

1386: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1387:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1388: @*/
1389: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1390: {
1394:   *nfails = snes->numFailures;
1395:   return(0);
1396: }

1398: /*@
1399:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1400:    attempted by the nonlinear solver before it gives up.

1402:    Not Collective

1404:    Input Parameters:
1405: +  snes     - SNES context
1406: -  maxFails - maximum of unsuccessful steps

1408:    Level: intermediate

1410: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1411:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1412: @*/
1413: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1414: {
1417:   snes->maxFailures = maxFails;
1418:   return(0);
1419: }

1421: /*@
1422:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1423:    attempted by the nonlinear solver before it gives up.

1425:    Not Collective

1427:    Input Parameter:
1428: .  snes     - SNES context

1430:    Output Parameter:
1431: .  maxFails - maximum of unsuccessful steps

1433:    Level: intermediate

1435: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1436:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1438: @*/
1439: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1440: {
1444:   *maxFails = snes->maxFailures;
1445:   return(0);
1446: }

1448: /*@
1449:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1450:      done by SNES.

1452:    Not Collective

1454:    Input Parameter:
1455: .  snes     - SNES context

1457:    Output Parameter:
1458: .  nfuncs - number of evaluations

1460:    Level: intermediate

1462:    Notes:
1463:     Reset every time SNESSolve is called unless SNESSetCountersReset() is used.

1465: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1466: @*/
1467: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1468: {
1472:   *nfuncs = snes->nfuncs;
1473:   return(0);
1474: }

1476: /*@
1477:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1478:    linear solvers.

1480:    Not Collective

1482:    Input Parameter:
1483: .  snes - SNES context

1485:    Output Parameter:
1486: .  nfails - number of failed solves

1488:    Level: intermediate

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

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

1496: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1497: @*/
1498: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1499: {
1503:   *nfails = snes->numLinearSolveFailures;
1504:   return(0);
1505: }

1507: /*@
1508:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1509:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1511:    Logically Collective on SNES

1513:    Input Parameters:
1514: +  snes     - SNES context
1515: -  maxFails - maximum allowed linear solve failures

1517:    Level: intermediate

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

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

1525: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1526: @*/
1527: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1528: {
1532:   snes->maxLinearSolveFailures = maxFails;
1533:   return(0);
1534: }

1536: /*@
1537:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1538:      are allowed before SNES terminates

1540:    Not Collective

1542:    Input Parameter:
1543: .  snes     - SNES context

1545:    Output Parameter:
1546: .  maxFails - maximum of unsuccessful solves allowed

1548:    Level: intermediate

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

1553: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1554: @*/
1555: PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1556: {
1560:   *maxFails = snes->maxLinearSolveFailures;
1561:   return(0);
1562: }

1564: /*@
1565:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1566:    used by the nonlinear solver.

1568:    Not Collective

1570:    Input Parameter:
1571: .  snes - SNES context

1573:    Output Parameter:
1574: .  lits - number of linear iterations

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

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

1582:    Level: intermediate

1584: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1585: @*/
1586: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1587: {
1591:   *lits = snes->linear_its;
1592:   return(0);
1593: }

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

1599:    Logically Collective on SNES

1601:    Input Parameter:
1602: +  snes - SNES context
1603: -  reset - whether to reset the counters or not

1605:    Notes:
1606:    This defaults to PETSC_TRUE

1608:    Level: developer

1610: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1611: @*/
1612: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1613: {
1617:   snes->counters_reset = reset;
1618:   return(0);
1619: }


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

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

1627:    Input Parameters:
1628: +  snes - the SNES context
1629: -  ksp - the KSP context

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

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

1638:    Level: developer

1640: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1641: @*/
1642: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1643: {

1650:   PetscObjectReference((PetscObject)ksp);
1651:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1652:   snes->ksp = ksp;
1653:   return(0);
1654: }

1656: /* -----------------------------------------------------------*/
1657: /*@
1658:    SNESCreate - Creates a nonlinear solver context.

1660:    Collective

1662:    Input Parameters:
1663: .  comm - MPI communicator

1665:    Output Parameter:
1666: .  outsnes - the new SNES context

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

1676:    Level: beginner

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

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

1688: .seealso: SNESSolve(), SNESDestroy(), SNES, SNESSetLagPreconditioner(), SNESSetLagJacobian()

1690: @*/
1691: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1692: {
1694:   SNES           snes;
1695:   SNESKSPEW      *kctx;

1699:   *outsnes = NULL;
1700:   SNESInitializePackage();

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

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

1766:   snes->mf          = PETSC_FALSE;
1767:   snes->mf_operator = PETSC_FALSE;
1768:   snes->mf_version  = 1;

1770:   snes->numLinearSolveFailures = 0;
1771:   snes->maxLinearSolveFailures = 1;

1773:   snes->vizerotolerance = 1.e-8;
1774:   snes->checkjacdomainerror = PetscDefined(USE_DEBUG) ? PETSC_TRUE : PETSC_FALSE;

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

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

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

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

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

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

1806:      Collective on snes

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

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

1816:    Level: intermediate

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

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

1826:    Logically Collective on SNES

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

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

1840:    Level: beginner

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

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

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


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

1872:    Logically Collective on SNES

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

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

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

1883:    Level: developer

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

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

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

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

1911:    Logically Collective on SNES

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

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

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

1929:    Level: developer

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


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

1946:    Logically Collective on SNES

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

1952:    Level: advanced

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


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

1968:   Logically Collective on SNES

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

1973: - normschedule - the frequency of norm computation

1975:   Level: developer

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

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

1990:   Not Collective

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

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

1998:   Level: developer

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

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

2014:   Not Collective

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

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

2022:   Level: developer

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

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

2038:   Not Collective

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

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

2046:   Level: developer

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

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

2063:    Logically Collective on SNES

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

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

2078:    Level: developer

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


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

2095:    Logically Collective on SNES

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

2101:    Level: advanced

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

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

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

2120:      Collective on snes

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

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

2130:    Level: intermediate

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

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

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

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

2149:    Level: intermediate

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

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

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

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

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

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

2198:    Logically Collective on SNES

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

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

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

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

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

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

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

2228:    Level: intermediate

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

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

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

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

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

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

2262:    Level: advanced

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

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

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

2283:    Logically Collective on SNES

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

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

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

2297:    Level: intermediate

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

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

2315:    Logically Collective on SNES

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

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

2323:    Level: intermediate

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

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

2339:    Collective on SNES

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

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

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

2353:    Level: developer

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

2369:   VecValidValues(x,2,PETSC_TRUE);

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

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

2407:    Collective on SNES

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

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

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

2422:    Level: developer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2625:    Collective on SNES

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

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

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


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

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

2661:    Level: developer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2916:      Collective on snes

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

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

2926:    Level: intermediate

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

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

2935:    Logically Collective on SNES

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

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

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

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

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

2958:    Level: beginner

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

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

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

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

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

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

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

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

3006:    Level: advanced

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

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

3027: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3028: {
3030:   DM             dm;
3031:   DMSNES         sdm;

3034:   SNESGetDM(snes,&dm);
3035:   DMGetDMSNES(dm,&sdm);
3036:   if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3037:     DM        dm;
3038:     PetscBool isdense,ismf;

3040:     SNESGetDM(snes,&dm);
3041:     PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&isdense,MATSEQDENSE,MATMPIDENSE,MATDENSE,NULL);
3042:     PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&ismf,MATMFFD,MATSHELL,NULL);
3043:     if (isdense) {
3044:       DMSNESSetJacobian(dm,SNESComputeJacobianDefault,NULL);
3045:     } else if (!ismf) {
3046:       DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
3047:     }
3048:   }
3049:   return(0);
3050: }

3052: /*@
3053:    SNESSetUp - Sets up the internal data structures for the later use
3054:    of a nonlinear solver.

3056:    Collective on SNES

3058:    Input Parameters:
3059: .  snes - the SNES context

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

3068:    Level: advanced

3070: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
3071: @*/
3072: PetscErrorCode  SNESSetUp(SNES snes)
3073: {
3075:   DM             dm;
3076:   DMSNES         sdm;
3077:   SNESLineSearch linesearch, pclinesearch;
3078:   void           *lsprectx,*lspostctx;
3079:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
3080:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
3081:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
3082:   Vec            f,fpc;
3083:   void           *funcctx;
3084:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
3085:   void           *jacctx,*appctx;
3086:   Mat            j,jpre;

3090:   if (snes->setupcalled) return(0);
3091:   PetscLogEventBegin(SNES_Setup,snes,0,0,0);

3093:   if (!((PetscObject)snes)->type_name) {
3094:     SNESSetType(snes,SNESNEWTONLS);
3095:   }

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

3099:   SNESGetDM(snes,&dm);
3100:   DMGetDMSNES(dm,&sdm);
3101:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
3102:   SNESSetDefaultComputeJacobian(snes);

3104:   if (!snes->vec_func) {
3105:     DMCreateGlobalVector(dm,&snes->vec_func);
3106:   }

3108:   if (!snes->ksp) {
3109:     SNESGetKSP(snes, &snes->ksp);
3110:   }

3112:   if (snes->linesearch) {
3113:     SNESGetLineSearch(snes, &snes->linesearch);
3114:     SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);
3115:   }

3117:   if (snes->npc && (snes->npcside== PC_LEFT)) {
3118:     snes->mf          = PETSC_TRUE;
3119:     snes->mf_operator = PETSC_FALSE;
3120:   }

3122:   if (snes->npc) {
3123:     /* copy the DM over */
3124:     SNESGetDM(snes,&dm);
3125:     SNESSetDM(snes->npc,dm);

3127:     SNESGetFunction(snes,&f,&func,&funcctx);
3128:     VecDuplicate(f,&fpc);
3129:     SNESSetFunction(snes->npc,fpc,func,funcctx);
3130:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
3131:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
3132:     SNESGetApplicationContext(snes,&appctx);
3133:     SNESSetApplicationContext(snes->npc,appctx);
3134:     VecDestroy(&fpc);

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

3139:     /* default to 1 iteration */
3140:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
3141:     if (snes->npcside==PC_RIGHT) {
3142:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
3143:     } else {
3144:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
3145:     }
3146:     SNESSetFromOptions(snes->npc);

3148:     /* copy the line search context over */
3149:     if (snes->linesearch && snes->npc->linesearch) {
3150:       SNESGetLineSearch(snes,&linesearch);
3151:       SNESGetLineSearch(snes->npc,&pclinesearch);
3152:       SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
3153:       SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
3154:       SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
3155:       SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
3156:       PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
3157:     }
3158:   }
3159:   if (snes->mf) {
3160:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
3161:   }
3162:   if (snes->ops->usercompute && !snes->user) {
3163:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
3164:   }

3166:   snes->jac_iter = 0;
3167:   snes->pre_iter = 0;

3169:   if (snes->ops->setup) {
3170:     (*snes->ops->setup)(snes);
3171:   }

3173:   SNESSetDefaultComputeJacobian(snes);

3175:   if (snes->npc && (snes->npcside== PC_LEFT)) {
3176:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3177:       if (snes->linesearch){
3178:         SNESGetLineSearch(snes,&linesearch);
3179:         SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
3180:       }
3181:     }
3182:   }
3183:   PetscLogEventEnd(SNES_Setup,snes,0,0,0);
3184:   snes->setupcalled = PETSC_TRUE;
3185:   return(0);
3186: }

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

3191:    Collective on SNES

3193:    Input Parameter:
3194: .  snes - iterative context obtained from SNESCreate()

3196:    Level: intermediate

3198:    Notes:
3199:     Also calls the application context destroy routine set with SNESSetComputeApplicationContext()

3201: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
3202: @*/
3203: PetscErrorCode  SNESReset(SNES snes)
3204: {

3209:   if (snes->ops->userdestroy && snes->user) {
3210:     (*snes->ops->userdestroy)((void**)&snes->user);
3211:     snes->user = NULL;
3212:   }
3213:   if (snes->npc) {
3214:     SNESReset(snes->npc);
3215:   }

3217:   if (snes->ops->reset) {
3218:     (*snes->ops->reset)(snes);
3219:   }
3220:   if (snes->ksp) {
3221:     KSPReset(snes->ksp);
3222:   }

3224:   if (snes->linesearch) {
3225:     SNESLineSearchReset(snes->linesearch);
3226:   }

3228:   VecDestroy(&snes->vec_rhs);
3229:   VecDestroy(&snes->vec_sol);
3230:   VecDestroy(&snes->vec_sol_update);
3231:   VecDestroy(&snes->vec_func);
3232:   MatDestroy(&snes->jacobian);
3233:   MatDestroy(&snes->jacobian_pre);
3234:   VecDestroyVecs(snes->nwork,&snes->work);
3235:   VecDestroyVecs(snes->nvwork,&snes->vwork);

3237:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3239:   snes->nwork       = snes->nvwork = 0;
3240:   snes->setupcalled = PETSC_FALSE;
3241:   return(0);
3242: }

3244: /*@
3245:    SNESDestroy - Destroys the nonlinear solver context that was created
3246:    with SNESCreate().

3248:    Collective on SNES

3250:    Input Parameter:
3251: .  snes - the SNES context

3253:    Level: beginner

3255: .seealso: SNESCreate(), SNESSolve()
3256: @*/
3257: PetscErrorCode  SNESDestroy(SNES *snes)
3258: {

3262:   if (!*snes) return(0);
3264:   if (--((PetscObject)(*snes))->refct > 0) {*snes = NULL; return(0);}

3266:   SNESReset((*snes));
3267:   SNESDestroy(&(*snes)->npc);

3269:   /* if memory was published with SAWs then destroy it */
3270:   PetscObjectSAWsViewOff((PetscObject)*snes);
3271:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

3273:   if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
3274:   DMDestroy(&(*snes)->dm);
3275:   KSPDestroy(&(*snes)->ksp);
3276:   SNESLineSearchDestroy(&(*snes)->linesearch);

3278:   PetscFree((*snes)->kspconvctx);
3279:   if ((*snes)->ops->convergeddestroy) {
3280:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
3281:   }
3282:   if ((*snes)->conv_hist_alloc) {
3283:     PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its);
3284:   }
3285:   SNESMonitorCancel((*snes));
3286:   PetscHeaderDestroy(snes);
3287:   return(0);
3288: }

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

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

3295:    Logically Collective on SNES

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

3302:    Options Database Keys:
3303: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3304: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3305: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3306: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag

3308:    Notes:
3309:    The default is 1
3310:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagPreconditionerPersists() was called
3311:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

3313:    Level: intermediate

3315: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESSetLagPreconditionerPersists(),
3316:           SNESSetLagJacobianPersists()

3318: @*/
3319: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3320: {
3323:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3324:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3326:   snes->lagpreconditioner = lag;
3327:   return(0);
3328: }

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

3333:    Logically Collective on SNES

3335:    Input Parameters:
3336: +  snes - the SNES context
3337: -  steps - the number of refinements to do, defaults to 0

3339:    Options Database Keys:
3340: .    -snes_grid_sequence <steps>

3342:    Level: intermediate

3344:    Notes:
3345:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

3349: @*/
3350: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3351: {
3355:   snes->gridsequence = steps;
3356:   return(0);
3357: }

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

3362:    Logically Collective on SNES

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

3367:    Output Parameter:
3368: .  steps - the number of refinements to do, defaults to 0

3370:    Options Database Keys:
3371: .    -snes_grid_sequence <steps>

3373:    Level: intermediate

3375:    Notes:
3376:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

3380: @*/
3381: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3382: {
3385:   *steps = snes->gridsequence;
3386:   return(0);
3387: }

3389: /*@
3390:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3392:    Not Collective

3394:    Input Parameter:
3395: .  snes - the SNES context

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

3401:    Options Database Keys:
3402: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3403: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3404: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3405: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag

3407:    Notes:
3408:    The default is 1
3409:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3411:    Level: intermediate

3413: .seealso: SNESSetTrustRegionTolerance(), SNESSetLagPreconditioner(), SNESSetLagJacobianPersists(), SNESSetLagPreconditionerPersists()

3415: @*/
3416: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3417: {
3420:   *lag = snes->lagpreconditioner;
3421:   return(0);
3422: }

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

3428:    Logically Collective on SNES

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

3435:    Options Database Keys:
3436: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3437: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3438: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3439: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag.

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

3447:    Level: intermediate

3449: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagPreconditioner(), SNESGetLagJacobianPersists(), SNESSetLagPreconditionerPersists()

3451: @*/
3452: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3453: {
3456:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3457:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3459:   snes->lagjacobian = lag;
3460:   return(0);
3461: }

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

3466:    Not Collective

3468:    Input Parameter:
3469: .  snes - the SNES context

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

3475:    Notes:
3476:    The default is 1
3477:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagJacobianPersists() was called.

3479:    Level: intermediate

3481: .seealso: SNESSetTrustRegionTolerance(), SNESSetLagJacobian(), SNESSetLagPreconditioner(), SNESGetLagPreconditioner(), SNESSetLagJacobianPersists(), SNESSetLagPreconditionerPersists()

3483: @*/
3484: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3485: {
3488:   *lag = snes->lagjacobian;
3489:   return(0);
3490: }

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

3495:    Logically collective on SNES

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

3501:    Options Database Keys:
3502: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3503: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3504: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3505: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag


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

3513:    Level: developer

3515: .seealso: SNESSetLagPreconditionerPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC(), SNESSetLagJacobianPersists()

3517: @*/
3518: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3519: {
3523:   snes->lagjac_persist = flg;
3524:   return(0);
3525: }

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

3530:    Logically Collective on SNES

3532:    Input Parameter:
3533: +  snes - the SNES context
3534: -   flg - preconditioner lagging persists if true

3536:    Options Database Keys:
3537: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3538: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3539: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3540: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag

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

3547:    Level: developer

3549: .seealso: SNESSetLagJacobianPersists(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESGetNPC(), SNESSetLagPreconditioner()

3551: @*/
3552: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3553: {
3557:   snes->lagpre_persist = flg;
3558:   return(0);
3559: }

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

3564:    Logically Collective on SNES

3566:    Input Parameters:
3567: +  snes - the SNES context
3568: -  force - PETSC_TRUE require at least one iteration

3570:    Options Database Keys:
3571: .    -snes_force_iteration <force> - Sets forcing an iteration

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

3576:    Level: intermediate

3578: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3579: @*/
3580: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3581: {
3584:   snes->forceiteration = force;
3585:   return(0);
3586: }

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

3591:    Logically Collective on SNES

3593:    Input Parameters:
3594: .  snes - the SNES context

3596:    Output Parameter:
3597: .  force - PETSC_TRUE requires at least one iteration.

3599:    Level: intermediate

3601: .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3602: @*/
3603: PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
3604: {
3607:   *force = snes->forceiteration;
3608:   return(0);
3609: }

3611: /*@
3612:    SNESSetTolerances - Sets various parameters used in convergence tests.

3614:    Logically Collective on SNES

3616:    Input Parameters:
3617: +  snes - the SNES context
3618: .  abstol - absolute convergence tolerance
3619: .  rtol - relative convergence tolerance
3620: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3621: .  maxit - maximum number of iterations
3622: -  maxf - maximum number of function evaluations (-1 indicates no limit)

3624:    Options Database Keys:
3625: +    -snes_atol <abstol> - Sets abstol
3626: .    -snes_rtol <rtol> - Sets rtol
3627: .    -snes_stol <stol> - Sets stol
3628: .    -snes_max_it <maxit> - Sets maxit
3629: -    -snes_max_funcs <maxf> - Sets maxf

3631:    Notes:
3632:    The default maximum number of iterations is 50.
3633:    The default maximum number of function evaluations is 1000.

3635:    Level: intermediate

3637: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3638: @*/
3639: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3640: {

3649:   if (abstol != PETSC_DEFAULT) {
3650:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3651:     snes->abstol = abstol;
3652:   }
3653:   if (rtol != PETSC_DEFAULT) {
3654:     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);
3655:     snes->rtol = rtol;
3656:   }
3657:   if (stol != PETSC_DEFAULT) {
3658:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3659:     snes->stol = stol;
3660:   }
3661:   if (maxit != PETSC_DEFAULT) {
3662:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3663:     snes->max_its = maxit;
3664:   }
3665:   if (maxf != PETSC_DEFAULT) {
3666:     if (maxf < -1) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be -1 or nonnegative",maxf);
3667:     snes->max_funcs = maxf;
3668:   }
3669:   snes->tolerancesset = PETSC_TRUE;
3670:   return(0);
3671: }

3673: /*@
3674:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3676:    Logically Collective on SNES

3678:    Input Parameters:
3679: +  snes - the SNES context
3680: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3682:    Options Database Keys:
3683: .    -snes_divergence_tolerance <divtol> - Sets divtol

3685:    Notes:
3686:    The default divergence tolerance is 1e4.

3688:    Level: intermediate

3690: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3691: @*/
3692: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3693: {

3698:   if (divtol != PETSC_DEFAULT) {
3699:     snes->divtol = divtol;
3700:   }
3701:   else {
3702:     snes->divtol = 1.0e4;
3703:   }
3704:   return(0);
3705: }

3707: /*@
3708:    SNESGetTolerances - Gets various parameters used in convergence tests.

3710:    Not Collective

3712:    Input Parameters:
3713: +  snes - the SNES context
3714: .  atol - absolute convergence tolerance
3715: .  rtol - relative convergence tolerance
3716: .  stol -  convergence tolerance in terms of the norm
3717:            of the change in the solution between steps
3718: .  maxit - maximum number of iterations
3719: -  maxf - maximum number of function evaluations

3721:    Notes:
3722:    The user can specify NULL for any parameter that is not needed.

3724:    Level: intermediate

3726: .seealso: SNESSetTolerances()
3727: @*/
3728: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3729: {
3732:   if (atol)  *atol  = snes->abstol;
3733:   if (rtol)  *rtol  = snes->rtol;
3734:   if (stol)  *stol  = snes->stol;
3735:   if (maxit) *maxit = snes->max_its;
3736:   if (maxf)  *maxf  = snes->max_funcs;
3737:   return(0);
3738: }

3740: /*@
3741:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3743:    Not Collective

3745:    Input Parameters:
3746: +  snes - the SNES context
3747: -  divtol - divergence tolerance

3749:    Level: intermediate

3751: .seealso: SNESSetDivergenceTolerance()
3752: @*/
3753: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3754: {
3757:   if (divtol) *divtol = snes->divtol;
3758:   return(0);
3759: }

3761: /*@
3762:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3764:    Logically Collective on SNES

3766:    Input Parameters:
3767: +  snes - the SNES context
3768: -  tol - tolerance

3770:    Options Database Key:
3771: .  -snes_trtol <tol> - Sets tol

3773:    Level: intermediate

3775: .seealso: SNESSetTolerances()
3776: @*/
3777: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3778: {
3782:   snes->deltatol = tol;
3783:   return(0);
3784: }

3786: /*
3787:    Duplicate the lg monitors for SNES from KSP; for some reason with
3788:    dynamic libraries things don't work under Sun4 if we just use
3789:    macros instead of functions
3790: */
3791: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3792: {

3797:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3798:   return(0);
3799: }

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

3806:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3807:   return(0);
3808: }

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

3812: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3813: {
3814:   PetscDrawLG      lg;
3815:   PetscErrorCode   ierr;
3816:   PetscReal        x,y,per;
3817:   PetscViewer      v = (PetscViewer)monctx;
3818:   static PetscReal prev; /* should be in the context */
3819:   PetscDraw        draw;

3823:   PetscViewerDrawGetDrawLG(v,0,&lg);
3824:   if (!n) {PetscDrawLGReset(lg);}
3825:   PetscDrawLGGetDraw(lg,&draw);
3826:   PetscDrawSetTitle(draw,"Residual norm");
3827:   x    = (PetscReal)n;
3828:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3829:   else y = -15.0;
3830:   PetscDrawLGAddPoint(lg,&x,&y);
3831:   if (n < 20 || !(n % 5) || snes->reason) {
3832:     PetscDrawLGDraw(lg);
3833:     PetscDrawLGSave(lg);
3834:   }

3836:   PetscViewerDrawGetDrawLG(v,1,&lg);
3837:   if (!n) {PetscDrawLGReset(lg);}
3838:   PetscDrawLGGetDraw(lg,&draw);
3839:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3840:    SNESMonitorRange_Private(snes,n,&per);
3841:   x    = (PetscReal)n;
3842:   y    = 100.0*per;
3843:   PetscDrawLGAddPoint(lg,&x,&y);
3844:   if (n < 20 || !(n % 5) || snes->reason) {
3845:     PetscDrawLGDraw(lg);
3846:     PetscDrawLGSave(lg);
3847:   }

3849:   PetscViewerDrawGetDrawLG(v,2,&lg);
3850:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3851:   PetscDrawLGGetDraw(lg,&draw);
3852:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3853:   x    = (PetscReal)n;
3854:   y    = (prev - rnorm)/prev;
3855:   PetscDrawLGAddPoint(lg,&x,&y);
3856:   if (n < 20 || !(n % 5) || snes->reason) {
3857:     PetscDrawLGDraw(lg);
3858:     PetscDrawLGSave(lg);
3859:   }

3861:   PetscViewerDrawGetDrawLG(v,3,&lg);
3862:   if (!n) {PetscDrawLGReset(lg);}
3863:   PetscDrawLGGetDraw(lg,&draw);
3864:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3865:   x    = (PetscReal)n;
3866:   y    = (prev - rnorm)/(prev*per);
3867:   if (n > 2) { /*skip initial crazy value */
3868:     PetscDrawLGAddPoint(lg,&x,&y);
3869:   }
3870:   if (n < 20 || !(n % 5) || snes->reason) {
3871:     PetscDrawLGDraw(lg);
3872:     PetscDrawLGSave(lg);
3873:   }
3874:   prev = rnorm;
3875:   return(0);
3876: }

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

3881:    Collective on SNES

3883:    Input Parameters:
3884: +  snes - nonlinear solver context obtained from SNESCreate()
3885: .  iter - iteration number
3886: -  rnorm - relative norm of the residual

3888:    Notes:
3889:    This routine is called by the SNES implementations.
3890:    It does not typically need to be called by the user.

3892:    Level: developer

3894: .seealso: SNESMonitorSet()
3895: @*/
3896: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3897: {
3899:   PetscInt       i,n = snes->numbermonitors;

3902:   VecLockReadPush(snes->vec_sol);
3903:   for (i=0; i<n; i++) {
3904:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3905:   }
3906:   VecLockReadPop(snes->vec_sol);
3907:   return(0);
3908: }

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

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

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

3919:      Collective on snes

3921:     Input Parameters:
3922: +    snes - the SNES context
3923: .    its - iteration number
3924: .    norm - 2-norm function value (may be estimated)
3925: -    mctx - [optional] monitoring context

3927:    Level: advanced

3929: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3930: M*/

3932: /*@C
3933:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3934:    iteration of the nonlinear solver to display the iteration's
3935:    progress.

3937:    Logically Collective on SNES

3939:    Input Parameters:
3940: +  snes - the SNES context
3941: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3942: .  mctx - [optional] user-defined context for private data for the
3943:           monitor routine (use NULL if no context is desired)
3944: -  monitordestroy - [optional] routine that frees monitor context
3945:           (may be NULL)

3947:    Options Database Keys:
3948: +    -snes_monitor        - sets SNESMonitorDefault()
3949: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3950:                             uses SNESMonitorLGCreate()
3951: -    -snes_monitor_cancel - cancels all monitors that have
3952:                             been hardwired into a code by
3953:                             calls to SNESMonitorSet(), but
3954:                             does not cancel those set via
3955:                             the options database.

3957:    Notes:
3958:    Several different monitoring routines may be set by calling
3959:    SNESMonitorSet() multiple times; all will be called in the
3960:    order in which they were set.

3962:    Fortran Notes:
3963:     Only a single monitor function can be set for each SNES object

3965:    Level: intermediate

3967: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3968: @*/
3969: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3970: {
3971:   PetscInt       i;
3973:   PetscBool      identical;

3977:   for (i=0; i<snes->numbermonitors;i++) {
3978:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3979:     if (identical) return(0);
3980:   }
3981:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3982:   snes->monitor[snes->numbermonitors]          = f;
3983:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3984:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3985:   return(0);
3986: }

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

3991:    Logically Collective on SNES

3993:    Input Parameters:
3994: .  snes - the SNES context

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

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

4004:    Level: intermediate

4006: .seealso: SNESMonitorDefault(), SNESMonitorSet()
4007: @*/
4008: PetscErrorCode  SNESMonitorCancel(SNES snes)
4009: {
4011:   PetscInt       i;

4015:   for (i=0; i<snes->numbermonitors; i++) {
4016:     if (snes->monitordestroy[i]) {
4017:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
4018:     }
4019:   }
4020:   snes->numbermonitors = 0;
4021:   return(0);
4022: }

4024: /*MC
4025:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

4031:      Collective on snes

4033:     Input Parameters:
4034: +    snes - the SNES context
4035: .    it - current iteration (0 is the first and is before any Newton step)
4036: .    xnorm - 2-norm of current iterate
4037: .    gnorm - 2-norm of current step
4038: .    f - 2-norm of function
4039: -    cctx - [optional] convergence context

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

4044:    Level: intermediate

4046: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
4047: M*/

4049: /*@C
4050:    SNESSetConvergenceTest - Sets the function that is to be used
4051:    to test for convergence of the nonlinear iterative solution.

4053:    Logically Collective on SNES

4055:    Input Parameters:
4056: +  snes - the SNES context
4057: .  SNESConvergenceTestFunction - routine to test for convergence
4058: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
4059: -  destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)

4061:    Level: advanced

4063: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
4064: @*/
4065: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
4066: {

4071:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
4072:   if (snes->ops->convergeddestroy) {
4073:     (*snes->ops->convergeddestroy)(snes->cnvP);
4074:   }
4075:   snes->ops->converged        = SNESConvergenceTestFunction;
4076:   snes->ops->convergeddestroy = destroy;
4077:   snes->cnvP                  = cctx;
4078:   return(0);
4079: }

4081: /*@
4082:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

4084:    Not Collective

4086:    Input Parameter:
4087: .  snes - the SNES context

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

4093:    Options Database:
4094: .   -snes_converged_reason - prints the reason to standard out

4096:    Level: intermediate

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

4101: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
4102: @*/
4103: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4104: {
4108:   *reason = snes->reason;
4109:   return(0);
4110: }

4112: /*@
4113:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

4115:    Not Collective

4117:    Input Parameters:
4118: +  snes - the SNES context
4119: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4120:             manual pages for the individual convergence tests for complete lists

4122:    Level: intermediate

4124: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
4125: @*/
4126: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
4127: {
4130:   snes->reason = reason;
4131:   return(0);
4132: }

4134: /*@
4135:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

4137:    Logically Collective on SNES

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

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

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

4155:    Level: intermediate

4157: .seealso: SNESGetConvergenceHistory()

4159: @*/
4160: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4161: {

4168:   if (!a) {
4169:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
4170:     PetscCalloc2(na,&a,na,&its);
4171:     snes->conv_hist_alloc = PETSC_TRUE;
4172:   }
4173:   snes->conv_hist       = a;
4174:   snes->conv_hist_its   = its;
4175:   snes->conv_hist_max   = na;
4176:   snes->conv_hist_len   = 0;
4177:   snes->conv_hist_reset = reset;
4178:   return(0);
4179: }

4181: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4182: #include <engine.h>   /* MATLAB include file */
4183: #include <mex.h>      /* MATLAB include file */

4185: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4186: {
4187:   mxArray   *mat;
4188:   PetscInt  i;
4189:   PetscReal *ar;

4192:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4193:   ar  = (PetscReal*) mxGetData(mat);
4194:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4195:   PetscFunctionReturn(mat);
4196: }
4197: #endif

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

4202:    Not Collective

4204:    Input Parameter:
4205: .  snes - iterative context obtained from SNESCreate()

4207:    Output Parameters:
4208: +  a   - array to hold history
4209: .  its - integer array holds the number of linear iterations (or
4210:          negative if not converged) for each solve.
4211: -  na  - size of a and its

4213:    Notes:
4214:     The calling sequence for this routine in Fortran is
4215: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

4221:    Level: intermediate

4223: .seealso: SNESSetConvergenceHistory()

4225: @*/
4226: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4227: {
4230:   if (a)   *a   = snes->conv_hist;
4231:   if (its) *its = snes->conv_hist_its;
4232:   if (na)  *na  = snes->conv_hist_len;
4233:   return(0);
4234: }

4236: /*@C
4237:   SNESSetUpdate - Sets the general-purpose update function called
4238:   at the beginning of every iteration of the nonlinear solve. Specifically
4239:   it is called just before the Jacobian is "evaluated".

4241:   Logically Collective on SNES

4243:   Input Parameters:
4244: + snes - The nonlinear solver context
4245: - func - The function

4247:   Calling sequence of func:
4248: $ func (SNES snes, PetscInt step);

4250: . step - The current step of the iteration

4252:   Level: advanced

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

4257: .seealso SNESSetJacobian(), SNESSolve()
4258: @*/
4259: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4260: {
4263:   snes->ops->update = func;
4264:   return(0);
4265: }

4267: /*
4268:    SNESScaleStep_Private - Scales a step so that its length is less than the
4269:    positive parameter delta.

4271:     Input Parameters:
4272: +   snes - the SNES context
4273: .   y - approximate solution of linear system
4274: .   fnorm - 2-norm of current function
4275: -   delta - trust region size

4277:     Output Parameters:
4278: +   gpnorm - predicted function norm at the new point, assuming local
4279:     linearization.  The value is zero if the step lies within the trust
4280:     region, and exceeds zero otherwise.
4281: -   ynorm - 2-norm of the step

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

4287: */
4288: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4289: {
4290:   PetscReal      nrm;
4291:   PetscScalar    cnorm;


4299:   VecNorm(y,NORM_2,&nrm);
4300:   if (nrm > *delta) {
4301:     nrm     = *delta/nrm;
4302:     *gpnorm = (1.0 - nrm)*(*fnorm);
4303:     cnorm   = nrm;
4304:     VecScale(y,cnorm);
4305:     *ynorm  = *delta;
4306:   } else {
4307:     *gpnorm = 0.0;
4308:     *ynorm  = nrm;
4309:   }
4310:   return(0);
4311: }

4313: /*@C
4314:    SNESConvergedReasonView - Displays the reason a SNES solve converged or diverged to a viewer

4316:    Collective on SNES

4318:    Parameter:
4319: +  snes - iterative context obtained from SNESCreate()
4320: -  viewer - the viewer to display the reason


4323:    Options Database Keys:
4324: +  -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4325: -  -snes_converged_reason ::failed - only print reason and number of iterations when diverged

4327:   Notes:
4328:      To change the format of the output call PetscViewerPushFormat(viewer,format) before this call. Use PETSC_VIEWER_DEFAULT for the default,
4329:      use PETSC_VIEWER_FAILED to only display a reason if it fails.

4331:    Level: beginner

4333: .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault(), SNESGetConvergedReason(), SNESConvergedReasonViewFromOptions(),
4334:           PetscViewerPushFormat(), PetscViewerPopFormat()

4336: @*/
4337: PetscErrorCode  SNESConvergedReasonView(SNES snes,PetscViewer viewer)
4338: {
4339:   PetscViewerFormat format;
4340:   PetscBool         isAscii;
4341:   PetscErrorCode    ierr;

4344:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4345:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
4346:   if (isAscii) {
4347:     PetscViewerGetFormat(viewer, &format);
4348:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
4349:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4350:       DM              dm;
4351:       Vec             u;
4352:       PetscDS         prob;
4353:       PetscInt        Nf, f;
4354:       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4355:       void            **exactCtx;
4356:       PetscReal       error;

4358:       SNESGetDM(snes, &dm);
4359:       SNESGetSolution(snes, &u);
4360:       DMGetDS(dm, &prob);
4361:       PetscDSGetNumFields(prob, &Nf);
4362:       PetscMalloc2(Nf, &exactSol, Nf, &exactCtx);
4363:       for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]);}
4364:       DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error);
4365:       PetscFree2(exactSol, exactCtx);
4366:       if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
4367:       else                 {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
4368:     }
4369:     if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4370:       if (((PetscObject) snes)->prefix) {
4371:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4372:       } else {
4373:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4374:       }
4375:     } else if (snes->reason <= 0) {
4376:       if (((PetscObject) snes)->prefix) {
4377:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4378:       } else {
4379:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4380:       }
4381:     }
4382:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4383:   }
4384:   return(0);
4385: }

4387: /*@
4388:   SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed.

4390:   Collective on SNES

4392:   Input Parameters:
4393: . snes   - the SNES object

4395:   Level: intermediate

4397: .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault(), SNESGetConvergedReason(), SNESConvergedReasonView()

4399: @*/
4400: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4401: {
4402:   PetscErrorCode    ierr;
4403:   PetscViewer       viewer;
4404:   PetscBool         flg;
4405:   static PetscBool  incall = PETSC_FALSE;
4406:   PetscViewerFormat format;

4409:   if (incall) return(0);
4410:   incall = PETSC_TRUE;
4411:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4412:   if (flg) {
4413:     PetscViewerPushFormat(viewer,format);
4414:     SNESConvergedReasonView(snes,viewer);
4415:     PetscViewerPopFormat(viewer);
4416:     PetscViewerDestroy(&viewer);
4417:   }
4418:   incall = PETSC_FALSE;
4419:   return(0);
4420: }

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

4426:    Collective on SNES

4428:    Input Parameters:
4429: +  snes - the SNES context
4430: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4431: -  x - the solution vector.

4433:    Notes:
4434:    The user should initialize the vector,x, with the initial guess
4435:    for the nonlinear solve prior to calling SNESSolve.  In particular,
4436:    to employ an initial guess of zero, the user should explicitly set
4437:    this vector to zero by calling VecSet().

4439:    Level: beginner

4441: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4442: @*/
4443: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4444: {
4445:   PetscErrorCode    ierr;
4446:   PetscBool         flg;
4447:   PetscInt          grid;
4448:   Vec               xcreated = NULL;
4449:   DM                dm;


4458:   /* High level operations using the nonlinear solver */
4459:   {
4460:     PetscViewer       viewer;
4461:     PetscViewerFormat format;
4462:     PetscInt          num;
4463:     PetscBool         flg;
4464:     static PetscBool  incall = PETSC_FALSE;

4466:     if (!incall) {
4467:       /* Estimate the convergence rate of the discretization */
4468:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4469:       if (flg) {
4470:         PetscConvEst conv;
4471:         DM           dm;
4472:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4473:         PetscInt     Nf;

4475:         incall = PETSC_TRUE;
4476:         SNESGetDM(snes, &dm);
4477:         DMGetNumFields(dm, &Nf);
4478:         PetscCalloc1(Nf, &alpha);
4479:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4480:         PetscConvEstSetSolver(conv, (PetscObject) snes);
4481:         PetscConvEstSetFromOptions(conv);
4482:         PetscConvEstSetUp(conv);
4483:         PetscConvEstGetConvRate(conv, alpha);
4484:         PetscViewerPushFormat(viewer, format);
4485:         PetscConvEstRateView(conv, alpha, viewer);
4486:         PetscViewerPopFormat(viewer);
4487:         PetscViewerDestroy(&viewer);
4488:         PetscConvEstDestroy(&conv);
4489:         PetscFree(alpha);
4490:         incall = PETSC_FALSE;
4491:       }
4492:       /* Adaptively refine the initial grid */
4493:       num  = 1;
4494:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);
4495:       if (flg) {
4496:         DMAdaptor adaptor;

4498:         incall = PETSC_TRUE;
4499:         DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor);
4500:         DMAdaptorSetSolver(adaptor, snes);
4501:         DMAdaptorSetSequenceLength(adaptor, num);
4502:         DMAdaptorSetFromOptions(adaptor);
4503:         DMAdaptorSetUp(adaptor);
4504:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4505:         DMAdaptorDestroy(&adaptor);
4506:         incall = PETSC_FALSE;
4507:       }
4508:       /* Use grid sequencing to adapt */
4509:       num  = 0;
4510:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4511:       if (num) {
4512:         DMAdaptor adaptor;

4514:         incall = PETSC_TRUE;
4515:         DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor);
4516:         DMAdaptorSetSolver(adaptor, snes);
4517:         DMAdaptorSetSequenceLength(adaptor, num);
4518:         DMAdaptorSetFromOptions(adaptor);
4519:         DMAdaptorSetUp(adaptor);
4520:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4521:         DMAdaptorDestroy(&adaptor);
4522:         incall = PETSC_FALSE;
4523:       }
4524:     }
4525:   }
4526:   if (!x) {
4527:     SNESGetDM(snes,&dm);
4528:     DMCreateGlobalVector(dm,&xcreated);
4529:     x    = xcreated;
4530:   }
4531:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4536:     /* set solution vector */
4537:     if (!grid) {PetscObjectReference((PetscObject)x);}
4538:     VecDestroy(&snes->vec_sol);
4539:     snes->vec_sol = x;
4540:     SNESGetDM(snes,&dm);

4542:     /* set affine vector if provided */
4543:     if (b) { PetscObjectReference((PetscObject)b); }
4544:     VecDestroy(&snes->vec_rhs);
4545:     snes->vec_rhs = b;

4547:     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");
4548:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4549:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4550:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4551:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4552:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4553:     }
4554:     DMShellSetGlobalVector(dm,snes->vec_sol);
4555:     SNESSetUp(snes);

4557:     if (!grid) {
4558:       if (snes->ops->computeinitialguess) {
4559:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4560:       }
4561:     }

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

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

4572:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4573:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

4575:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg);
4576:     if (flg && !PetscPreLoadingOn) { SNESTestLocalMin(snes); }
4577:     SNESConvergedReasonViewFromOptions(snes);

4579:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4580:     if (snes->reason < 0) break;
4581:     if (grid <  snes->gridsequence) {
4582:       DM  fine;
4583:       Vec xnew;
4584:       Mat interp;

4586:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4587:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4588:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4589:       DMCreateGlobalVector(fine,&xnew);
4590:       MatInterpolate(interp,x,xnew);
4591:       DMInterpolate(snes->dm,interp,fine);
4592:       MatDestroy(&interp);
4593:       x    = xnew;

4595:       SNESReset(snes);
4596:       SNESSetDM(snes,fine);
4597:       SNESResetFromOptions(snes);
4598:       DMDestroy(&fine);
4599:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4600:     }
4601:   }
4602:   SNESViewFromOptions(snes,NULL,"-snes_view");
4603:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");
4604:   DMMonitor(snes->dm);

4606:   VecDestroy(&xcreated);
4607:   PetscObjectSAWsBlock((PetscObject)snes);
4608:   return(0);
4609: }

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

4613: /*@C
4614:    SNESSetType - Sets the method for the nonlinear solver.

4616:    Collective on SNES

4618:    Input Parameters:
4619: +  snes - the SNES context
4620: -  type - a known method

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

4626:    Notes:
4627:    See "petsc/include/petscsnes.h" for available methods (for instance)
4628: +    SNESNEWTONLS - Newton's method with line search
4629:      (systems of nonlinear equations)
4630: -    SNESNEWTONTR - Newton's method with trust region
4631:      (systems of nonlinear equations)

4633:   Normally, it is best to use the SNESSetFromOptions() command and then
4634:   set the SNES solver type from the options database rather than by using
4635:   this routine.  Using the options database provides the user with
4636:   maximum flexibility in evaluating the many nonlinear solvers.
4637:   The SNESSetType() routine is provided for those situations where it
4638:   is necessary to set the nonlinear solver independently of the command
4639:   line or options database.  This might be the case, for example, when
4640:   the choice of solver changes during the execution of the program,
4641:   and the user's application is taking responsibility for choosing the
4642:   appropriate method.

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

4648:   Level: intermediate

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

4652: @*/
4653: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4654: {
4655:   PetscErrorCode ierr,(*r)(SNES);
4656:   PetscBool      match;


4662:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4663:   if (match) return(0);

4665:   PetscFunctionListFind(SNESList,type,&r);
4666:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4667:   /* Destroy the previous private SNES context */
4668:   if (snes->ops->destroy) {
4669:     (*(snes)->ops->destroy)(snes);
4670:     snes->ops->destroy = NULL;
4671:   }
4672:   /* Reinitialize function pointers in SNESOps structure */
4673:   snes->ops->setup          = NULL;
4674:   snes->ops->solve          = NULL;
4675:   snes->ops->view           = NULL;
4676:   snes->ops->setfromoptions = NULL;
4677:   snes->ops->destroy        = NULL;

4679:   /* It may happen the user has customized the line search before calling SNESSetType */
4680:   if (((PetscObject)snes)->type_name) {
4681:     SNESLineSearchDestroy(&snes->linesearch);
4682:   }

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

4687:   PetscObjectChangeTypeName((PetscObject)snes,type);
4688:   (*r)(snes);
4689:   return(0);
4690: }

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

4695:    Not Collective

4697:    Input Parameter:
4698: .  snes - nonlinear solver context

4700:    Output Parameter:
4701: .  type - SNES method (a character string)

4703:    Level: intermediate

4705: @*/
4706: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4707: {
4711:   *type = ((PetscObject)snes)->type_name;
4712:   return(0);
4713: }

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

4718:   Logically Collective on SNES

4720:   Input Parameters:
4721: + snes - the SNES context obtained from SNESCreate()
4722: - u    - the solution vector

4724:   Level: beginner

4726: @*/
4727: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4728: {
4729:   DM             dm;

4735:   PetscObjectReference((PetscObject) u);
4736:   VecDestroy(&snes->vec_sol);

4738:   snes->vec_sol = u;

4740:   SNESGetDM(snes, &dm);
4741:   DMShellSetGlobalVector(dm, u);
4742:   return(0);
4743: }

4745: /*@
4746:    SNESGetSolution - Returns the vector where the approximate solution is
4747:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

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

4754:    Output Parameter:
4755: .  x - the solution

4757:    Level: intermediate

4759: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4760: @*/
4761: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4762: {
4766:   *x = snes->vec_sol;
4767:   return(0);
4768: }

4770: /*@
4771:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4772:    stored.

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

4776:    Input Parameter:
4777: .  snes - the SNES context

4779:    Output Parameter:
4780: .  x - the solution update

4782:    Level: advanced

4784: .seealso: SNESGetSolution(), SNESGetFunction()
4785: @*/
4786: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4787: {
4791:   *x = snes->vec_sol_update;
4792:   return(0);
4793: }

4795: /*@C
4796:    SNESGetFunction - Returns the vector where the function is stored.

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

4800:    Input Parameter:
4801: .  snes - the SNES context

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

4808:    Level: advanced

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

4812: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4813: @*/
4814: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4815: {
4817:   DM             dm;

4821:   if (r) {
4822:     if (!snes->vec_func) {
4823:       if (snes->vec_rhs) {
4824:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4825:       } else if (snes->vec_sol) {
4826:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4827:       } else if (snes->dm) {
4828:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4829:       }
4830:     }
4831:     *r = snes->vec_func;
4832:   }
4833:   SNESGetDM(snes,&dm);
4834:   DMSNESGetFunction(dm,f,ctx);
4835:   return(0);
4836: }

4838: /*@C
4839:    SNESGetNGS - Returns the NGS function and context.

4841:    Input Parameter:
4842: .  snes - the SNES context

4844:    Output Parameter:
4845: +  f - the function (or NULL) see SNESNGSFunction for details
4846: -  ctx    - the function context (or NULL)

4848:    Level: advanced

4850: .seealso: SNESSetNGS(), SNESGetFunction()
4851: @*/

4853: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4854: {
4856:   DM             dm;

4860:   SNESGetDM(snes,&dm);
4861:   DMSNESGetNGS(dm,f,ctx);
4862:   return(0);
4863: }

4865: /*@C
4866:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4867:    SNES options in the database.

4869:    Logically Collective on SNES

4871:    Input Parameter:
4872: +  snes - the SNES context
4873: -  prefix - the prefix to prepend to all option names

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

4879:    Level: advanced

4881: .seealso: SNESSetFromOptions()
4882: @*/
4883: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4884: {

4889:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4890:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4891:   if (snes->linesearch) {
4892:     SNESGetLineSearch(snes,&snes->linesearch);
4893:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4894:   }
4895:   KSPSetOptionsPrefix(snes->ksp,prefix);
4896:   return(0);
4897: }

4899: /*@C
4900:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4901:    SNES options in the database.

4903:    Logically Collective on SNES

4905:    Input Parameters:
4906: +  snes - the SNES context
4907: -  prefix - the prefix to prepend to all option names

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

4913:    Level: advanced

4915: .seealso: SNESGetOptionsPrefix()
4916: @*/
4917: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4918: {

4923:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4924:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4925:   if (snes->linesearch) {
4926:     SNESGetLineSearch(snes,&snes->linesearch);
4927:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4928:   }
4929:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4930:   return(0);
4931: }

4933: /*@C
4934:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4935:    SNES options in the database.

4937:    Not Collective

4939:    Input Parameter:
4940: .  snes - the SNES context

4942:    Output Parameter:
4943: .  prefix - pointer to the prefix string used

4945:    Notes:
4946:     On the fortran side, the user should pass in a string 'prefix' of
4947:    sufficient length to hold the prefix.

4949:    Level: advanced

4951: .seealso: SNESAppendOptionsPrefix()
4952: @*/
4953: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4954: {

4959:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4960:   return(0);
4961: }


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

4967:    Not collective

4969:    Input Parameters:
4970: +  name_solver - name of a new user-defined solver
4971: -  routine_create - routine to create method context

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

4976:    Sample usage:
4977: .vb
4978:    SNESRegister("my_solver",MySolverCreate);
4979: .ve

4981:    Then, your solver can be chosen with the procedural interface via
4982: $     SNESSetType(snes,"my_solver")
4983:    or at runtime via the option
4984: $     -snes_type my_solver

4986:    Level: advanced

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

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

4992:   Level: advanced
4993: @*/
4994: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4995: {

4999:   SNESInitializePackage();
5000:   PetscFunctionListAdd(&SNESList,sname,function);
5001:   return(0);
5002: }

5004: PetscErrorCode  SNESTestLocalMin(SNES snes)
5005: {
5007:   PetscInt       N,i,j;
5008:   Vec            u,uh,fh;
5009:   PetscScalar    value;
5010:   PetscReal      norm;

5013:   SNESGetSolution(snes,&u);
5014:   VecDuplicate(u,&uh);
5015:   VecDuplicate(u,&fh);

5017:   /* currently only works for sequential */
5018:   PetscPrintf(PetscObjectComm((PetscObject)snes),"Testing FormFunction() for local min\n");
5019:   VecGetSize(u,&N);
5020:   for (i=0; i<N; i++) {
5021:     VecCopy(u,uh);
5022:     PetscPrintf(PetscObjectComm((PetscObject)snes),"i = %D\n",i);
5023:     for (j=-10; j<11; j++) {
5024:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
5025:       VecSetValue(uh,i,value,ADD_VALUES);
5026:       SNESComputeFunction(snes,uh,fh);
5027:       VecNorm(fh,NORM_2,&norm);
5028:       PetscPrintf(PetscObjectComm((PetscObject)snes),"       j norm %D %18.16e\n",j,norm);
5029:       value = -value;
5030:       VecSetValue(uh,i,value,ADD_VALUES);
5031:     }
5032:   }
5033:   VecDestroy(&uh);
5034:   VecDestroy(&fh);
5035:   return(0);
5036: }

5038: /*@
5039:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
5040:    computing relative tolerance for linear solvers within an inexact
5041:    Newton method.

5043:    Logically Collective on SNES

5045:    Input Parameters:
5046: +  snes - SNES context
5047: -  flag - PETSC_TRUE or PETSC_FALSE

5049:     Options Database:
5050: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
5051: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
5052: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
5053: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
5054: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
5055: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
5056: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
5057: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

5059:    Notes:
5060:    Currently, the default is to use a constant relative tolerance for
5061:    the inner linear solvers.  Alternatively, one can use the
5062:    Eisenstat-Walker method, where the relative convergence tolerance
5063:    is reset at each Newton iteration according progress of the nonlinear
5064:    solver.

5066:    Level: advanced

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

5072: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
5073: @*/
5074: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
5075: {
5079:   snes->ksp_ewconv = flag;
5080:   return(0);
5081: }

5083: /*@
5084:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
5085:    for computing relative tolerance for linear solvers within an
5086:    inexact Newton method.

5088:    Not Collective

5090:    Input Parameter:
5091: .  snes - SNES context

5093:    Output Parameter:
5094: .  flag - PETSC_TRUE or PETSC_FALSE

5096:    Notes:
5097:    Currently, the default is to use a constant relative tolerance for
5098:    the inner linear solvers.  Alternatively, one can use the
5099:    Eisenstat-Walker method, where the relative convergence tolerance
5100:    is reset at each Newton iteration according progress of the nonlinear
5101:    solver.

5103:    Level: advanced

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

5109: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
5110: @*/
5111: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
5112: {
5116:   *flag = snes->ksp_ewconv;
5117:   return(0);
5118: }

5120: /*@
5121:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5122:    convergence criteria for the linear solvers within an inexact
5123:    Newton method.

5125:    Logically Collective on SNES

5127:    Input Parameters:
5128: +    snes - SNES context
5129: .    version - version 1, 2 (default is 2) or 3
5130: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5131: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5132: .    gamma - multiplicative factor for version 2 rtol computation
5133:              (0 <= gamma2 <= 1)
5134: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5135: .    alpha2 - power for safeguard
5136: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5138:    Note:
5139:    Version 3 was contributed by Luis Chacon, June 2006.

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

5143:    Level: advanced

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

5150: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
5151: @*/
5152: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
5153: {
5154:   SNESKSPEW *kctx;

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

5168:   if (version != PETSC_DEFAULT)   kctx->version   = version;
5169:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
5170:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
5171:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
5172:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
5173:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
5174:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

5176:   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);
5177:   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);
5178:   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);
5179:   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);
5180:   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);
5181:   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);
5182:   return(0);
5183: }

5185: /*@
5186:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5187:    convergence criteria for the linear solvers within an inexact
5188:    Newton method.

5190:    Not Collective

5192:    Input Parameters:
5193:      snes - SNES context

5195:    Output Parameters:
5196: +    version - version 1, 2 (default is 2) or 3
5197: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5198: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5199: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5200: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5201: .    alpha2 - power for safeguard
5202: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5204:    Level: advanced

5206: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
5207: @*/
5208: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
5209: {
5210:   SNESKSPEW *kctx;

5214:   kctx = (SNESKSPEW*)snes->kspconvctx;
5215:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5216:   if (version)   *version   = kctx->version;
5217:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
5218:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
5219:   if (gamma)     *gamma     = kctx->gamma;
5220:   if (alpha)     *alpha     = kctx->alpha;
5221:   if (alpha2)    *alpha2    = kctx->alpha2;
5222:   if (threshold) *threshold = kctx->threshold;
5223:   return(0);
5224: }

5226:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5227: {
5229:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5230:   PetscReal      rtol  = PETSC_DEFAULT,stol;

5233:   if (!snes->ksp_ewconv) return(0);
5234:   if (!snes->iter) {
5235:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5236:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
5237:   }
5238:   else {
5239:     if (kctx->version == 1) {
5240:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
5241:       if (rtol < 0.0) rtol = -rtol;
5242:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5243:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5244:     } else if (kctx->version == 2) {
5245:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5246:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5247:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5248:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5249:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5250:       /* safeguard: avoid sharp decrease of rtol */
5251:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5252:       stol = PetscMax(rtol,stol);
5253:       rtol = PetscMin(kctx->rtol_0,stol);
5254:       /* safeguard: avoid oversolving */
5255:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5256:       stol = PetscMax(rtol,stol);
5257:       rtol = PetscMin(kctx->rtol_0,stol);
5258:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
5259:   }
5260:   /* safeguard: avoid rtol greater than one */
5261:   rtol = PetscMin(rtol,kctx->rtol_max);
5262:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
5263:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
5264:   return(0);
5265: }

5267: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5268: {
5270:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5271:   PCSide         pcside;
5272:   Vec            lres;

5275:   if (!snes->ksp_ewconv) return(0);
5276:   KSPGetTolerances(ksp,&kctx->rtol_last,NULL,NULL,NULL);
5277:   kctx->norm_last = snes->norm;
5278:   if (kctx->version == 1) {
5279:     PC        pc;
5280:     PetscBool isNone;

5282:     KSPGetPC(ksp, &pc);
5283:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
5284:     KSPGetPCSide(ksp,&pcside);
5285:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
5286:       /* KSP residual is true linear residual */
5287:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
5288:     } else {
5289:       /* KSP residual is preconditioned residual */
5290:       /* compute true linear residual norm */
5291:       VecDuplicate(b,&lres);
5292:       MatMult(snes->jacobian,x,lres);
5293:       VecAYPX(lres,-1.0,b);
5294:       VecNorm(lres,NORM_2,&kctx->lresid_last);
5295:       VecDestroy(&lres);
5296:     }
5297:   }
5298:   return(0);
5299: }

5301: /*@
5302:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

5306:    Input Parameter:
5307: .  snes - the SNES context

5309:    Output Parameter:
5310: .  ksp - the KSP context

5312:    Notes:
5313:    The user can then directly manipulate the KSP context to set various
5314:    options, etc.  Likewise, the user can then extract and manipulate the
5315:    PC contexts as well.

5317:    Level: beginner

5319: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5320: @*/
5321: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
5322: {


5329:   if (!snes->ksp) {
5330:     PetscBool monitor = PETSC_FALSE;

5332:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
5333:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
5334:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

5339:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
5340:     if (monitor) {
5341:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
5342:     }
5343:     monitor = PETSC_FALSE;
5344:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
5345:     if (monitor) {
5346:       PetscObject *objs;
5347:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
5348:       objs[0] = (PetscObject) snes;
5349:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
5350:     }
5351:     PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options);
5352:   }
5353:   *ksp = snes->ksp;
5354:   return(0);
5355: }


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

5362:    Logically Collective on SNES

5364:    Input Parameters:
5365: +  snes - the nonlinear solver context
5366: -  dm - the dm, cannot be NULL

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

5373:    Level: intermediate

5375: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
5376: @*/
5377: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5378: {
5380:   KSP            ksp;
5381:   DMSNES         sdm;

5386:   PetscObjectReference((PetscObject)dm);
5387:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5388:     if (snes->dm->dmsnes && !dm->dmsnes) {
5389:       DMCopyDMSNES(snes->dm,dm);
5390:       DMGetDMSNES(snes->dm,&sdm);
5391:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5392:     }
5393:     DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5394:     DMDestroy(&snes->dm);
5395:   }
5396:   snes->dm     = dm;
5397:   snes->dmAuto = PETSC_FALSE;

5399:   SNESGetKSP(snes,&ksp);
5400:   KSPSetDM(ksp,dm);
5401:   KSPSetDMActive(ksp,PETSC_FALSE);
5402:   if (snes->npc) {
5403:     SNESSetDM(snes->npc, snes->dm);
5404:     SNESSetNPCSide(snes,snes->npcside);
5405:   }
5406:   return(0);
5407: }

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

5412:    Not Collective but DM obtained is parallel on SNES

5414:    Input Parameter:
5415: . snes - the preconditioner context

5417:    Output Parameter:
5418: .  dm - the dm

5420:    Level: intermediate

5422: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5423: @*/
5424: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5425: {

5430:   if (!snes->dm) {
5431:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5432:     snes->dmAuto = PETSC_TRUE;
5433:   }
5434:   *dm = snes->dm;
5435:   return(0);
5436: }

5438: /*@
5439:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5441:   Collective on SNES

5443:   Input Parameters:
5444: + snes - iterative context obtained from SNESCreate()
5445: - pc   - the preconditioner object

5447:   Notes:
5448:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5449:   to configure it using the API).

5451:   Level: developer

5453: .seealso: SNESGetNPC(), SNESHasNPC()
5454: @*/
5455: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5456: {

5463:   PetscObjectReference((PetscObject) pc);
5464:   SNESDestroy(&snes->npc);
5465:   snes->npc = pc;
5466:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5467:   return(0);
5468: }

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

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

5475:   Input Parameter:
5476: . snes - iterative context obtained from SNESCreate()

5478:   Output Parameter:
5479: . pc - preconditioner context

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

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

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

5490:   Level: developer

5492: .seealso: SNESSetNPC(), SNESHasNPC(), SNES, SNESCreate()
5493: @*/
5494: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5495: {
5497:   const char     *optionsprefix;

5502:   if (!snes->npc) {
5503:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5504:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5505:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5506:     SNESGetOptionsPrefix(snes,&optionsprefix);
5507:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5508:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5509:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5510:   }
5511:   *pc = snes->npc;
5512:   return(0);
5513: }

5515: /*@
5516:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5518:   Not Collective

5520:   Input Parameter:
5521: . snes - iterative context obtained from SNESCreate()

5523:   Output Parameter:
5524: . has_npc - whether the SNES has an NPC or not

5526:   Level: developer

5528: .seealso: SNESSetNPC(), SNESGetNPC()
5529: @*/
5530: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5531: {
5534:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5535:   return(0);
5536: }

5538: /*@
5539:     SNESSetNPCSide - Sets the preconditioning side.

5541:     Logically Collective on SNES

5543:     Input Parameter:
5544: .   snes - iterative context obtained from SNESCreate()

5546:     Output Parameter:
5547: .   side - the preconditioning side, where side is one of
5548: .vb
5549:       PC_LEFT - left preconditioning
5550:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5551: .ve

5553:     Options Database Keys:
5554: .   -snes_pc_side <right,left>

5556:     Notes:
5557:     SNESNRICHARDSON and SNESNCG only support left preconditioning.

5559:     Level: intermediate

5561: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5562: @*/
5563: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5564: {
5568:   snes->npcside= side;
5569:   return(0);
5570: }

5572: /*@
5573:     SNESGetNPCSide - Gets the preconditioning side.

5575:     Not Collective

5577:     Input Parameter:
5578: .   snes - iterative context obtained from SNESCreate()

5580:     Output Parameter:
5581: .   side - the preconditioning side, where side is one of
5582: .vb
5583:       PC_LEFT - left preconditioning
5584:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5585: .ve

5587:     Level: intermediate

5589: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5590: @*/
5591: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5592: {
5596:   *side = snes->npcside;
5597:   return(0);
5598: }

5600: /*@
5601:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5603:   Collective on SNES

5605:   Input Parameters:
5606: + snes - iterative context obtained from SNESCreate()
5607: - linesearch   - the linesearch object

5609:   Notes:
5610:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5611:   to configure it using the API).

5613:   Level: developer

5615: .seealso: SNESGetLineSearch()
5616: @*/
5617: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5618: {

5625:   PetscObjectReference((PetscObject) linesearch);
5626:   SNESLineSearchDestroy(&snes->linesearch);

5628:   snes->linesearch = linesearch;

5630:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5631:   return(0);
5632: }

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

5638:   Not Collective

5640:   Input Parameter:
5641: . snes - iterative context obtained from SNESCreate()

5643:   Output Parameter:
5644: . linesearch - linesearch context

5646:   Level: beginner

5648: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5649: @*/
5650: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5651: {
5653:   const char     *optionsprefix;

5658:   if (!snes->linesearch) {
5659:     SNESGetOptionsPrefix(snes, &optionsprefix);
5660:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5661:     SNESLineSearchSetSNES(snes->linesearch, snes);
5662:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5663:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5664:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5665:   }
5666:   *linesearch = snes->linesearch;
5667:   return(0);
5668: }