Actual source code: snes.c

  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 available formats include
357: +     PETSC_VIEWER_DEFAULT - standard output (default)
358: -     PETSC_VIEWER_ASCII_INFO_DETAIL - more verbose output for SNESNASM

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

363:   In the debugger you can do "call SNESView(snes,0)" to display the SNES solver. (The same holds for any PETSc object viewer).

365:    Level: beginner

367: .seealso: PetscViewerASCIIOpen()
368: @*/
369: PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
370: {
371:   SNESKSPEW      *kctx;
373:   KSP            ksp;
374:   SNESLineSearch linesearch;
375:   PetscBool      iascii,isstring,isbinary,isdraw;
376:   DMSNES         dmsnes;
377: #if defined(PETSC_HAVE_SAWS)
378:   PetscBool      issaws;
379: #endif

383:   if (!viewer) {
384:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer);
385:   }

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

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

474:     PetscObjectGetComm((PetscObject)snes,&comm);
475:     MPI_Comm_rank(comm,&rank);
476:     if (rank == 0) {
477:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
478:       PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));
479:       PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR);
480:     }
481:     if (snes->ops->view) {
482:       (*snes->ops->view)(snes,viewer);
483:     }
484:   } else if (isdraw) {
485:     PetscDraw draw;
486:     char      str[36];
487:     PetscReal x,y,bottom,h;

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

504:     PetscObjectGetName((PetscObject)snes,&name);
505:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
506:     if (!((PetscObject)snes)->amsmem && rank == 0) {
507:       char       dir[1024];

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

549: /*
550:   We retain a list of functions that also take SNES command
551:   line options. These are called at the end SNESSetFromOptions()
552: */
553: #define MAXSETFROMOPTIONS 5
554: static PetscInt numberofsetfromoptions;
555: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);

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

560:   Not Collective

562:   Input Parameter:
563: . snescheck - function that checks for options

565:   Level: developer

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

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

579: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
580: {
581:   Mat            J;
583:   MatNullSpace   nullsp;


588:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
589:     Mat A = snes->jacobian, B = snes->jacobian_pre;
590:     MatCreateVecs(A ? A : B, NULL,&snes->vec_func);
591:   }

593:   if (version == 1) {
594:     MatCreateSNESMF(snes,&J);
595:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
596:     MatSetFromOptions(J);
597:   } else if (version == 2) {
598:     if (!snes->vec_func) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
599: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
600:     SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J);
601: #else
602:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator routines (version 2)");
603: #endif
604:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator routines, only version 1 and 2");

606:   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
607:   if (snes->jacobian) {
608:     MatGetNullSpace(snes->jacobian,&nullsp);
609:     if (nullsp) {
610:       MatSetNullSpace(J,nullsp);
611:     }
612:   }

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

617:     /* This version replaces the user provided Jacobian matrix with a
618:        matrix-free version but still employs the user-provided preconditioner matrix. */
619:     SNESSetJacobian(snes,J,NULL,NULL,NULL);
620:   } else {
621:     /* This version replaces both the user-provided Jacobian and the user-
622:      provided preconditioner Jacobian with the default matrix free version. */
623:     if ((snes->npcside== PC_LEFT) && snes->npc) {
624:       if (!snes->jacobian) {SNESSetJacobian(snes,J,NULL,NULL,NULL);}
625:     } else {
626:       KSP       ksp;
627:       PC        pc;
628:       PetscBool match;

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

645: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
646: {
647:   SNES           snes = (SNES)ctx;
649:   Vec            Xfine,Xfine_named = NULL,Xcoarse;

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

677: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
678: {

682:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
683:   return(0);
684: }

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

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

714:     DMGetDMSNES(snes->dm, &sdm);
715:     if (!sdm->ops->computejacobian) {
716:       DMCopyDMSNES(dmsave, snes->dm);
717:     }
718:   }
719:   /* Compute the operators */
720:   SNESComputeJacobian(snes,X,A,B);
721:   /* Put the previous context back */
722:   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
723:     SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);
724:   }

726:   if (Xnamed) {DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);}
727:   snes->dm = dmsave;
728:   return(0);
729: }

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

734:    Collective

736:    Input Parameter:
737: .  snes - snes to configure

739:    Level: developer

741: .seealso: SNESSetUp()
742: @*/
743: PetscErrorCode SNESSetUpMatrices(SNES snes)
744: {
746:   DM             dm;
747:   DMSNES         sdm;

750:   SNESGetDM(snes,&dm);
751:   DMGetDMSNES(dm,&sdm);
752:   if (!snes->jacobian && snes->mf) {
753:     Mat  J;
754:     void *functx;
755:     MatCreateSNESMF(snes,&J);
756:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
757:     MatSetFromOptions(J);
758:     SNESGetFunction(snes,NULL,NULL,&functx);
759:     SNESSetJacobian(snes,J,J,NULL,NULL);
760:     MatDestroy(&J);
761:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
762:     Mat J,B;
763:     MatCreateSNESMF(snes,&J);
764:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
765:     MatSetFromOptions(J);
766:     DMCreateMatrix(snes->dm,&B);
767:     /* sdm->computejacobian was already set to reach here */
768:     SNESSetJacobian(snes,J,B,NULL,NULL);
769:     MatDestroy(&J);
770:     MatDestroy(&B);
771:   } else if (!snes->jacobian_pre) {
772:     PetscDS   prob;
773:     Mat       J, B;
774:     PetscBool hasPrec   = PETSC_FALSE;

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

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

798:    Collective on SNES

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

808:    Level: developer

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

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

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

842:    Collective on SNES

844:    Input Parameter:
845: .  snes - the SNES context

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

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 explicitly 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","correct_pressure"};
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,sizeof(convtests)/sizeof(char*),"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:     case 2: SNESSetConvergenceTest(snes,SNESConvergedCorrectPressure,NULL,NULL); break;
969:     }
970:   }

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

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

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

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

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

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

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

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

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

1009:   flg  = PETSC_FALSE;
1010:   PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);
1011:   if (flg) {
1012:     PetscViewer ctx;

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

1018:   flg  = PETSC_FALSE;
1019:   PetscOptionsBool("-snes_converged_reason_view_cancel","Remove all converged reason viewers","SNESConvergedReasonViewCancel",flg,&flg,&set);
1020:   if (set && flg) {SNESConvergedReasonViewCancel(snes);}

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

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

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

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

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

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

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

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

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

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

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

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

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

1132:    Collective on SNES

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

1137:    Level: beginner

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

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

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

1154:    Logically Collective on SNES

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

1161:    Level: intermediate

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

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

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

1181:    Logically Collective on SNES

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

1187:    Level: intermediate

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

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

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

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

1212:    Not Collective

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

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

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

1224:    Level: intermediate

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

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

1239:    Collective on SNES

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

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

1252:    Level: intermediate

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

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

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

1274:    Collective on SNES

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

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

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

1287:    Level: intermediate

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

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

1304:    Not Collective

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

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

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

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

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

1328:    Level: intermediate

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

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

1344:    Not Collective

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

1350:    Level: developer

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

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

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

1370:    Not Collective

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

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

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

1381:    Level: intermediate

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

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

1399:    Not Collective

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

1405:    Level: intermediate

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

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

1422:    Not Collective

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

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

1430:    Level: intermediate

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

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

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

1449:    Not Collective

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

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

1457:    Level: intermediate

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

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

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

1477:    Not Collective

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

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

1485:    Level: intermediate

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

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

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

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

1508:    Logically Collective on SNES

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

1514:    Level: intermediate

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

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

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

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

1537:    Not Collective

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

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

1545:    Level: intermediate

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

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

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

1565:    Not Collective

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

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

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

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

1579:    Level: intermediate

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

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

1596:    Logically Collective on SNES

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

1602:    Notes:
1603:    This defaults to PETSC_TRUE

1605:    Level: developer

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

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

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

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

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

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

1634:    Level: developer

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

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

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

1656:    Collective

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

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

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

1672:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

1792:   *outsnes = snes;
1793:   return(0);
1794: }

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

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

1803:      Collective on snes

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

1810:      Output Parameter:
1811: .     f  - vector to put residual (function value)

1813:    Level: intermediate

1815: .seealso:   SNESSetFunction(), SNESGetFunction()
1816: M*/

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

1823:    Logically Collective on SNES

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

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

1837:    Level: beginner

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

1848:   if (r) {
1851:     PetscObjectReference((PetscObject)r);
1852:     VecDestroy(&snes->vec_func);
1853:     snes->vec_func = r;
1854:   }
1855:   SNESGetDM(snes,&dm);
1856:   DMSNESSetFunction(dm,f,ctx);
1857:   if (f == SNESPicardComputeFunction) {
1858:     DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx);
1859:   }
1860:   return(0);
1861: }

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

1870:    Logically Collective on SNES

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

1876:    Notes:
1877:    This should not be modified during the solution procedure.

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

1881:    Level: developer

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

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

1901:   snes->vec_func_init_set = PETSC_TRUE;
1902:   return(0);
1903: }

1905: /*@
1906:    SNESSetNormSchedule - Sets the SNESNormSchedule used in convergence and monitoring
1907:    of the SNES method.

1909:    Logically Collective on SNES

1911:    Input Parameters:
1912: +  snes - the SNES context
1913: -  normschedule - the frequency of norm computation

1915:    Options Database Key:
1916: .  -snes_norm_schedule <none, always, initialonly, finalonly, initialfinalonly>

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

1927:    Level: developer

1929: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1930: @*/
1931: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1932: {
1935:   snes->normschedule = normschedule;
1936:   return(0);
1937: }

1939: /*@
1940:    SNESGetNormSchedule - Gets the SNESNormSchedule used in convergence and monitoring
1941:    of the SNES method.

1943:    Logically Collective on SNES

1945:    Input Parameters:
1946: +  snes - the SNES context
1947: -  normschedule - the type of the norm used

1949:    Level: advanced

1951: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1952: @*/
1953: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1954: {
1957:   *normschedule = snes->normschedule;
1958:   return(0);
1959: }

1961: /*@
1962:   SNESSetFunctionNorm - Sets the last computed residual norm.

1964:   Logically Collective on SNES

1966:   Input Parameters:
1967: + snes - the SNES context

1969: - normschedule - the frequency of norm computation

1971:   Level: developer

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

1983: /*@
1984:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1986:   Not Collective

1988:   Input Parameter:
1989: . snes - the SNES context

1991:   Output Parameter:
1992: . norm - the last computed residual norm

1994:   Level: developer

1996: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1997: @*/
1998: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1999: {
2003:   *norm = snes->norm;
2004:   return(0);
2005: }

2007: /*@
2008:   SNESGetUpdateNorm - Gets the last computed norm of the Newton update

2010:   Not Collective

2012:   Input Parameter:
2013: . snes - the SNES context

2015:   Output Parameter:
2016: . ynorm - the last computed update norm

2018:   Level: developer

2020: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm()
2021: @*/
2022: PetscErrorCode SNESGetUpdateNorm(SNES snes, PetscReal *ynorm)
2023: {
2027:   *ynorm = snes->ynorm;
2028:   return(0);
2029: }

2031: /*@
2032:   SNESGetSolutionNorm - Gets the last computed norm of the solution

2034:   Not Collective

2036:   Input Parameter:
2037: . snes - the SNES context

2039:   Output Parameter:
2040: . xnorm - the last computed solution norm

2042:   Level: developer

2044: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), SNESGetFunctionNorm(), SNESGetUpdateNorm()
2045: @*/
2046: PetscErrorCode SNESGetSolutionNorm(SNES snes, PetscReal *xnorm)
2047: {
2051:   *xnorm = snes->xnorm;
2052:   return(0);
2053: }

2055: /*@C
2056:    SNESSetFunctionType - Sets the SNESNormSchedule used in convergence and monitoring
2057:    of the SNES method.

2059:    Logically Collective on SNES

2061:    Input Parameters:
2062: +  snes - the SNES context
2063: -  normschedule - the frequency of norm computation

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

2074:    Level: developer

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

2086: /*@C
2087:    SNESGetFunctionType - Gets the SNESNormSchedule used in convergence and monitoring
2088:    of the SNES method.

2090:    Logically Collective on SNES

2092:    Input Parameters:
2093: +  snes - the SNES context
2094: -  normschedule - the type of the norm used

2096:    Level: advanced

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

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

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

2115:      Collective on snes

2117:      Input Parameters:
2118: +  X   - solution vector
2119: .  B   - RHS vector
2120: -  ctx - optional user-defined Gauss-Seidel context

2122:      Output Parameter:
2123: .  X   - solution vector

2125:    Level: intermediate

2127: .seealso:   SNESSetNGS(), SNESGetNGS()
2128: M*/

2130: /*@C
2131:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
2132:    use with composed nonlinear solvers.

2134:    Input Parameters:
2135: +  snes   - the SNES context
2136: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
2137: -  ctx    - [optional] user-defined context for private data for the
2138:             smoother evaluation routine (may be NULL)

2140:    Notes:
2141:    The NGS routines are used by the composed nonlinear solver to generate
2142:     a problem appropriate update to the solution, particularly FAS.

2144:    Level: intermediate

2146: .seealso: SNESGetFunction(), SNESComputeNGS()
2147: @*/
2148: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
2149: {
2151:   DM             dm;

2155:   SNESGetDM(snes,&dm);
2156:   DMSNESSetNGS(dm,f,ctx);
2157:   return(0);
2158: }

2160: /*
2161:      This is used for -snes_mf_operator; it uses a duplicate of snes->jacobian_pre because snes->jacobian_pre cannot be
2162:    changed during the KSPSolve()
2163: */
2164: PetscErrorCode SNESPicardComputeMFFunction(SNES snes,Vec x,Vec f,void *ctx)
2165: {
2167:   DM             dm;
2168:   DMSNES         sdm;

2171:   SNESGetDM(snes,&dm);
2172:   DMGetDMSNES(dm,&sdm);
2173:   if (!sdm->ops->computepjacobian) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2174:   /*  A(x)*x - b(x) */
2175:   if (sdm->ops->computepfunction) {
2176:     PetscStackPush("SNES Picard user function");
2177:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
2178:     PetscStackPop;
2179:     VecScale(f,-1.0);
2180:     if (!snes->picard) {
2181:       /* Cannot share nonzero pattern because of the possible use of SNESComputeJacobianDefault() */
2182:       MatDuplicate(snes->jacobian_pre,MAT_DO_NOT_COPY_VALUES,&snes->picard);
2183:     }
2184:     PetscStackPush("SNES Picard user Jacobian");
2185:     (*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx);
2186:     PetscStackPop;
2187:     MatMultAdd(snes->picard,x,f,f);
2188:   } else {
2189:     PetscStackPush("SNES Picard user Jacobian");
2190:     (*sdm->ops->computepjacobian)(snes,x,snes->picard,snes->picard,sdm->pctx);
2191:     PetscStackPop;
2192:     MatMult(snes->picard,x,f);
2193:   }
2194:   return(0);
2195: }

2197: PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
2198: {
2200:   DM             dm;
2201:   DMSNES         sdm;

2204:   SNESGetDM(snes,&dm);
2205:   DMGetDMSNES(dm,&sdm);
2206:   if (!sdm->ops->computepjacobian) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2207:   /*  A(x)*x - b(x) */
2208:   if (sdm->ops->computepfunction) {
2209:     PetscStackPush("SNES Picard user function");
2210:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
2211:     PetscStackPop;
2212:     VecScale(f,-1.0);
2213:     PetscStackPush("SNES Picard user Jacobian");
2214:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
2215:     PetscStackPop;
2216:     MatMultAdd(snes->jacobian_pre,x,f,f);
2217:   } else {
2218:     PetscStackPush("SNES Picard user Jacobian");
2219:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
2220:     PetscStackPop;
2221:     MatMult(snes->jacobian_pre,x,f);
2222:   }
2223:   return(0);
2224: }

2226: PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
2227: {
2230:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2231:   /* must assembly if matrix-free to get the last SNES solution */
2232:   MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
2233:   MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
2234:   return(0);
2235: }

2237: /*@C
2238:    SNESSetPicard - Use SNES to solve the system A(x) x = bp(x) + b via a Picard type iteration (Picard linearization)

2240:    Logically Collective on SNES

2242:    Input Parameters:
2243: +  snes - the SNES context
2244: .  r - vector to store function values, may be NULL
2245: .  bp - function evaluation routine, may be NULL
2246: .  Amat - matrix with which A(x) x - bp(x) - b is to be computed
2247: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2248: .  J  - function to compute matrix values, see SNESJacobianFunction() for details on its calling sequence
2249: -  ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)

2251:    Notes:
2252:     It is often better to provide the nonlinear function F() and some approximation to its Jacobian directly and use
2253:     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.

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

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

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

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

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

2269:    When used with -snes_mf_operator this will run matrix-free Newton's method where the matrix-vector product is of the true Jacobian of A(x)x - bp(x) -b.

2271:    When used with -snes_fd this will compute the true Jacobian (very slowly one column at at time) and thus represent Newton's method.

2273:    When used with -snes_fd_coloring this will compute the Jacobian via coloring and thus represent a faster implementation of Newton's method. But the
2274:    the nonzero structure of the Jacobian is, in general larger than that of the Picard matrix A so you must provide in A the needed nonzero structure for the correct
2275:    coloring. When using DMDA this may mean creating the matrix A with DMCreateMatrix() using a wider stencil than strictly needed for A or with a DMDA_STENCIL_BOX.
2276:    See the commment in src/snes/tutorials/ex15.c.

2278:    Level: intermediate

2280: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2281: @*/
2282: PetscErrorCode  SNESSetPicard(SNES snes,Vec r,PetscErrorCode (*bp)(SNES,Vec,Vec,void*),Mat Amat, Mat Pmat, PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2283: {
2285:   DM             dm;

2289:   SNESGetDM(snes, &dm);
2290:   DMSNESSetPicard(dm,bp,J,ctx);
2291:   DMSNESSetMFFunction(dm,SNESPicardComputeMFFunction,ctx);
2292:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2293:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2294:   return(0);
2295: }

2297: /*@C
2298:    SNESGetPicard - Returns the context for the Picard iteration

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

2302:    Input Parameter:
2303: .  snes - the SNES context

2305:    Output Parameters:
2306: +  r - the function (or NULL)
2307: .  f - the function (or NULL); see SNESFunction for calling sequence details
2308: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2309: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2310: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2311: -  ctx - the function context (or NULL)

2313:    Level: advanced

2315: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2316: @*/
2317: 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)
2318: {
2320:   DM             dm;

2324:   SNESGetFunction(snes,r,NULL,NULL);
2325:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2326:   SNESGetDM(snes,&dm);
2327:   DMSNESGetPicard(dm,f,J,ctx);
2328:   return(0);
2329: }

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

2334:    Logically Collective on SNES

2336:    Input Parameters:
2337: +  snes - the SNES context
2338: .  func - function evaluation routine
2339: -  ctx - [optional] user-defined context for private data for the
2340:          function evaluation routine (may be NULL)

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

2345: .  f - function vector
2346: -  ctx - optional user-defined function context

2348:    Level: intermediate

2350: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2351: @*/
2352: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2353: {
2356:   if (func) snes->ops->computeinitialguess = func;
2357:   if (ctx)  snes->initialguessP            = ctx;
2358:   return(0);
2359: }

2361: /* --------------------------------------------------------------- */
2362: /*@C
2363:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2364:    it assumes a zero right hand side.

2366:    Logically Collective on SNES

2368:    Input Parameter:
2369: .  snes - the SNES context

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

2374:    Level: intermediate

2376: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2377: @*/
2378: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2379: {
2383:   *rhs = snes->vec_rhs;
2384:   return(0);
2385: }

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

2390:    Collective on SNES

2392:    Input Parameters:
2393: +  snes - the SNES context
2394: -  x - input vector

2396:    Output Parameter:
2397: .  y - function vector, as set by SNESSetFunction()

2399:    Notes:
2400:    SNESComputeFunction() is typically used within nonlinear solvers
2401:    implementations, so users would not generally call this routine themselves.

2403:    Level: developer

2405: .seealso: SNESSetFunction(), SNESGetFunction(), SNESComputeMFFunction()
2406: @*/
2407: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2408: {
2410:   DM             dm;
2411:   DMSNES         sdm;

2419:   VecValidValues(x,2,PETSC_TRUE);

2421:   SNESGetDM(snes,&dm);
2422:   DMGetDMSNES(dm,&sdm);
2423:   if (sdm->ops->computefunction) {
2424:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2425:       PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2426:     }
2427:     VecLockReadPush(x);
2428:     PetscStackPush("SNES user function");
2429:     /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2430:     snes->domainerror = PETSC_FALSE;
2431:     (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);
2432:     PetscStackPop;
2433:     VecLockReadPop(x);
2434:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2435:       PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2436:     }
2437:   } else if (snes->vec_rhs) {
2438:     MatMult(snes->jacobian, x, y);
2439:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2440:   if (snes->vec_rhs) {
2441:     VecAXPY(y,-1.0,snes->vec_rhs);
2442:   }
2443:   snes->nfuncs++;
2444:   /*
2445:      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2446:      propagate the value to all processes
2447:   */
2448:   if (snes->domainerror) {
2449:     VecSetInf(y);
2450:   }
2451:   return(0);
2452: }

2454: /*@
2455:    SNESComputeMFFunction - Calls the function that has been set with SNESSetMFFunction().

2457:    Collective on SNES

2459:    Input Parameters:
2460: +  snes - the SNES context
2461: -  x - input vector

2463:    Output Parameter:
2464: .  y - function vector, as set by SNESSetMFFunction()

2466:    Notes:
2467:        SNESComputeMFFunction() is used within the matrix vector products called by the matrix created with MatCreateSNESMF()
2468:    so users would not generally call this routine themselves.

2470:        Since this function is intended for use with finite differencing it does not subtract the right hand side vector provided with SNESSolve()
2471:     while SNESComputeFunction() does. As such, this routine cannot be used with  MatMFFDSetBase() with a provided F function value even if it applies the
2472:     same function as SNESComputeFunction() if a SNESSolve() right hand side vector is use because the two functions difference would include this right hand side function.

2474:    Level: developer

2476: .seealso: SNESSetFunction(), SNESGetFunction(), SNESComputeFunction(), MatCreateSNESMF
2477: @*/
2478: PetscErrorCode  SNESComputeMFFunction(SNES snes,Vec x,Vec y)
2479: {
2481:   DM             dm;
2482:   DMSNES         sdm;

2490:   VecValidValues(x,2,PETSC_TRUE);

2492:   SNESGetDM(snes,&dm);
2493:   DMGetDMSNES(dm,&sdm);
2494:   PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2495:   VecLockReadPush(x);
2496:   PetscStackPush("SNES user function");
2497:   /* ensure domainerror is false prior to computefunction evaluation (may not have been reset) */
2498:   snes->domainerror = PETSC_FALSE;
2499:   (*sdm->ops->computemffunction)(snes,x,y,sdm->mffunctionctx);
2500:   PetscStackPop;
2501:   VecLockReadPop(x);
2502:   PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2503:   snes->nfuncs++;
2504:   /*
2505:      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2506:      propagate the value to all processes
2507:   */
2508:   if (snes->domainerror) {
2509:     VecSetInf(y);
2510:   }
2511:   return(0);
2512: }

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

2517:    Collective on SNES

2519:    Input Parameters:
2520: +  snes - the SNES context
2521: .  x - input vector
2522: -  b - rhs vector

2524:    Output Parameter:
2525: .  x - new solution vector

2527:    Notes:
2528:    SNESComputeNGS() is typically used within composed nonlinear solver
2529:    implementations, so most users would not generally call this routine
2530:    themselves.

2532:    Level: developer

2534: .seealso: SNESSetNGS(), SNESComputeFunction()
2535: @*/
2536: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2537: {
2539:   DM             dm;
2540:   DMSNES         sdm;

2548:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2549:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2550:   SNESGetDM(snes,&dm);
2551:   DMGetDMSNES(dm,&sdm);
2552:   if (sdm->ops->computegs) {
2553:     if (b) {VecLockReadPush(b);}
2554:     PetscStackPush("SNES user NGS");
2555:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2556:     PetscStackPop;
2557:     if (b) {VecLockReadPop(b);}
2558:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2559:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2560:   return(0);
2561: }

2563: PetscErrorCode SNESTestJacobian(SNES snes)
2564: {
2565:   Mat               A,B,C,D,jacobian;
2566:   Vec               x = snes->vec_sol,f = snes->vec_func;
2567:   PetscErrorCode    ierr;
2568:   PetscReal         nrm,gnorm;
2569:   PetscReal         threshold = 1.e-5;
2570:   MatType           mattype;
2571:   PetscInt          m,n,M,N;
2572:   void              *functx;
2573:   PetscBool         complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg,istranspose;
2574:   PetscViewer       viewer,mviewer;
2575:   MPI_Comm          comm;
2576:   PetscInt          tabs;
2577:   static PetscBool  directionsprinted = PETSC_FALSE;
2578:   PetscViewerFormat format;

2581:   PetscObjectOptionsBegin((PetscObject)snes);
2582:   PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test);
2583:   PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL);
2584:   PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print);
2585:   if (!complete_print) {
2586:     PetscOptionsDeprecated("-snes_test_jacobian_display","-snes_test_jacobian_view","3.13",NULL);
2587:     PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print);
2588:   }
2589:   /* for compatibility with PETSc 3.9 and older. */
2590:   PetscOptionsDeprecated("-snes_test_jacobian_display_threshold","-snes_test_jacobian","3.13","-snes_test_jacobian accepts an optional threshold (since v3.10)");
2591:   PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print);
2592:   PetscOptionsEnd();
2593:   if (!test) return(0);

2595:   PetscObjectGetComm((PetscObject)snes,&comm);
2596:   PetscViewerASCIIGetStdout(comm,&viewer);
2597:   PetscViewerASCIIGetTab(viewer, &tabs);
2598:   PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);
2599:   PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n");
2600:   if (!complete_print && !directionsprinted) {
2601:     PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n");
2602:     PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n");
2603:   }
2604:   if (!directionsprinted) {
2605:     PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n");
2606:     PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n");
2607:     directionsprinted = PETSC_TRUE;
2608:   }
2609:   if (complete_print) {
2610:     PetscViewerPushFormat(mviewer,format);
2611:   }

2613:   PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg);
2614:   if (!flg) jacobian = snes->jacobian;
2615:   else jacobian = snes->jacobian_pre;

2617:   if (!x) {
2618:     MatCreateVecs(jacobian, &x, NULL);
2619:   } else {
2620:     PetscObjectReference((PetscObject) x);
2621:   }
2622:   if (!f) {
2623:     VecDuplicate(x, &f);
2624:   } else {
2625:     PetscObjectReference((PetscObject) f);
2626:   }
2627:   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2628:   SNESComputeFunction(snes,x,f);
2629:   VecDestroy(&f);
2630:   PetscObjectTypeCompare((PetscObject)snes,SNESKSPTRANSPOSEONLY,&istranspose);
2631:   while (jacobian) {
2632:     Mat JT = NULL, Jsave = NULL;

2634:     if (istranspose) {
2635:       MatCreateTranspose(jacobian,&JT);
2636:       Jsave = jacobian;
2637:       jacobian = JT;
2638:     }
2639:     PetscObjectBaseTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPISBAIJ,"");
2640:     if (flg) {
2641:       A    = jacobian;
2642:       PetscObjectReference((PetscObject)A);
2643:     } else {
2644:       MatComputeOperator(jacobian,MATAIJ,&A);
2645:     }

2647:     MatGetType(A,&mattype);
2648:     MatGetSize(A,&M,&N);
2649:     MatGetLocalSize(A,&m,&n);
2650:     MatCreate(PetscObjectComm((PetscObject)A),&B);
2651:     MatSetType(B,mattype);
2652:     MatSetSizes(B,m,n,M,N);
2653:     MatSetBlockSizesFromMats(B,A,A);
2654:     MatSetUp(B);
2655:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2657:     SNESGetFunction(snes,NULL,NULL,&functx);
2658:     SNESComputeJacobianDefault(snes,x,B,B,functx);

2660:     MatDuplicate(B,MAT_COPY_VALUES,&D);
2661:     MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2662:     MatNorm(D,NORM_FROBENIUS,&nrm);
2663:     MatNorm(A,NORM_FROBENIUS,&gnorm);
2664:     MatDestroy(&D);
2665:     if (!gnorm) gnorm = 1; /* just in case */
2666:     PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm);

2668:     if (complete_print) {
2669:       PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n");
2670:       MatView(A,mviewer);
2671:       PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n");
2672:       MatView(B,mviewer);
2673:     }

2675:     if (threshold_print || complete_print) {
2676:       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2677:       PetscScalar       *cvals;
2678:       const PetscInt    *bcols;
2679:       const PetscScalar *bvals;

2681:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2682:       MatSetType(C,mattype);
2683:       MatSetSizes(C,m,n,M,N);
2684:       MatSetBlockSizesFromMats(C,A,A);
2685:       MatSetUp(C);
2686:       MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2688:       MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2689:       MatGetOwnershipRange(B,&Istart,&Iend);

2691:       for (row = Istart; row < Iend; row++) {
2692:         MatGetRow(B,row,&bncols,&bcols,&bvals);
2693:         PetscMalloc2(bncols,&ccols,bncols,&cvals);
2694:         for (j = 0, cncols = 0; j < bncols; j++) {
2695:           if (PetscAbsScalar(bvals[j]) > threshold) {
2696:             ccols[cncols] = bcols[j];
2697:             cvals[cncols] = bvals[j];
2698:             cncols += 1;
2699:           }
2700:         }
2701:         if (cncols) {
2702:           MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES);
2703:         }
2704:         MatRestoreRow(B,row,&bncols,&bcols,&bvals);
2705:         PetscFree2(ccols,cvals);
2706:       }
2707:       MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2708:       MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
2709:       PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold);
2710:       MatView(C,complete_print ? mviewer : viewer);
2711:       MatDestroy(&C);
2712:     }
2713:     MatDestroy(&A);
2714:     MatDestroy(&B);
2715:     MatDestroy(&JT);
2716:     if (Jsave) jacobian = Jsave;
2717:     if (jacobian != snes->jacobian_pre) {
2718:       jacobian = snes->jacobian_pre;
2719:       PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n");
2720:     }
2721:     else jacobian = NULL;
2722:   }
2723:   VecDestroy(&x);
2724:   if (complete_print) {
2725:     PetscViewerPopFormat(mviewer);
2726:   }
2727:   if (mviewer) { PetscViewerDestroy(&mviewer); }
2728:   PetscViewerASCIISetTab(viewer,tabs);
2729:   return(0);
2730: }

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

2735:    Collective on SNES

2737:    Input Parameters:
2738: +  snes - the SNES context
2739: -  x - input vector

2741:    Output Parameters:
2742: +  A - Jacobian matrix
2743: -  B - optional preconditioning matrix

2745:   Options Database Keys:
2746: +    -snes_lag_preconditioner <lag>
2747: .    -snes_lag_jacobian <lag>
2748: .    -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.
2749: .    -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
2750: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2751: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2752: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2753: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2754: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2755: .    -snes_compare_coloring_display - Compute the finite difference Jacobian using coloring and display verbose differences
2756: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2757: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2758: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2759: .    -snes_compare_coloring_draw - Compute the finite difference Jacobian using coloring and draw differences
2760: -    -snes_compare_coloring_draw_contour - Compute the finite difference Jacobian using coloring and show contours of matrices and differences

2762:    Notes:
2763:    Most users should not need to explicitly call this routine, as it
2764:    is used internally within the nonlinear solvers.

2766:    Developer Notes:
2767:     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
2768:       for with the SNESType of test that has been removed.

2770:    Level: developer

2772: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2773: @*/
2774: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2775: {
2777:   PetscBool      flag;
2778:   DM             dm;
2779:   DMSNES         sdm;
2780:   KSP            ksp;

2786:   VecValidValues(X,2,PETSC_TRUE);
2787:   SNESGetDM(snes,&dm);
2788:   DMGetDMSNES(dm,&sdm);

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

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

2794:   if (snes->lagjacobian == -2) {
2795:     snes->lagjacobian = -1;

2797:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2798:   } else if (snes->lagjacobian == -1) {
2799:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2800:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2801:     if (flag) {
2802:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2803:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2804:     }
2805:     return(0);
2806:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2807:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2808:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2809:     if (flag) {
2810:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2811:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2812:     }
2813:     return(0);
2814:   }
2815:   if (snes->npc && snes->npcside== PC_LEFT) {
2816:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2817:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2818:     return(0);
2819:   }

2821:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2822:   VecLockReadPush(X);
2823:   PetscStackPush("SNES user Jacobian function");
2824:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2825:   PetscStackPop;
2826:   VecLockReadPop(X);
2827:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

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

2832:   /* the next line ensures that snes->ksp exists */
2833:   SNESGetKSP(snes,&ksp);
2834:   if (snes->lagpreconditioner == -2) {
2835:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2836:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2837:     snes->lagpreconditioner = -1;
2838:   } else if (snes->lagpreconditioner == -1) {
2839:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2840:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2841:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2842:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2843:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2844:   } else {
2845:     PetscInfo(snes,"Rebuilding preconditioner\n");
2846:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2847:   }

2849:   SNESTestJacobian(snes);
2850:   /* make sure user returned a correct Jacobian and preconditioner */
2853:   {
2854:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2855:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2856:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2857:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2858:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject) snes)->options,((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2859:     if (flag || flag_draw || flag_contour) {
2860:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2861:       PetscViewer  vdraw,vstdout;
2862:       PetscBool    flg;
2863:       if (flag_operator) {
2864:         MatComputeOperator(A,MATAIJ,&Bexp_mine);
2865:         Bexp = Bexp_mine;
2866:       } else {
2867:         /* See if the preconditioning matrix can be viewed and added directly */
2868:         PetscObjectBaseTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2869:         if (flg) Bexp = B;
2870:         else {
2871:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2872:           MatComputeOperator(B,MATAIJ,&Bexp_mine);
2873:           Bexp = Bexp_mine;
2874:         }
2875:       }
2876:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2877:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2878:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2879:       if (flag_draw || flag_contour) {
2880:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2881:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2882:       } else vdraw = NULL;
2883:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2884:       if (flag) {MatView(Bexp,vstdout);}
2885:       if (vdraw) {MatView(Bexp,vdraw);}
2886:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2887:       if (flag) {MatView(FDexp,vstdout);}
2888:       if (vdraw) {MatView(FDexp,vdraw);}
2889:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2890:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2891:       if (flag) {MatView(FDexp,vstdout);}
2892:       if (vdraw) {              /* Always use contour for the difference */
2893:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2894:         MatView(FDexp,vdraw);
2895:         PetscViewerPopFormat(vdraw);
2896:       }
2897:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2898:       PetscViewerDestroy(&vdraw);
2899:       MatDestroy(&Bexp_mine);
2900:       MatDestroy(&FDexp);
2901:     }
2902:   }
2903:   {
2904:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2905:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2906:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2907:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2908:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2909:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2910:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2911:     if (flag_threshold) {
2912:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2913:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2914:     }
2915:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2916:       Mat            Bfd;
2917:       PetscViewer    vdraw,vstdout;
2918:       MatColoring    coloring;
2919:       ISColoring     iscoloring;
2920:       MatFDColoring  matfdcoloring;
2921:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2922:       void           *funcctx;
2923:       PetscReal      norm1,norm2,normmax;

2925:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2926:       MatColoringCreate(Bfd,&coloring);
2927:       MatColoringSetType(coloring,MATCOLORINGSL);
2928:       MatColoringSetFromOptions(coloring);
2929:       MatColoringApply(coloring,&iscoloring);
2930:       MatColoringDestroy(&coloring);
2931:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2932:       MatFDColoringSetFromOptions(matfdcoloring);
2933:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2934:       ISColoringDestroy(&iscoloring);

2936:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2937:       SNESGetFunction(snes,NULL,&func,&funcctx);
2938:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2939:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2940:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2941:       MatFDColoringSetFromOptions(matfdcoloring);
2942:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2943:       MatFDColoringDestroy(&matfdcoloring);

2945:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2946:       if (flag_draw || flag_contour) {
2947:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2948:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2949:       } else vdraw = NULL;
2950:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2951:       if (flag_display) {MatView(B,vstdout);}
2952:       if (vdraw) {MatView(B,vdraw);}
2953:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2954:       if (flag_display) {MatView(Bfd,vstdout);}
2955:       if (vdraw) {MatView(Bfd,vdraw);}
2956:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2957:       MatNorm(Bfd,NORM_1,&norm1);
2958:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2959:       MatNorm(Bfd,NORM_MAX,&normmax);
2960:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2961:       if (flag_display) {MatView(Bfd,vstdout);}
2962:       if (vdraw) {              /* Always use contour for the difference */
2963:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2964:         MatView(Bfd,vdraw);
2965:         PetscViewerPopFormat(vdraw);
2966:       }
2967:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2969:       if (flag_threshold) {
2970:         PetscInt bs,rstart,rend,i;
2971:         MatGetBlockSize(B,&bs);
2972:         MatGetOwnershipRange(B,&rstart,&rend);
2973:         for (i=rstart; i<rend; i++) {
2974:           const PetscScalar *ba,*ca;
2975:           const PetscInt    *bj,*cj;
2976:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2977:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2978:           MatGetRow(B,i,&bn,&bj,&ba);
2979:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2980:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2981:           for (j=0; j<bn; j++) {
2982:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2983:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2984:               maxentrycol = bj[j];
2985:               maxentry    = PetscRealPart(ba[j]);
2986:             }
2987:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2988:               maxdiffcol = bj[j];
2989:               maxdiff    = PetscRealPart(ca[j]);
2990:             }
2991:             if (rdiff > maxrdiff) {
2992:               maxrdiffcol = bj[j];
2993:               maxrdiff    = rdiff;
2994:             }
2995:           }
2996:           if (maxrdiff > 1) {
2997:             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);
2998:             for (j=0; j<bn; j++) {
2999:               PetscReal rdiff;
3000:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
3001:               if (rdiff > 1) {
3002:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
3003:               }
3004:             }
3005:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
3006:           }
3007:           MatRestoreRow(B,i,&bn,&bj,&ba);
3008:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
3009:         }
3010:       }
3011:       PetscViewerDestroy(&vdraw);
3012:       MatDestroy(&Bfd);
3013:     }
3014:   }
3015:   return(0);
3016: }

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

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

3025:      Collective on snes

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

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

3035:    Level: intermediate

3037: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
3038: M*/

3040: /*@C
3041:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
3042:    location to store the matrix.

3044:    Logically Collective on SNES

3046:    Input Parameters:
3047: +  snes - the SNES context
3048: .  Amat - the matrix that defines the (approximate) Jacobian
3049: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
3050: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
3051: -  ctx - [optional] user-defined context for private data for the
3052:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

3054:    Notes:
3055:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
3056:    each matrix.

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

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

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

3067:    Level: beginner

3069: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
3070:           SNESSetPicard(), SNESJacobianFunction
3071: @*/
3072: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
3073: {
3075:   DM             dm;

3083:   SNESGetDM(snes,&dm);
3084:   DMSNESSetJacobian(dm,J,ctx);
3085:   if (Amat) {
3086:     PetscObjectReference((PetscObject)Amat);
3087:     MatDestroy(&snes->jacobian);

3089:     snes->jacobian = Amat;
3090:   }
3091:   if (Pmat) {
3092:     PetscObjectReference((PetscObject)Pmat);
3093:     MatDestroy(&snes->jacobian_pre);

3095:     snes->jacobian_pre = Pmat;
3096:   }
3097:   return(0);
3098: }

3100: /*@C
3101:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
3102:    provided context for evaluating the Jacobian.

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

3106:    Input Parameter:
3107: .  snes - the nonlinear solver context

3109:    Output Parameters:
3110: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
3111: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
3112: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
3113: -  ctx - location to stash Jacobian ctx (or NULL)

3115:    Level: advanced

3117: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
3118: @*/
3119: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
3120: {
3122:   DM             dm;
3123:   DMSNES         sdm;

3127:   if (Amat) *Amat = snes->jacobian;
3128:   if (Pmat) *Pmat = snes->jacobian_pre;
3129:   SNESGetDM(snes,&dm);
3130:   DMGetDMSNES(dm,&sdm);
3131:   if (J) *J = sdm->ops->computejacobian;
3132:   if (ctx) *ctx = sdm->jacobianctx;
3133:   return(0);
3134: }

3136: static PetscErrorCode SNESSetDefaultComputeJacobian(SNES snes)
3137: {
3139:   DM             dm;
3140:   DMSNES         sdm;

3143:   SNESGetDM(snes,&dm);
3144:   DMGetDMSNES(dm,&sdm);
3145:   if (!sdm->ops->computejacobian && snes->jacobian_pre) {
3146:     DM        dm;
3147:     PetscBool isdense,ismf;

3149:     SNESGetDM(snes,&dm);
3150:     PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&isdense,MATSEQDENSE,MATMPIDENSE,MATDENSE,NULL);
3151:     PetscObjectTypeCompareAny((PetscObject)snes->jacobian_pre,&ismf,MATMFFD,MATSHELL,NULL);
3152:     if (isdense) {
3153:       DMSNESSetJacobian(dm,SNESComputeJacobianDefault,NULL);
3154:     } else if (!ismf) {
3155:       DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
3156:     }
3157:   }
3158:   return(0);
3159: }

3161: /*@
3162:    SNESSetUp - Sets up the internal data structures for the later use
3163:    of a nonlinear solver.

3165:    Collective on SNES

3167:    Input Parameters:
3168: .  snes - the SNES context

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

3177:    Level: advanced

3179: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
3180: @*/
3181: PetscErrorCode  SNESSetUp(SNES snes)
3182: {
3184:   DM             dm;
3185:   DMSNES         sdm;
3186:   SNESLineSearch linesearch, pclinesearch;
3187:   void           *lsprectx,*lspostctx;
3188:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
3189:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
3190:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
3191:   Vec            f,fpc;
3192:   void           *funcctx;
3193:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
3194:   void           *jacctx,*appctx;
3195:   Mat            j,jpre;

3199:   if (snes->setupcalled) return(0);
3200:   PetscLogEventBegin(SNES_Setup,snes,0,0,0);

3202:   if (!((PetscObject)snes)->type_name) {
3203:     SNESSetType(snes,SNESNEWTONLS);
3204:   }

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

3208:   SNESGetDM(snes,&dm);
3209:   DMGetDMSNES(dm,&sdm);
3210:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
3211:   SNESSetDefaultComputeJacobian(snes);

3213:   if (!snes->vec_func) {
3214:     DMCreateGlobalVector(dm,&snes->vec_func);
3215:   }

3217:   if (!snes->ksp) {
3218:     SNESGetKSP(snes, &snes->ksp);
3219:   }

3221:   if (snes->linesearch) {
3222:     SNESGetLineSearch(snes, &snes->linesearch);
3223:     SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);
3224:   }

3226:   if (snes->npc && (snes->npcside== PC_LEFT)) {
3227:     snes->mf          = PETSC_TRUE;
3228:     snes->mf_operator = PETSC_FALSE;
3229:   }

3231:   if (snes->npc) {
3232:     /* copy the DM over */
3233:     SNESGetDM(snes,&dm);
3234:     SNESSetDM(snes->npc,dm);

3236:     SNESGetFunction(snes,&f,&func,&funcctx);
3237:     VecDuplicate(f,&fpc);
3238:     SNESSetFunction(snes->npc,fpc,func,funcctx);
3239:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
3240:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
3241:     SNESGetApplicationContext(snes,&appctx);
3242:     SNESSetApplicationContext(snes->npc,appctx);
3243:     VecDestroy(&fpc);

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

3248:     /* default to 1 iteration */
3249:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
3250:     if (snes->npcside==PC_RIGHT) {
3251:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
3252:     } else {
3253:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
3254:     }
3255:     SNESSetFromOptions(snes->npc);

3257:     /* copy the line search context over */
3258:     if (snes->linesearch && snes->npc->linesearch) {
3259:       SNESGetLineSearch(snes,&linesearch);
3260:       SNESGetLineSearch(snes->npc,&pclinesearch);
3261:       SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
3262:       SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
3263:       SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
3264:       SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
3265:       PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
3266:     }
3267:   }
3268:   if (snes->mf) {
3269:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
3270:   }
3271:   if (snes->ops->usercompute && !snes->user) {
3272:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
3273:   }

3275:   snes->jac_iter = 0;
3276:   snes->pre_iter = 0;

3278:   if (snes->ops->setup) {
3279:     (*snes->ops->setup)(snes);
3280:   }

3282:   SNESSetDefaultComputeJacobian(snes);

3284:   if (snes->npc && (snes->npcside== PC_LEFT)) {
3285:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
3286:       if (snes->linesearch) {
3287:         SNESGetLineSearch(snes,&linesearch);
3288:         SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
3289:       }
3290:     }
3291:   }
3292:   PetscLogEventEnd(SNES_Setup,snes,0,0,0);
3293:   snes->setupcalled = PETSC_TRUE;
3294:   return(0);
3295: }

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

3300:    Collective on SNES

3302:    Input Parameter:
3303: .  snes - iterative context obtained from SNESCreate()

3305:    Level: intermediate

3307:    Notes:
3308:     Also calls the application context destroy routine set with SNESSetComputeApplicationContext()

3310: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
3311: @*/
3312: PetscErrorCode  SNESReset(SNES snes)
3313: {

3318:   if (snes->ops->userdestroy && snes->user) {
3319:     (*snes->ops->userdestroy)((void**)&snes->user);
3320:     snes->user = NULL;
3321:   }
3322:   if (snes->npc) {
3323:     SNESReset(snes->npc);
3324:   }

3326:   if (snes->ops->reset) {
3327:     (*snes->ops->reset)(snes);
3328:   }
3329:   if (snes->ksp) {
3330:     KSPReset(snes->ksp);
3331:   }

3333:   if (snes->linesearch) {
3334:     SNESLineSearchReset(snes->linesearch);
3335:   }

3337:   VecDestroy(&snes->vec_rhs);
3338:   VecDestroy(&snes->vec_sol);
3339:   VecDestroy(&snes->vec_sol_update);
3340:   VecDestroy(&snes->vec_func);
3341:   MatDestroy(&snes->jacobian);
3342:   MatDestroy(&snes->jacobian_pre);
3343:   MatDestroy(&snes->picard);
3344:   VecDestroyVecs(snes->nwork,&snes->work);
3345:   VecDestroyVecs(snes->nvwork,&snes->vwork);

3347:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3349:   snes->nwork       = snes->nvwork = 0;
3350:   snes->setupcalled = PETSC_FALSE;
3351:   return(0);
3352: }

3354: /*@
3355:    SNESConvergedReasonViewCancel - Clears all the reasonview functions for a SNES object.

3357:    Collective on SNES

3359:    Input Parameter:
3360: .  snes - iterative context obtained from SNESCreate()

3362:    Level: intermediate

3364: .seealso: SNESCreate(), SNESDestroy(), SNESReset()
3365: @*/
3366: PetscErrorCode  SNESConvergedReasonViewCancel(SNES snes)
3367: {
3369:   PetscInt       i;

3373:   for (i=0; i<snes->numberreasonviews; i++) {
3374:     if (snes->reasonviewdestroy[i]) {
3375:       (*snes->reasonviewdestroy[i])(&snes->reasonviewcontext[i]);
3376:     }
3377:   }
3378:   snes->numberreasonviews = 0;
3379:   return(0);
3380: }

3382: /*@C
3383:    SNESDestroy - Destroys the nonlinear solver context that was created
3384:    with SNESCreate().

3386:    Collective on SNES

3388:    Input Parameter:
3389: .  snes - the SNES context

3391:    Level: beginner

3393: .seealso: SNESCreate(), SNESSolve()
3394: @*/
3395: PetscErrorCode  SNESDestroy(SNES *snes)
3396: {

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

3404:   SNESReset((*snes));
3405:   SNESDestroy(&(*snes)->npc);

3407:   /* if memory was published with SAWs then destroy it */
3408:   PetscObjectSAWsViewOff((PetscObject)*snes);
3409:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

3411:   if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
3412:   DMDestroy(&(*snes)->dm);
3413:   KSPDestroy(&(*snes)->ksp);
3414:   SNESLineSearchDestroy(&(*snes)->linesearch);

3416:   PetscFree((*snes)->kspconvctx);
3417:   if ((*snes)->ops->convergeddestroy) {
3418:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
3419:   }
3420:   if ((*snes)->conv_hist_alloc) {
3421:     PetscFree2((*snes)->conv_hist,(*snes)->conv_hist_its);
3422:   }
3423:   SNESMonitorCancel((*snes));
3424:   SNESConvergedReasonViewCancel((*snes));
3425:   PetscHeaderDestroy(snes);
3426:   return(0);
3427: }

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

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

3434:    Logically Collective on SNES

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

3441:    Options Database Keys:
3442: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3443: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3444: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3445: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag

3447:    Notes:
3448:    The default is 1
3449:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1 or SNESSetLagPreconditionerPersists() was called

3451:    SNESSetLagPreconditionerPersists() allows using the same uniform lagging (for example every second solve) across multiple solves.

3453:    Level: intermediate

3455: .seealso: SNESSetTrustRegionTolerance(), SNESGetLagPreconditioner(), SNESSetLagJacobian(), SNESGetLagJacobian(), SNESSetLagPreconditionerPersists(),
3456:           SNESSetLagJacobianPersists()

3458: @*/
3459: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3460: {
3463:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3464:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3466:   snes->lagpreconditioner = lag;
3467:   return(0);
3468: }

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

3473:    Logically Collective on SNES

3475:    Input Parameters:
3476: +  snes - the SNES context
3477: -  steps - the number of refinements to do, defaults to 0

3479:    Options Database Keys:
3480: .    -snes_grid_sequence <steps>

3482:    Level: intermediate

3484:    Notes:
3485:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

3489: @*/
3490: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3491: {
3495:   snes->gridsequence = steps;
3496:   return(0);
3497: }

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

3502:    Logically Collective on SNES

3504:    Input Parameter:
3505: .  snes - the SNES context

3507:    Output Parameter:
3508: .  steps - the number of refinements to do, defaults to 0

3510:    Options Database Keys:
3511: .    -snes_grid_sequence <steps>

3513:    Level: intermediate

3515:    Notes:
3516:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

3520: @*/
3521: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3522: {
3525:   *steps = snes->gridsequence;
3526:   return(0);
3527: }

3529: /*@
3530:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3532:    Not Collective

3534:    Input Parameter:
3535: .  snes - the SNES context

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

3541:    Options Database Keys:
3542: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3543: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3544: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3545: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag

3547:    Notes:
3548:    The default is 1
3549:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3551:    Level: intermediate

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

3555: @*/
3556: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3557: {
3560:   *lag = snes->lagpreconditioner;
3561:   return(0);
3562: }

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

3568:    Logically Collective on SNES

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

3575:    Options Database Keys:
3576: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3577: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3578: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3579: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag.

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

3587:    Level: intermediate

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

3591: @*/
3592: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3593: {
3596:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3597:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3599:   snes->lagjacobian = lag;
3600:   return(0);
3601: }

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

3606:    Not Collective

3608:    Input Parameter:
3609: .  snes - the SNES context

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

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

3619:    Level: intermediate

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

3623: @*/
3624: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3625: {
3628:   *lag = snes->lagjacobian;
3629:   return(0);
3630: }

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

3635:    Logically collective on SNES

3637:    Input Parameters:
3638: +  snes - the SNES context
3639: -   flg - jacobian lagging persists if true

3641:    Options Database Keys:
3642: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3643: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3644: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3645: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag

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

3652:    Level: developer

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

3656: @*/
3657: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3658: {
3662:   snes->lagjac_persist = flg;
3663:   return(0);
3664: }

3666: /*@
3667:    SNESSetLagPreconditionerPersists - Set whether or not the preconditioner lagging persists through multiple nonlinear solves

3669:    Logically Collective on SNES

3671:    Input Parameters:
3672: +  snes - the SNES context
3673: -   flg - preconditioner lagging persists if true

3675:    Options Database Keys:
3676: +    -snes_lag_jacobian_persists <true,false> - sets the persistence
3677: .    -snes_lag_jacobian <-2,1,2,...> - sets the lag
3678: .    -snes_lag_preconditioner_persists <true,false> - sets the persistence
3679: -    -snes_lag_preconditioner <-2,1,2,...> - sets the lag

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

3686:    Level: developer

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

3690: @*/
3691: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3692: {
3696:   snes->lagpre_persist = flg;
3697:   return(0);
3698: }

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

3703:    Logically Collective on SNES

3705:    Input Parameters:
3706: +  snes - the SNES context
3707: -  force - PETSC_TRUE require at least one iteration

3709:    Options Database Keys:
3710: .    -snes_force_iteration <force> - Sets forcing an iteration

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

3715:    Level: intermediate

3717: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3718: @*/
3719: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3720: {
3723:   snes->forceiteration = force;
3724:   return(0);
3725: }

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

3730:    Logically Collective on SNES

3732:    Input Parameters:
3733: .  snes - the SNES context

3735:    Output Parameter:
3736: .  force - PETSC_TRUE requires at least one iteration.

3738:    Level: intermediate

3740: .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3741: @*/
3742: PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
3743: {
3746:   *force = snes->forceiteration;
3747:   return(0);
3748: }

3750: /*@
3751:    SNESSetTolerances - Sets various parameters used in convergence tests.

3753:    Logically Collective on SNES

3755:    Input Parameters:
3756: +  snes - the SNES context
3757: .  abstol - absolute convergence tolerance
3758: .  rtol - relative convergence tolerance
3759: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3760: .  maxit - maximum number of iterations
3761: -  maxf - maximum number of function evaluations (-1 indicates no limit)

3763:    Options Database Keys:
3764: +    -snes_atol <abstol> - Sets abstol
3765: .    -snes_rtol <rtol> - Sets rtol
3766: .    -snes_stol <stol> - Sets stol
3767: .    -snes_max_it <maxit> - Sets maxit
3768: -    -snes_max_funcs <maxf> - Sets maxf

3770:    Notes:
3771:    The default maximum number of iterations is 50.
3772:    The default maximum number of function evaluations is 1000.

3774:    Level: intermediate

3776: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3777: @*/
3778: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3779: {

3788:   if (abstol != PETSC_DEFAULT) {
3789:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3790:     snes->abstol = abstol;
3791:   }
3792:   if (rtol != PETSC_DEFAULT) {
3793:     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);
3794:     snes->rtol = rtol;
3795:   }
3796:   if (stol != PETSC_DEFAULT) {
3797:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3798:     snes->stol = stol;
3799:   }
3800:   if (maxit != PETSC_DEFAULT) {
3801:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3802:     snes->max_its = maxit;
3803:   }
3804:   if (maxf != PETSC_DEFAULT) {
3805:     if (maxf < -1) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be -1 or nonnegative",maxf);
3806:     snes->max_funcs = maxf;
3807:   }
3808:   snes->tolerancesset = PETSC_TRUE;
3809:   return(0);
3810: }

3812: /*@
3813:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3815:    Logically Collective on SNES

3817:    Input Parameters:
3818: +  snes - the SNES context
3819: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3821:    Options Database Keys:
3822: .    -snes_divergence_tolerance <divtol> - Sets divtol

3824:    Notes:
3825:    The default divergence tolerance is 1e4.

3827:    Level: intermediate

3829: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3830: @*/
3831: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3832: {

3837:   if (divtol != PETSC_DEFAULT) {
3838:     snes->divtol = divtol;
3839:   }
3840:   else {
3841:     snes->divtol = 1.0e4;
3842:   }
3843:   return(0);
3844: }

3846: /*@
3847:    SNESGetTolerances - Gets various parameters used in convergence tests.

3849:    Not Collective

3851:    Input Parameters:
3852: +  snes - the SNES context
3853: .  atol - absolute convergence tolerance
3854: .  rtol - relative convergence tolerance
3855: .  stol -  convergence tolerance in terms of the norm
3856:            of the change in the solution between steps
3857: .  maxit - maximum number of iterations
3858: -  maxf - maximum number of function evaluations

3860:    Notes:
3861:    The user can specify NULL for any parameter that is not needed.

3863:    Level: intermediate

3865: .seealso: SNESSetTolerances()
3866: @*/
3867: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3868: {
3871:   if (atol)  *atol  = snes->abstol;
3872:   if (rtol)  *rtol  = snes->rtol;
3873:   if (stol)  *stol  = snes->stol;
3874:   if (maxit) *maxit = snes->max_its;
3875:   if (maxf)  *maxf  = snes->max_funcs;
3876:   return(0);
3877: }

3879: /*@
3880:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3882:    Not Collective

3884:    Input Parameters:
3885: +  snes - the SNES context
3886: -  divtol - divergence tolerance

3888:    Level: intermediate

3890: .seealso: SNESSetDivergenceTolerance()
3891: @*/
3892: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3893: {
3896:   if (divtol) *divtol = snes->divtol;
3897:   return(0);
3898: }

3900: /*@
3901:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3903:    Logically Collective on SNES

3905:    Input Parameters:
3906: +  snes - the SNES context
3907: -  tol - tolerance

3909:    Options Database Key:
3910: .  -snes_trtol <tol> - Sets tol

3912:    Level: intermediate

3914: .seealso: SNESSetTolerances()
3915: @*/
3916: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3917: {
3921:   snes->deltatol = tol;
3922:   return(0);
3923: }

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

3927: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3928: {
3929:   PetscDrawLG      lg;
3930:   PetscErrorCode   ierr;
3931:   PetscReal        x,y,per;
3932:   PetscViewer      v = (PetscViewer)monctx;
3933:   static PetscReal prev; /* should be in the context */
3934:   PetscDraw        draw;

3938:   PetscViewerDrawGetDrawLG(v,0,&lg);
3939:   if (!n) {PetscDrawLGReset(lg);}
3940:   PetscDrawLGGetDraw(lg,&draw);
3941:   PetscDrawSetTitle(draw,"Residual norm");
3942:   x    = (PetscReal)n;
3943:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3944:   else y = -15.0;
3945:   PetscDrawLGAddPoint(lg,&x,&y);
3946:   if (n < 20 || !(n % 5) || snes->reason) {
3947:     PetscDrawLGDraw(lg);
3948:     PetscDrawLGSave(lg);
3949:   }

3951:   PetscViewerDrawGetDrawLG(v,1,&lg);
3952:   if (!n) {PetscDrawLGReset(lg);}
3953:   PetscDrawLGGetDraw(lg,&draw);
3954:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3955:    SNESMonitorRange_Private(snes,n,&per);
3956:   x    = (PetscReal)n;
3957:   y    = 100.0*per;
3958:   PetscDrawLGAddPoint(lg,&x,&y);
3959:   if (n < 20 || !(n % 5) || snes->reason) {
3960:     PetscDrawLGDraw(lg);
3961:     PetscDrawLGSave(lg);
3962:   }

3964:   PetscViewerDrawGetDrawLG(v,2,&lg);
3965:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3966:   PetscDrawLGGetDraw(lg,&draw);
3967:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3968:   x    = (PetscReal)n;
3969:   y    = (prev - rnorm)/prev;
3970:   PetscDrawLGAddPoint(lg,&x,&y);
3971:   if (n < 20 || !(n % 5) || snes->reason) {
3972:     PetscDrawLGDraw(lg);
3973:     PetscDrawLGSave(lg);
3974:   }

3976:   PetscViewerDrawGetDrawLG(v,3,&lg);
3977:   if (!n) {PetscDrawLGReset(lg);}
3978:   PetscDrawLGGetDraw(lg,&draw);
3979:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3980:   x    = (PetscReal)n;
3981:   y    = (prev - rnorm)/(prev*per);
3982:   if (n > 2) { /*skip initial crazy value */
3983:     PetscDrawLGAddPoint(lg,&x,&y);
3984:   }
3985:   if (n < 20 || !(n % 5) || snes->reason) {
3986:     PetscDrawLGDraw(lg);
3987:     PetscDrawLGSave(lg);
3988:   }
3989:   prev = rnorm;
3990:   return(0);
3991: }

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

3996:    Collective on SNES

3998:    Input Parameters:
3999: +  snes - nonlinear solver context obtained from SNESCreate()
4000: .  iter - iteration number
4001: -  rnorm - relative norm of the residual

4003:    Notes:
4004:    This routine is called by the SNES implementations.
4005:    It does not typically need to be called by the user.

4007:    Level: developer

4009: .seealso: SNESMonitorSet()
4010: @*/
4011: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
4012: {
4014:   PetscInt       i,n = snes->numbermonitors;

4017:   VecLockReadPush(snes->vec_sol);
4018:   for (i=0; i<n; i++) {
4019:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
4020:   }
4021:   VecLockReadPop(snes->vec_sol);
4022:   return(0);
4023: }

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

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

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

4034:      Collective on snes

4036:     Input Parameters:
4037: +    snes - the SNES context
4038: .    its - iteration number
4039: .    norm - 2-norm function value (may be estimated)
4040: -    mctx - [optional] monitoring context

4042:    Level: advanced

4044: .seealso:   SNESMonitorSet(), SNESMonitorGet()
4045: M*/

4047: /*@C
4048:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
4049:    iteration of the nonlinear solver to display the iteration's
4050:    progress.

4052:    Logically Collective on SNES

4054:    Input Parameters:
4055: +  snes - the SNES context
4056: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
4057: .  mctx - [optional] user-defined context for private data for the
4058:           monitor routine (use NULL if no context is desired)
4059: -  monitordestroy - [optional] routine that frees monitor context
4060:           (may be NULL)

4062:    Options Database Keys:
4063: +    -snes_monitor        - sets SNESMonitorDefault()
4064: .    -snes_monitor draw::draw_lg - sets line graph monitor,
4065: -    -snes_monitor_cancel - cancels all monitors that have
4066:                             been hardwired into a code by
4067:                             calls to SNESMonitorSet(), but
4068:                             does not cancel those set via
4069:                             the options database.

4071:    Notes:
4072:    Several different monitoring routines may be set by calling
4073:    SNESMonitorSet() multiple times; all will be called in the
4074:    order in which they were set.

4076:    Fortran Notes:
4077:     Only a single monitor function can be set for each SNES object

4079:    Level: intermediate

4081: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
4082: @*/
4083: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
4084: {
4085:   PetscInt       i;
4087:   PetscBool      identical;

4091:   for (i=0; i<snes->numbermonitors;i++) {
4092:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
4093:     if (identical) return(0);
4094:   }
4095:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
4096:   snes->monitor[snes->numbermonitors]          = f;
4097:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
4098:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
4099:   return(0);
4100: }

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

4105:    Logically Collective on SNES

4107:    Input Parameters:
4108: .  snes - the SNES context

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

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

4118:    Level: intermediate

4120: .seealso: SNESMonitorDefault(), SNESMonitorSet()
4121: @*/
4122: PetscErrorCode  SNESMonitorCancel(SNES snes)
4123: {
4125:   PetscInt       i;

4129:   for (i=0; i<snes->numbermonitors; i++) {
4130:     if (snes->monitordestroy[i]) {
4131:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
4132:     }
4133:   }
4134:   snes->numbermonitors = 0;
4135:   return(0);
4136: }

4138: /*MC
4139:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

4145:      Collective on snes

4147:     Input Parameters:
4148: +    snes - the SNES context
4149: .    it - current iteration (0 is the first and is before any Newton step)
4150: .    xnorm - 2-norm of current iterate
4151: .    gnorm - 2-norm of current step
4152: .    f - 2-norm of function
4153: -    cctx - [optional] convergence context

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

4158:    Level: intermediate

4160: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
4161: M*/

4163: /*@C
4164:    SNESSetConvergenceTest - Sets the function that is to be used
4165:    to test for convergence of the nonlinear iterative solution.

4167:    Logically Collective on SNES

4169:    Input Parameters:
4170: +  snes - the SNES context
4171: .  SNESConvergenceTestFunction - routine to test for convergence
4172: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
4173: -  destroy - [optional] destructor for the context (may be NULL; PETSC_NULL_FUNCTION in Fortran)

4175:    Level: advanced

4177: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
4178: @*/
4179: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
4180: {

4185:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
4186:   if (snes->ops->convergeddestroy) {
4187:     (*snes->ops->convergeddestroy)(snes->cnvP);
4188:   }
4189:   snes->ops->converged        = SNESConvergenceTestFunction;
4190:   snes->ops->convergeddestroy = destroy;
4191:   snes->cnvP                  = cctx;
4192:   return(0);
4193: }

4195: /*@
4196:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

4198:    Not Collective

4200:    Input Parameter:
4201: .  snes - the SNES context

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

4207:    Options Database:
4208: .   -snes_converged_reason - prints the reason to standard out

4210:    Level: intermediate

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

4215: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
4216: @*/
4217: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
4218: {
4222:   *reason = snes->reason;
4223:   return(0);
4224: }

4226: /*@C
4227:    SNESGetConvergedReasonString - Return a human readable string for snes converged reason

4229:    Not Collective

4231:    Input Parameter:
4232: .  snes - the SNES context

4234:    Output Parameter:
4235: .  strreason - a human readable string that describes SNES converged reason

4237:    Level: beginner

4239: .seealso: SNESGetConvergedReason()
4240: @*/
4241: PetscErrorCode SNESGetConvergedReasonString(SNES snes, const char** strreason)
4242: {
4246:   *strreason = SNESConvergedReasons[snes->reason];
4247:   return(0);
4248: }

4250: /*@
4251:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

4253:    Not Collective

4255:    Input Parameters:
4256: +  snes - the SNES context
4257: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
4258:             manual pages for the individual convergence tests for complete lists

4260:    Level: intermediate

4262: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
4263: @*/
4264: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
4265: {
4268:   snes->reason = reason;
4269:   return(0);
4270: }

4272: /*@
4273:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

4275:    Logically Collective on SNES

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

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

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

4293:    Level: intermediate

4295: .seealso: SNESGetConvergenceHistory()

4297: @*/
4298: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
4299: {

4306:   if (!a) {
4307:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
4308:     PetscCalloc2(na,&a,na,&its);
4309:     snes->conv_hist_alloc = PETSC_TRUE;
4310:   }
4311:   snes->conv_hist       = a;
4312:   snes->conv_hist_its   = its;
4313:   snes->conv_hist_max   = na;
4314:   snes->conv_hist_len   = 0;
4315:   snes->conv_hist_reset = reset;
4316:   return(0);
4317: }

4319: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4320: #include <engine.h>   /* MATLAB include file */
4321: #include <mex.h>      /* MATLAB include file */

4323: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4324: {
4325:   mxArray   *mat;
4326:   PetscInt  i;
4327:   PetscReal *ar;

4330:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4331:   ar  = (PetscReal*) mxGetData(mat);
4332:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4333:   PetscFunctionReturn(mat);
4334: }
4335: #endif

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

4340:    Not Collective

4342:    Input Parameter:
4343: .  snes - iterative context obtained from SNESCreate()

4345:    Output Parameters:
4346: +  a   - array to hold history
4347: .  its - integer array holds the number of linear iterations (or
4348:          negative if not converged) for each solve.
4349: -  na  - size of a and its

4351:    Notes:
4352:     The calling sequence for this routine in Fortran is
4353: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

4359:    Level: intermediate

4361: .seealso: SNESSetConvergenceHistory()

4363: @*/
4364: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4365: {
4368:   if (a)   *a   = snes->conv_hist;
4369:   if (its) *its = snes->conv_hist_its;
4370:   if (na)  *na  = snes->conv_hist_len;
4371:   return(0);
4372: }

4374: /*@C
4375:   SNESSetUpdate - Sets the general-purpose update function called
4376:   at the beginning of every iteration of the nonlinear solve. Specifically
4377:   it is called just before the Jacobian is "evaluated".

4379:   Logically Collective on SNES

4381:   Input Parameters:
4382: + snes - The nonlinear solver context
4383: - func - The function

4385:   Calling sequence of func:
4386: $ func (SNES snes, PetscInt step);

4388: . step - The current step of the iteration

4390:   Level: advanced

4392:   Note:
4393:      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()
4394:      This is not used by most users.

4396:      There are a varity of function hooks one many set that are called at different stages of the nonlinear solution process, see the functions listed below.

4398: .seealso SNESSetJacobian(), SNESSolve(), SNESLineSearchSetPreCheck(), SNESLineSearchSetPostCheck(), SNESNewtonTRSetPreCheck(), SNESNewtonTRSetPostCheck(),
4399:          SNESMonitorSet(), SNESSetDivergenceTest()
4400: @*/
4401: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4402: {
4405:   snes->ops->update = func;
4406:   return(0);
4407: }

4409: /*
4410:    SNESScaleStep_Private - Scales a step so that its length is less than the
4411:    positive parameter delta.

4413:     Input Parameters:
4414: +   snes - the SNES context
4415: .   y - approximate solution of linear system
4416: .   fnorm - 2-norm of current function
4417: -   delta - trust region size

4419:     Output Parameters:
4420: +   gpnorm - predicted function norm at the new point, assuming local
4421:     linearization.  The value is zero if the step lies within the trust
4422:     region, and exceeds zero otherwise.
4423: -   ynorm - 2-norm of the step

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

4429: */
4430: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4431: {
4432:   PetscReal      nrm;
4433:   PetscScalar    cnorm;


4441:   VecNorm(y,NORM_2,&nrm);
4442:   if (nrm > *delta) {
4443:     nrm     = *delta/nrm;
4444:     *gpnorm = (1.0 - nrm)*(*fnorm);
4445:     cnorm   = nrm;
4446:     VecScale(y,cnorm);
4447:     *ynorm  = *delta;
4448:   } else {
4449:     *gpnorm = 0.0;
4450:     *ynorm  = nrm;
4451:   }
4452:   return(0);
4453: }

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

4458:    Collective on SNES

4460:    Parameter:
4461: +  snes - iterative context obtained from SNESCreate()
4462: -  viewer - the viewer to display the reason

4464:    Options Database Keys:
4465: +  -snes_converged_reason - print reason for converged or diverged, also prints number of iterations
4466: -  -snes_converged_reason ::failed - only print reason and number of iterations when diverged

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

4472:    Level: beginner

4474: .seealso: SNESCreate(), SNESSetUp(), SNESDestroy(), SNESSetTolerances(), SNESConvergedDefault(), SNESGetConvergedReason(), SNESConvergedReasonViewFromOptions(),
4475:           PetscViewerPushFormat(), PetscViewerPopFormat()

4477: @*/
4478: PetscErrorCode  SNESConvergedReasonView(SNES snes,PetscViewer viewer)
4479: {
4480:   PetscViewerFormat format;
4481:   PetscBool         isAscii;
4482:   PetscErrorCode    ierr;

4485:   if (!viewer) viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
4486:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
4487:   if (isAscii) {
4488:     PetscViewerGetFormat(viewer, &format);
4489:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
4490:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4491:       DM              dm;
4492:       Vec             u;
4493:       PetscDS         prob;
4494:       PetscInt        Nf, f;
4495:       PetscErrorCode (**exactSol)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4496:       void            **exactCtx;
4497:       PetscReal       error;

4499:       SNESGetDM(snes, &dm);
4500:       SNESGetSolution(snes, &u);
4501:       DMGetDS(dm, &prob);
4502:       PetscDSGetNumFields(prob, &Nf);
4503:       PetscMalloc2(Nf, &exactSol, Nf, &exactCtx);
4504:       for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactSol[f], &exactCtx[f]);}
4505:       DMComputeL2Diff(dm, 0.0, exactSol, exactCtx, u, &error);
4506:       PetscFree2(exactSol, exactCtx);
4507:       if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
4508:       else                 {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
4509:     }
4510:     if (snes->reason > 0 && format != PETSC_VIEWER_FAILED) {
4511:       if (((PetscObject) snes)->prefix) {
4512:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4513:       } else {
4514:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4515:       }
4516:     } else if (snes->reason <= 0) {
4517:       if (((PetscObject) snes)->prefix) {
4518:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4519:       } else {
4520:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4521:       }
4522:     }
4523:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4524:   }
4525:   return(0);
4526: }

4528: /*@C
4529:    SNESConvergedReasonViewSet - Sets an ADDITIONAL function that is to be used at the
4530:     end of the nonlinear solver to display the conver reason of the nonlinear solver.

4532:    Logically Collective on SNES

4534:    Input Parameters:
4535: +  snes - the SNES context
4536: .  f - the snes converged reason view function
4537: .  vctx - [optional] user-defined context for private data for the
4538:           snes converged reason view routine (use NULL if no context is desired)
4539: -  reasonviewdestroy - [optional] routine that frees reasonview context
4540:           (may be NULL)

4542:    Options Database Keys:
4543: +    -snes_converged_reason        - sets a default SNESConvergedReasonView()
4544: -    -snes_converged_reason_view_cancel - cancels all converged reason viewers that have
4545:                             been hardwired into a code by
4546:                             calls to SNESConvergedReasonViewSet(), but
4547:                             does not cancel those set via
4548:                             the options database.

4550:    Notes:
4551:    Several different converged reason view routines may be set by calling
4552:    SNESConvergedReasonViewSet() multiple times; all will be called in the
4553:    order in which they were set.

4555:    Level: intermediate

4557: .seealso: SNESConvergedReasonView(), SNESConvergedReasonViewCancel()
4558: @*/
4559: PetscErrorCode  SNESConvergedReasonViewSet(SNES snes,PetscErrorCode (*f)(SNES,void*),void *vctx,PetscErrorCode (*reasonviewdestroy)(void**))
4560: {
4561:   PetscInt       i;
4563:   PetscBool      identical;

4567:   for (i=0; i<snes->numberreasonviews;i++) {
4568:     PetscMonitorCompare((PetscErrorCode (*)(void))f,vctx,reasonviewdestroy,(PetscErrorCode (*)(void))snes->reasonview[i],snes->reasonviewcontext[i],snes->reasonviewdestroy[i],&identical);
4569:     if (identical) return(0);
4570:   }
4571:   if (snes->numberreasonviews >= MAXSNESREASONVIEWS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many SNES reasonview set");
4572:   snes->reasonview[snes->numberreasonviews]          = f;
4573:   snes->reasonviewdestroy[snes->numberreasonviews]   = reasonviewdestroy;
4574:   snes->reasonviewcontext[snes->numberreasonviews++] = (void*)vctx;
4575:   return(0);
4576: }

4578: /*@
4579:   SNESConvergedReasonViewFromOptions - Processes command line options to determine if/how a SNESReason is to be viewed.
4580:                                        All the user-provided convergedReasonView routines will be involved as well, if they exist.

4582:   Collective on SNES

4584:   Input Parameters:
4585: . snes   - the SNES object

4587:   Level: intermediate

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

4591: @*/
4592: PetscErrorCode SNESConvergedReasonViewFromOptions(SNES snes)
4593: {
4594:   PetscErrorCode    ierr;
4595:   PetscViewer       viewer;
4596:   PetscBool         flg;
4597:   static PetscBool  incall = PETSC_FALSE;
4598:   PetscViewerFormat format;
4599:   PetscInt          i;

4602:   if (incall) return(0);
4603:   incall = PETSC_TRUE;

4605:   /* All user-provided viewers are called first, if they exist. */
4606:   for (i=0; i<snes->numberreasonviews; i++) {
4607:     (*snes->reasonview[i])(snes,snes->reasonviewcontext[i]);
4608:   }

4610:   /* Call PETSc default routine if users ask for it */
4611:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4612:   if (flg) {
4613:     PetscViewerPushFormat(viewer,format);
4614:     SNESConvergedReasonView(snes,viewer);
4615:     PetscViewerPopFormat(viewer);
4616:     PetscViewerDestroy(&viewer);
4617:   }
4618:   incall = PETSC_FALSE;
4619:   return(0);
4620: }

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

4626:    Collective on SNES

4628:    Input Parameters:
4629: +  snes - the SNES context
4630: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4631: -  x - the solution vector.

4633:    Notes:
4634:    The user should initialize the vector,x, with the initial guess
4635:    for the nonlinear solve prior to calling SNESSolve().  In particular,
4636:    to employ an initial guess of zero, the user should explicitly set
4637:    this vector to zero by calling VecSet().

4639:    Level: beginner

4641: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution(),
4642:           SNESNewtonTRSetPreCheck(), SNESNewtonTRGetPreCheck(), SNESNewtonTRSetPostCheck(), SNESNewtonTRGetPostCheck(),
4643:           SNESLineSearchSetPostCheck(), SNESLineSearchGetPostCheck(), SNESLineSearchSetPreCheck(), SNESLineSearchGetPreCheck()
4644: @*/
4645: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4646: {
4647:   PetscErrorCode    ierr;
4648:   PetscBool         flg;
4649:   PetscInt          grid;
4650:   Vec               xcreated = NULL;
4651:   DM                dm;


4660:   /* High level operations using the nonlinear solver */
4661:   {
4662:     PetscViewer       viewer;
4663:     PetscViewerFormat format;
4664:     PetscInt          num;
4665:     PetscBool         flg;
4666:     static PetscBool  incall = PETSC_FALSE;

4668:     if (!incall) {
4669:       /* Estimate the convergence rate of the discretization */
4670:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes),((PetscObject)snes)->options, ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4671:       if (flg) {
4672:         PetscConvEst conv;
4673:         DM           dm;
4674:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4675:         PetscInt     Nf;

4677:         incall = PETSC_TRUE;
4678:         SNESGetDM(snes, &dm);
4679:         DMGetNumFields(dm, &Nf);
4680:         PetscCalloc1(Nf, &alpha);
4681:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4682:         PetscConvEstSetSolver(conv, (PetscObject) snes);
4683:         PetscConvEstSetFromOptions(conv);
4684:         PetscConvEstSetUp(conv);
4685:         PetscConvEstGetConvRate(conv, alpha);
4686:         PetscViewerPushFormat(viewer, format);
4687:         PetscConvEstRateView(conv, alpha, viewer);
4688:         PetscViewerPopFormat(viewer);
4689:         PetscViewerDestroy(&viewer);
4690:         PetscConvEstDestroy(&conv);
4691:         PetscFree(alpha);
4692:         incall = PETSC_FALSE;
4693:       }
4694:       /* Adaptively refine the initial grid */
4695:       num  = 1;
4696:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);
4697:       if (flg) {
4698:         DMAdaptor adaptor;

4700:         incall = PETSC_TRUE;
4701:         DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor);
4702:         DMAdaptorSetSolver(adaptor, snes);
4703:         DMAdaptorSetSequenceLength(adaptor, num);
4704:         DMAdaptorSetFromOptions(adaptor);
4705:         DMAdaptorSetUp(adaptor);
4706:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4707:         DMAdaptorDestroy(&adaptor);
4708:         incall = PETSC_FALSE;
4709:       }
4710:       /* Use grid sequencing to adapt */
4711:       num  = 0;
4712:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4713:       if (num) {
4714:         DMAdaptor adaptor;

4716:         incall = PETSC_TRUE;
4717:         DMAdaptorCreate(PetscObjectComm((PetscObject)snes), &adaptor);
4718:         DMAdaptorSetSolver(adaptor, snes);
4719:         DMAdaptorSetSequenceLength(adaptor, num);
4720:         DMAdaptorSetFromOptions(adaptor);
4721:         DMAdaptorSetUp(adaptor);
4722:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4723:         DMAdaptorDestroy(&adaptor);
4724:         incall = PETSC_FALSE;
4725:       }
4726:     }
4727:   }
4728:   if (!x) {
4729:     SNESGetDM(snes,&dm);
4730:     DMCreateGlobalVector(dm,&xcreated);
4731:     x    = xcreated;
4732:   }
4733:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4738:     /* set solution vector */
4739:     if (!grid) {PetscObjectReference((PetscObject)x);}
4740:     VecDestroy(&snes->vec_sol);
4741:     snes->vec_sol = x;
4742:     SNESGetDM(snes,&dm);

4744:     /* set affine vector if provided */
4745:     if (b) { PetscObjectReference((PetscObject)b); }
4746:     VecDestroy(&snes->vec_rhs);
4747:     snes->vec_rhs = b;

4749:     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");
4750:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4751:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4752:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4753:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4754:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4755:     }
4756:     DMShellSetGlobalVector(dm,snes->vec_sol);
4757:     SNESSetUp(snes);

4759:     if (!grid) {
4760:       if (snes->ops->computeinitialguess) {
4761:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4762:       }
4763:     }

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

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

4774:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4775:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

4777:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg);
4778:     if (flg && !PetscPreLoadingOn) { SNESTestLocalMin(snes); }
4779:     /* Call converged reason views. This may involve user-provided viewers as well */
4780:     SNESConvergedReasonViewFromOptions(snes);

4782:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4783:     if (snes->reason < 0) break;
4784:     if (grid <  snes->gridsequence) {
4785:       DM  fine;
4786:       Vec xnew;
4787:       Mat interp;

4789:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4790:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4791:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4792:       DMCreateGlobalVector(fine,&xnew);
4793:       MatInterpolate(interp,x,xnew);
4794:       DMInterpolate(snes->dm,interp,fine);
4795:       MatDestroy(&interp);
4796:       x    = xnew;

4798:       SNESReset(snes);
4799:       SNESSetDM(snes,fine);
4800:       SNESResetFromOptions(snes);
4801:       DMDestroy(&fine);
4802:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4803:     }
4804:   }
4805:   SNESViewFromOptions(snes,NULL,"-snes_view");
4806:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");
4807:   DMMonitor(snes->dm);

4809:   VecDestroy(&xcreated);
4810:   PetscObjectSAWsBlock((PetscObject)snes);
4811:   return(0);
4812: }

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

4816: /*@C
4817:    SNESSetType - Sets the method for the nonlinear solver.

4819:    Collective on SNES

4821:    Input Parameters:
4822: +  snes - the SNES context
4823: -  type - a known method

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

4829:    Notes:
4830:    See "petsc/include/petscsnes.h" for available methods (for instance)
4831: +    SNESNEWTONLS - Newton's method with line search
4832:      (systems of nonlinear equations)
4833: -    SNESNEWTONTR - Newton's method with trust region
4834:      (systems of nonlinear equations)

4836:   Normally, it is best to use the SNESSetFromOptions() command and then
4837:   set the SNES solver type from the options database rather than by using
4838:   this routine.  Using the options database provides the user with
4839:   maximum flexibility in evaluating the many nonlinear solvers.
4840:   The SNESSetType() routine is provided for those situations where it
4841:   is necessary to set the nonlinear solver independently of the command
4842:   line or options database.  This might be the case, for example, when
4843:   the choice of solver changes during the execution of the program,
4844:   and the user's application is taking responsibility for choosing the
4845:   appropriate method.

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

4851:   Level: intermediate

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

4855: @*/
4856: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4857: {
4858:   PetscErrorCode ierr,(*r)(SNES);
4859:   PetscBool      match;


4865:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4866:   if (match) return(0);

4868:   PetscFunctionListFind(SNESList,type,&r);
4869:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4870:   /* Destroy the previous private SNES context */
4871:   if (snes->ops->destroy) {
4872:     (*(snes)->ops->destroy)(snes);
4873:     snes->ops->destroy = NULL;
4874:   }
4875:   /* Reinitialize function pointers in SNESOps structure */
4876:   snes->ops->setup          = NULL;
4877:   snes->ops->solve          = NULL;
4878:   snes->ops->view           = NULL;
4879:   snes->ops->setfromoptions = NULL;
4880:   snes->ops->destroy        = NULL;

4882:   /* It may happen the user has customized the line search before calling SNESSetType */
4883:   if (((PetscObject)snes)->type_name) {
4884:     SNESLineSearchDestroy(&snes->linesearch);
4885:   }

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

4890:   PetscObjectChangeTypeName((PetscObject)snes,type);
4891:   (*r)(snes);
4892:   return(0);
4893: }

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

4898:    Not Collective

4900:    Input Parameter:
4901: .  snes - nonlinear solver context

4903:    Output Parameter:
4904: .  type - SNES method (a character string)

4906:    Level: intermediate

4908: @*/
4909: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4910: {
4914:   *type = ((PetscObject)snes)->type_name;
4915:   return(0);
4916: }

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

4921:   Logically Collective on SNES

4923:   Input Parameters:
4924: + snes - the SNES context obtained from SNESCreate()
4925: - u    - the solution vector

4927:   Level: beginner

4929: @*/
4930: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4931: {
4932:   DM             dm;

4938:   PetscObjectReference((PetscObject) u);
4939:   VecDestroy(&snes->vec_sol);

4941:   snes->vec_sol = u;

4943:   SNESGetDM(snes, &dm);
4944:   DMShellSetGlobalVector(dm, u);
4945:   return(0);
4946: }

4948: /*@
4949:    SNESGetSolution - Returns the vector where the approximate solution is
4950:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4954:    Input Parameter:
4955: .  snes - the SNES context

4957:    Output Parameter:
4958: .  x - the solution

4960:    Level: intermediate

4962: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4963: @*/
4964: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4965: {
4969:   *x = snes->vec_sol;
4970:   return(0);
4971: }

4973: /*@
4974:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4975:    stored.

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

4979:    Input Parameter:
4980: .  snes - the SNES context

4982:    Output Parameter:
4983: .  x - the solution update

4985:    Level: advanced

4987: .seealso: SNESGetSolution(), SNESGetFunction()
4988: @*/
4989: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4990: {
4994:   *x = snes->vec_sol_update;
4995:   return(0);
4996: }

4998: /*@C
4999:    SNESGetFunction - Returns the vector where the function is stored.

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

5003:    Input Parameter:
5004: .  snes - the SNES context

5006:    Output Parameters:
5007: +  r - the vector that is used to store residuals (or NULL if you don't want it)
5008: .  f - the function (or NULL if you don't want it); see SNESFunction for calling sequence details
5009: -  ctx - the function context (or NULL if you don't want it)

5011:    Level: advanced

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

5015: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
5016: @*/
5017: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
5018: {
5020:   DM             dm;

5024:   if (r) {
5025:     if (!snes->vec_func) {
5026:       if (snes->vec_rhs) {
5027:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
5028:       } else if (snes->vec_sol) {
5029:         VecDuplicate(snes->vec_sol,&snes->vec_func);
5030:       } else if (snes->dm) {
5031:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
5032:       }
5033:     }
5034:     *r = snes->vec_func;
5035:   }
5036:   SNESGetDM(snes,&dm);
5037:   DMSNESGetFunction(dm,f,ctx);
5038:   return(0);
5039: }

5041: /*@C
5042:    SNESGetNGS - Returns the NGS function and context.

5044:    Input Parameter:
5045: .  snes - the SNES context

5047:    Output Parameters:
5048: +  f - the function (or NULL) see SNESNGSFunction for details
5049: -  ctx    - the function context (or NULL)

5051:    Level: advanced

5053: .seealso: SNESSetNGS(), SNESGetFunction()
5054: @*/

5056: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
5057: {
5059:   DM             dm;

5063:   SNESGetDM(snes,&dm);
5064:   DMSNESGetNGS(dm,f,ctx);
5065:   return(0);
5066: }

5068: /*@C
5069:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
5070:    SNES options in the database.

5072:    Logically Collective on SNES

5074:    Input Parameters:
5075: +  snes - the SNES context
5076: -  prefix - the prefix to prepend to all option names

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

5082:    Level: advanced

5084: .seealso: SNESSetFromOptions()
5085: @*/
5086: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
5087: {

5092:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
5093:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
5094:   if (snes->linesearch) {
5095:     SNESGetLineSearch(snes,&snes->linesearch);
5096:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
5097:   }
5098:   KSPSetOptionsPrefix(snes->ksp,prefix);
5099:   return(0);
5100: }

5102: /*@C
5103:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
5104:    SNES options in the database.

5106:    Logically Collective on SNES

5108:    Input Parameters:
5109: +  snes - the SNES context
5110: -  prefix - the prefix to prepend to all option names

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

5116:    Level: advanced

5118: .seealso: SNESGetOptionsPrefix()
5119: @*/
5120: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
5121: {

5126:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
5127:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
5128:   if (snes->linesearch) {
5129:     SNESGetLineSearch(snes,&snes->linesearch);
5130:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
5131:   }
5132:   KSPAppendOptionsPrefix(snes->ksp,prefix);
5133:   return(0);
5134: }

5136: /*@C
5137:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
5138:    SNES options in the database.

5140:    Not Collective

5142:    Input Parameter:
5143: .  snes - the SNES context

5145:    Output Parameter:
5146: .  prefix - pointer to the prefix string used

5148:    Notes:
5149:     On the fortran side, the user should pass in a string 'prefix' of
5150:    sufficient length to hold the prefix.

5152:    Level: advanced

5154: .seealso: SNESAppendOptionsPrefix()
5155: @*/
5156: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
5157: {

5162:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
5163:   return(0);
5164: }

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

5169:    Not collective

5171:    Input Parameters:
5172: +  name_solver - name of a new user-defined solver
5173: -  routine_create - routine to create method context

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

5178:    Sample usage:
5179: .vb
5180:    SNESRegister("my_solver",MySolverCreate);
5181: .ve

5183:    Then, your solver can be chosen with the procedural interface via
5184: $     SNESSetType(snes,"my_solver")
5185:    or at runtime via the option
5186: $     -snes_type my_solver

5188:    Level: advanced

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

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

5194:   Level: advanced
5195: @*/
5196: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
5197: {

5201:   SNESInitializePackage();
5202:   PetscFunctionListAdd(&SNESList,sname,function);
5203:   return(0);
5204: }

5206: PetscErrorCode  SNESTestLocalMin(SNES snes)
5207: {
5209:   PetscInt       N,i,j;
5210:   Vec            u,uh,fh;
5211:   PetscScalar    value;
5212:   PetscReal      norm;

5215:   SNESGetSolution(snes,&u);
5216:   VecDuplicate(u,&uh);
5217:   VecDuplicate(u,&fh);

5219:   /* currently only works for sequential */
5220:   PetscPrintf(PetscObjectComm((PetscObject)snes),"Testing FormFunction() for local min\n");
5221:   VecGetSize(u,&N);
5222:   for (i=0; i<N; i++) {
5223:     VecCopy(u,uh);
5224:     PetscPrintf(PetscObjectComm((PetscObject)snes),"i = %D\n",i);
5225:     for (j=-10; j<11; j++) {
5226:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
5227:       VecSetValue(uh,i,value,ADD_VALUES);
5228:       SNESComputeFunction(snes,uh,fh);
5229:       VecNorm(fh,NORM_2,&norm);
5230:       PetscPrintf(PetscObjectComm((PetscObject)snes),"       j norm %D %18.16e\n",j,norm);
5231:       value = -value;
5232:       VecSetValue(uh,i,value,ADD_VALUES);
5233:     }
5234:   }
5235:   VecDestroy(&uh);
5236:   VecDestroy(&fh);
5237:   return(0);
5238: }

5240: /*@
5241:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
5242:    computing relative tolerance for linear solvers within an inexact
5243:    Newton method.

5245:    Logically Collective on SNES

5247:    Input Parameters:
5248: +  snes - SNES context
5249: -  flag - PETSC_TRUE or PETSC_FALSE

5251:     Options Database:
5252: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
5253: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
5254: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
5255: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
5256: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
5257: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
5258: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
5259: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

5261:    Notes:
5262:    Currently, the default is to use a constant relative tolerance for
5263:    the inner linear solvers.  Alternatively, one can use the
5264:    Eisenstat-Walker method, where the relative convergence tolerance
5265:    is reset at each Newton iteration according progress of the nonlinear
5266:    solver.

5268:    Level: advanced

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

5274: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
5275: @*/
5276: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
5277: {
5281:   snes->ksp_ewconv = flag;
5282:   return(0);
5283: }

5285: /*@
5286:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
5287:    for computing relative tolerance for linear solvers within an
5288:    inexact Newton method.

5290:    Not Collective

5292:    Input Parameter:
5293: .  snes - SNES context

5295:    Output Parameter:
5296: .  flag - PETSC_TRUE or PETSC_FALSE

5298:    Notes:
5299:    Currently, the default is to use a constant relative tolerance for
5300:    the inner linear solvers.  Alternatively, one can use the
5301:    Eisenstat-Walker method, where the relative convergence tolerance
5302:    is reset at each Newton iteration according progress of the nonlinear
5303:    solver.

5305:    Level: advanced

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

5311: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
5312: @*/
5313: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
5314: {
5318:   *flag = snes->ksp_ewconv;
5319:   return(0);
5320: }

5322: /*@
5323:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
5324:    convergence criteria for the linear solvers within an inexact
5325:    Newton method.

5327:    Logically Collective on SNES

5329:    Input Parameters:
5330: +    snes - SNES context
5331: .    version - version 1, 2 (default is 2) or 3
5332: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5333: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5334: .    gamma - multiplicative factor for version 2 rtol computation
5335:              (0 <= gamma2 <= 1)
5336: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5337: .    alpha2 - power for safeguard
5338: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5340:    Note:
5341:    Version 3 was contributed by Luis Chacon, June 2006.

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

5345:    Level: advanced

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

5352: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
5353: @*/
5354: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
5355: {
5356:   SNESKSPEW *kctx;

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

5370:   if (version != PETSC_DEFAULT)   kctx->version   = version;
5371:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
5372:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
5373:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
5374:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
5375:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
5376:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

5378:   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);
5379:   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);
5380:   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);
5381:   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);
5382:   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);
5383:   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);
5384:   return(0);
5385: }

5387: /*@
5388:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5389:    convergence criteria for the linear solvers within an inexact
5390:    Newton method.

5392:    Not Collective

5394:    Input Parameter:
5395: .    snes - SNES context

5397:    Output Parameters:
5398: +    version - version 1, 2 (default is 2) or 3
5399: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5400: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5401: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5402: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5403: .    alpha2 - power for safeguard
5404: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5406:    Level: advanced

5408: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
5409: @*/
5410: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
5411: {
5412:   SNESKSPEW *kctx;

5416:   kctx = (SNESKSPEW*)snes->kspconvctx;
5417:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5418:   if (version)   *version   = kctx->version;
5419:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
5420:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
5421:   if (gamma)     *gamma     = kctx->gamma;
5422:   if (alpha)     *alpha     = kctx->alpha;
5423:   if (alpha2)    *alpha2    = kctx->alpha2;
5424:   if (threshold) *threshold = kctx->threshold;
5425:   return(0);
5426: }

5428:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5429: {
5431:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5432:   PetscReal      rtol  = PETSC_DEFAULT,stol;

5435:   if (!snes->ksp_ewconv) return(0);
5436:   if (!snes->iter) {
5437:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5438:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
5439:   }
5440:   else {
5441:     if (kctx->version == 1) {
5442:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
5443:       if (rtol < 0.0) rtol = -rtol;
5444:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5445:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5446:     } else if (kctx->version == 2) {
5447:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5448:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5449:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5450:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5451:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5452:       /* safeguard: avoid sharp decrease of rtol */
5453:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5454:       stol = PetscMax(rtol,stol);
5455:       rtol = PetscMin(kctx->rtol_0,stol);
5456:       /* safeguard: avoid oversolving */
5457:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5458:       stol = PetscMax(rtol,stol);
5459:       rtol = PetscMin(kctx->rtol_0,stol);
5460:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
5461:   }
5462:   /* safeguard: avoid rtol greater than one */
5463:   rtol = PetscMin(rtol,kctx->rtol_max);
5464:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
5465:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
5466:   return(0);
5467: }

5469: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5470: {
5472:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5473:   PCSide         pcside;
5474:   Vec            lres;

5477:   if (!snes->ksp_ewconv) return(0);
5478:   KSPGetTolerances(ksp,&kctx->rtol_last,NULL,NULL,NULL);
5479:   kctx->norm_last = snes->norm;
5480:   if (kctx->version == 1) {
5481:     PC        pc;
5482:     PetscBool isNone;

5484:     KSPGetPC(ksp, &pc);
5485:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
5486:     KSPGetPCSide(ksp,&pcside);
5487:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
5488:       /* KSP residual is true linear residual */
5489:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
5490:     } else {
5491:       /* KSP residual is preconditioned residual */
5492:       /* compute true linear residual norm */
5493:       VecDuplicate(b,&lres);
5494:       MatMult(snes->jacobian,x,lres);
5495:       VecAYPX(lres,-1.0,b);
5496:       VecNorm(lres,NORM_2,&kctx->lresid_last);
5497:       VecDestroy(&lres);
5498:     }
5499:   }
5500:   return(0);
5501: }

5503: /*@
5504:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

5508:    Input Parameter:
5509: .  snes - the SNES context

5511:    Output Parameter:
5512: .  ksp - the KSP context

5514:    Notes:
5515:    The user can then directly manipulate the KSP context to set various
5516:    options, etc.  Likewise, the user can then extract and manipulate the
5517:    PC contexts as well.

5519:    Level: beginner

5521: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5522: @*/
5523: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
5524: {


5531:   if (!snes->ksp) {
5532:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
5533:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
5534:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

5539:     KSPMonitorSetFromOptions(snes->ksp, "-snes_monitor_ksp", "snes_preconditioned_residual", snes);
5540:     PetscObjectSetOptions((PetscObject)snes->ksp,((PetscObject)snes)->options);
5541:   }
5542:   *ksp = snes->ksp;
5543:   return(0);
5544: }

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

5550:    Logically Collective on SNES

5552:    Input Parameters:
5553: +  snes - the nonlinear solver context
5554: -  dm - the dm, cannot be NULL

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

5561:    Level: intermediate

5563: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
5564: @*/
5565: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5566: {
5568:   KSP            ksp;
5569:   DMSNES         sdm;

5574:   PetscObjectReference((PetscObject)dm);
5575:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5576:     if (snes->dm->dmsnes && !dm->dmsnes) {
5577:       DMCopyDMSNES(snes->dm,dm);
5578:       DMGetDMSNES(snes->dm,&sdm);
5579:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5580:     }
5581:     DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5582:     DMDestroy(&snes->dm);
5583:   }
5584:   snes->dm     = dm;
5585:   snes->dmAuto = PETSC_FALSE;

5587:   SNESGetKSP(snes,&ksp);
5588:   KSPSetDM(ksp,dm);
5589:   KSPSetDMActive(ksp,PETSC_FALSE);
5590:   if (snes->npc) {
5591:     SNESSetDM(snes->npc, snes->dm);
5592:     SNESSetNPCSide(snes,snes->npcside);
5593:   }
5594:   return(0);
5595: }

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

5600:    Not Collective but DM obtained is parallel on SNES

5602:    Input Parameter:
5603: . snes - the preconditioner context

5605:    Output Parameter:
5606: .  dm - the dm

5608:    Level: intermediate

5610: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5611: @*/
5612: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5613: {

5618:   if (!snes->dm) {
5619:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5620:     snes->dmAuto = PETSC_TRUE;
5621:   }
5622:   *dm = snes->dm;
5623:   return(0);
5624: }

5626: /*@
5627:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5629:   Collective on SNES

5631:   Input Parameters:
5632: + snes - iterative context obtained from SNESCreate()
5633: - pc   - the preconditioner object

5635:   Notes:
5636:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5637:   to configure it using the API).

5639:   Level: developer

5641: .seealso: SNESGetNPC(), SNESHasNPC()
5642: @*/
5643: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5644: {

5651:   PetscObjectReference((PetscObject) pc);
5652:   SNESDestroy(&snes->npc);
5653:   snes->npc = pc;
5654:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5655:   return(0);
5656: }

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

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

5663:   Input Parameter:
5664: . snes - iterative context obtained from SNESCreate()

5666:   Output Parameter:
5667: . pc - preconditioner context

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

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

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

5678:   Level: developer

5680: .seealso: SNESSetNPC(), SNESHasNPC(), SNES, SNESCreate()
5681: @*/
5682: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5683: {
5685:   const char     *optionsprefix;

5690:   if (!snes->npc) {
5691:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5692:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5693:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5694:     SNESGetOptionsPrefix(snes,&optionsprefix);
5695:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5696:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5697:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5698:   }
5699:   *pc = snes->npc;
5700:   return(0);
5701: }

5703: /*@
5704:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5706:   Not Collective

5708:   Input Parameter:
5709: . snes - iterative context obtained from SNESCreate()

5711:   Output Parameter:
5712: . has_npc - whether the SNES has an NPC or not

5714:   Level: developer

5716: .seealso: SNESSetNPC(), SNESGetNPC()
5717: @*/
5718: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5719: {
5722:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5723:   return(0);
5724: }

5726: /*@
5727:     SNESSetNPCSide - Sets the preconditioning side.

5729:     Logically Collective on SNES

5731:     Input Parameter:
5732: .   snes - iterative context obtained from SNESCreate()

5734:     Output Parameter:
5735: .   side - the preconditioning side, where side is one of
5736: .vb
5737:       PC_LEFT - left preconditioning
5738:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5739: .ve

5741:     Options Database Keys:
5742: .   -snes_pc_side <right,left>

5744:     Notes:
5745:     SNESNRICHARDSON and SNESNCG only support left preconditioning.

5747:     Level: intermediate

5749: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5750: @*/
5751: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5752: {
5756:   snes->npcside= side;
5757:   return(0);
5758: }

5760: /*@
5761:     SNESGetNPCSide - Gets the preconditioning side.

5763:     Not Collective

5765:     Input Parameter:
5766: .   snes - iterative context obtained from SNESCreate()

5768:     Output Parameter:
5769: .   side - the preconditioning side, where side is one of
5770: .vb
5771:       PC_LEFT - left preconditioning
5772:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5773: .ve

5775:     Level: intermediate

5777: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5778: @*/
5779: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5780: {
5784:   *side = snes->npcside;
5785:   return(0);
5786: }

5788: /*@
5789:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5791:   Collective on SNES

5793:   Input Parameters:
5794: + snes - iterative context obtained from SNESCreate()
5795: - linesearch   - the linesearch object

5797:   Notes:
5798:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5799:   to configure it using the API).

5801:   Level: developer

5803: .seealso: SNESGetLineSearch()
5804: @*/
5805: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5806: {

5813:   PetscObjectReference((PetscObject) linesearch);
5814:   SNESLineSearchDestroy(&snes->linesearch);

5816:   snes->linesearch = linesearch;

5818:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5819:   return(0);
5820: }

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

5826:   Not Collective

5828:   Input Parameter:
5829: . snes - iterative context obtained from SNESCreate()

5831:   Output Parameter:
5832: . linesearch - linesearch context

5834:   Level: beginner

5836: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5837: @*/
5838: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5839: {
5841:   const char     *optionsprefix;

5846:   if (!snes->linesearch) {
5847:     SNESGetOptionsPrefix(snes, &optionsprefix);
5848:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5849:     SNESLineSearchSetSNES(snes->linesearch, snes);
5850:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5851:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5852:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5853:   }
5854:   *linesearch = snes->linesearch;
5855:   return(0);
5856: }