Actual source code: snes.c

petsc-master 2018-06-16
Report Typos and Errors

  2:  #include <petsc/private/snesimpl.h>
  3:  #include <petscdmshell.h>
  4:  #include <petscdraw.h>
  5:  #include <petscds.h>
  6:  #include <petscdmadaptor.h>
  7:  #include <petscconvest.h>

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

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

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

 19:    Logically Collective on SNES

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

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

 28:    Level: intermediate

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

 34: .keywords: SNES, set, initial guess, nonzero

 36: .seealso: SNESGetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIFNotConverged()
 37: @*/
 38: PetscErrorCode  SNESSetErrorIfNotConverged(SNES snes,PetscBool flg)
 39: {
 43:   snes->errorifnotconverged = flg;
 44:   return(0);
 45: }

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

 50:    Not Collective

 52:    Input Parameter:
 53: .  snes - iterative context obtained from SNESCreate()

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

 58:    Level: intermediate

 60: .keywords: SNES, set, initial guess, nonzero

 62: .seealso:  SNESSetErrorIfNotConverged(), KSPGetErrorIfNotConverged(), KSPSetErrorIFNotConverged()
 63: @*/
 64: PetscErrorCode  SNESGetErrorIfNotConverged(SNES snes,PetscBool  *flag)
 65: {
 69:   *flag = snes->errorifnotconverged;
 70:   return(0);
 71: }

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

 76:    Logically Collective on SNES

 78:     Input Parameters:
 79: +   snes - the shell SNES
 80: -   flg - is the residual computed?

 82:    Level: advanced

 84: .seealso: SNESGetAlwaysComputesFinalResidual()
 85: @*/
 86: PetscErrorCode  SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
 87: {
 90:   snes->alwayscomputesfinalresidual = flg;
 91:   return(0);
 92: }

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

 97:    Logically Collective on SNES

 99:     Input Parameter:
100: .   snes - the shell SNES

102:     Output Parameter:
103: .   flg - is the residual computed?

105:    Level: advanced

107: .seealso: SNESSetAlwaysComputesFinalResidual()
108: @*/
109: PetscErrorCode  SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
110: {
113:   *flg = snes->alwayscomputesfinalresidual;
114:   return(0);
115: }

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

121:    Logically Collective on SNES

123:    Input Parameters:
124: .  snes - the SNES context

126:    Level: advanced

128: .keywords: SNES, view

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

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

144:    Logically Collective on SNES

146:    Input Parameters:
147: .  snes - the SNES context

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

152:    Level: advanced

154: .keywords: SNES, view

156: .seealso: SNESSetFunctionDomainError(), SNESComputeFunction()
157: @*/
158: PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
159: {
163:   *domainerror = snes->domainerror;
164:   return(0);
165: }

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

170:   Collective on PetscViewer

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

177:    Level: intermediate

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

182:   Notes for advanced users:
183:   Most users should not need to know the details of the binary storage
184:   format, since SNESLoad() and TSView() completely hide these details.
185:   But for anyone who's interested, the standard binary matrix storage
186:   format is
187: .vb
188:      has not yet been determined
189: .ve

191: .seealso: PetscViewerBinaryOpen(), SNESView(), MatLoad(), VecLoad()
192: @*/
193: PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
194: {
196:   PetscBool      isbinary;
197:   PetscInt       classid;
198:   char           type[256];
199:   KSP            ksp;
200:   DM             dm;
201:   DMSNES         dmsnes;

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

209:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
210:   if (classid != SNES_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
211:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
212:   SNESSetType(snes, type);
213:   if (snes->ops->load) {
214:     (*snes->ops->load)(snes,viewer);
215:   }
216:   SNESGetDM(snes,&dm);
217:   DMGetDMSNES(dm,&dmsnes);
218:   DMSNESLoad(dmsnes,viewer);
219:   SNESGetKSP(snes,&ksp);
220:   KSPLoad(ksp,viewer);
221:   return(0);
222: }

224:  #include <petscdraw.h>
225: #if defined(PETSC_HAVE_SAWS)
226:  #include <petscviewersaws.h>
227: #endif

229: /*@C
230:    SNESView - Prints the SNES data structure.

232:    Collective on SNES

234:    Input Parameters:
235: +  SNES - the SNES context
236: -  viewer - visualization context

238:    Options Database Key:
239: .  -snes_view - Calls SNESView() at end of SNESSolve()

241:    Notes:
242:    The available visualization contexts include
243: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
244: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
245:          output where only the first processor opens
246:          the file.  All other processors send their
247:          data to the first processor to print.

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

252:    Level: beginner

254: .keywords: SNES, view

256: .seealso: PetscViewerASCIIOpen()
257: @*/
258: PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
259: {
260:   SNESKSPEW      *kctx;
262:   KSP            ksp;
263:   SNESLineSearch linesearch;
264:   PetscBool      iascii,isstring,isbinary,isdraw;
265:   DMSNES         dmsnes;
266: #if defined(PETSC_HAVE_SAWS)
267:   PetscBool      issaws;
268: #endif

272:   if (!viewer) {
273:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer);
274:   }

278:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
279:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
280:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
281:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
282: #if defined(PETSC_HAVE_SAWS)
283:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
284: #endif
285:   if (iascii) {
286:     SNESNormSchedule normschedule;
287:     DM               dm;
288:     PetscErrorCode   (*cJ)(SNES,Vec,Mat,Mat,void*);
289:     void             *ctx;
290:     PetscInt         tabs;

292:     PetscViewerASCIIGetTab(viewer, &tabs);
293:     PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);
294:     PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer);
295:     if (!snes->setupcalled) {
296:       PetscViewerASCIIPrintf(viewer,"  SNES has not been set up so information may be incomplete\n");
297:     }
298:     if (snes->ops->view) {
299:       PetscViewerASCIIPushTab(viewer);
300:       (*snes->ops->view)(snes,viewer);
301:       PetscViewerASCIIPopTab(viewer);
302:     }
303:     PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, maximum function evaluations=%D\n",snes->max_its,snes->max_funcs);
304:     PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol);
305:     if (snes->usesksp) {
306:       PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",snes->linear_its);
307:     }
308:     PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%D\n",snes->nfuncs);
309:     SNESGetNormSchedule(snes, &normschedule);
310:     if (normschedule > 0) {PetscViewerASCIIPrintf(viewer,"  norm schedule %s\n",SNESNormSchedules[normschedule]);}
311:     if (snes->gridsequence) {
312:       PetscViewerASCIIPrintf(viewer,"  total number of grid sequence refinements=%D\n",snes->gridsequence);
313:     }
314:     if (snes->ksp_ewconv) {
315:       kctx = (SNESKSPEW*)snes->kspconvctx;
316:       if (kctx) {
317:         PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %D)\n",kctx->version);
318:         PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold);
319:         PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2);
320:       }
321:     }
322:     if (snes->lagpreconditioner == -1) {
323:       PetscViewerASCIIPrintf(viewer,"  Preconditioned is never rebuilt\n");
324:     } else if (snes->lagpreconditioner > 1) {
325:       PetscViewerASCIIPrintf(viewer,"  Preconditioned is rebuilt every %D new Jacobians\n",snes->lagpreconditioner);
326:     }
327:     if (snes->lagjacobian == -1) {
328:       PetscViewerASCIIPrintf(viewer,"  Jacobian is never rebuilt\n");
329:     } else if (snes->lagjacobian > 1) {
330:       PetscViewerASCIIPrintf(viewer,"  Jacobian is rebuilt every %D SNES iterations\n",snes->lagjacobian);
331:     }
332:     SNESGetDM(snes,&dm);
333:     DMSNESGetJacobian(dm,&cJ,&ctx);
334:     if (cJ == SNESComputeJacobianDefault) {
335:       PetscViewerASCIIPrintf(viewer,"  Jacobian is built using finite differences one column at a time\n");
336:     } else if (cJ == SNESComputeJacobianDefaultColor) {
337:       PetscViewerASCIIPrintf(viewer,"  Jacobian is built using finite differences with coloring\n");
338:     }
339:     PetscViewerASCIISetTab(viewer, tabs);
340:   } else if (isstring) {
341:     const char *type;
342:     SNESGetType(snes,&type);
343:     PetscViewerStringSPrintf(viewer," %-3.3s",type);
344:   } else if (isbinary) {
345:     PetscInt    classid = SNES_FILE_CLASSID;
346:     MPI_Comm    comm;
347:     PetscMPIInt rank;
348:     char        type[256];

350:     PetscObjectGetComm((PetscObject)snes,&comm);
351:     MPI_Comm_rank(comm,&rank);
352:     if (!rank) {
353:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
354:       PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));
355:       PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR,PETSC_FALSE);
356:     }
357:     if (snes->ops->view) {
358:       (*snes->ops->view)(snes,viewer);
359:     }
360:   } else if (isdraw) {
361:     PetscDraw draw;
362:     char      str[36];
363:     PetscReal x,y,bottom,h;

365:     PetscViewerDrawGetDraw(viewer,0,&draw);
366:     PetscDrawGetCurrentPoint(draw,&x,&y);
367:     PetscStrncpy(str,"SNES: ",sizeof(str));
368:     PetscStrlcat(str,((PetscObject)snes)->type_name,sizeof(str));
369:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h);
370:     bottom = y - h;
371:     PetscDrawPushCurrentPoint(draw,x,bottom);
372:     if (snes->ops->view) {
373:       (*snes->ops->view)(snes,viewer);
374:     }
375: #if defined(PETSC_HAVE_SAWS)
376:   } else if (issaws) {
377:     PetscMPIInt rank;
378:     const char *name;

380:     PetscObjectGetName((PetscObject)snes,&name);
381:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
382:     if (!((PetscObject)snes)->amsmem && !rank) {
383:       char       dir[1024];

385:       PetscObjectViewSAWs((PetscObject)snes,viewer);
386:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);
387:       PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
388:       if (!snes->conv_hist) {
389:         SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE);
390:       }
391:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name);
392:       PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
393:     }
394: #endif
395:   }
396:   if (snes->linesearch) {
397:     SNESGetLineSearch(snes, &linesearch);
398:     SNESLineSearchView(linesearch, viewer);
399:   }
400:   if (snes->npc && snes->usesnpc) {
401:     SNESView(snes->npc, viewer);
402:   }
403:   PetscViewerASCIIPushTab(viewer);
404:   DMGetDMSNES(snes->dm,&dmsnes);
405:   DMSNESView(dmsnes, viewer);
406:   PetscViewerASCIIPopTab(viewer);
407:   if (snes->usesksp) {
408:     SNESGetKSP(snes,&ksp);
409:     KSPView(ksp,viewer);
410:   }
411:   if (isdraw) {
412:     PetscDraw draw;
413:     PetscViewerDrawGetDraw(viewer,0,&draw);
414:     PetscDrawPopCurrentPoint(draw);
415:   }
416:   return(0);
417: }

419: /*
420:   We retain a list of functions that also take SNES command
421:   line options. These are called at the end SNESSetFromOptions()
422: */
423: #define MAXSETFROMOPTIONS 5
424: static PetscInt numberofsetfromoptions;
425: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);

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

430:   Not Collective

432:   Input Parameter:
433: . snescheck - function that checks for options

435:   Level: developer

437: .seealso: SNESSetFromOptions()
438: @*/
439: PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
440: {
442:   if (numberofsetfromoptions >= MAXSETFROMOPTIONS) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %D allowed", MAXSETFROMOPTIONS);
443:   othersetfromoptions[numberofsetfromoptions++] = snescheck;
444:   return(0);
445: }

447: extern PetscErrorCode  SNESDefaultMatrixFreeCreate2(SNES,Vec,Mat*);

449: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
450: {
451:   Mat            J;
452:   KSP            ksp;
453:   PC             pc;
454:   PetscBool      match;
456:   MatNullSpace   nullsp;


461:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
462:     Mat A = snes->jacobian, B = snes->jacobian_pre;
463:     MatCreateVecs(A ? A : B, NULL,&snes->vec_func);
464:   }

466:   if (version == 1) {
467:     MatCreateSNESMF(snes,&J);
468:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
469:     MatSetFromOptions(J);
470:   } else if (version == 2) {
471:     if (!snes->vec_func) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
472: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
473:     SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J);
474: #else
475:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator rutines (version 2)");
476: #endif
477:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator rutines, only version 1 and 2");

479:   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
480:   if (snes->jacobian) {
481:     MatGetNullSpace(snes->jacobian,&nullsp);
482:     if (nullsp) {
483:       MatSetNullSpace(J,nullsp);
484:     }
485:   }

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

490:     /* This version replaces the user provided Jacobian matrix with a
491:        matrix-free version but still employs the user-provided preconditioner matrix. */
492:     SNESSetJacobian(snes,J,0,0,0);
493:   } else {
494:     /* This version replaces both the user-provided Jacobian and the user-
495:      provided preconditioner Jacobian with the default matrix free version. */
496:     if ((snes->npcside== PC_LEFT) && snes->npc) {
497:       if (!snes->jacobian){SNESSetJacobian(snes,J,0,0,0);}
498:     } else {
499:       SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,0);
500:     }
501:     /* Force no preconditioner */
502:     SNESGetKSP(snes,&ksp);
503:     KSPGetPC(ksp,&pc);
504:     PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&match);
505:     if (!match) {
506:       PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n");
507:       PCSetType(pc,PCNONE);
508:     }
509:   }
510:   MatDestroy(&J);
511:   return(0);
512: }

514: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
515: {
516:   SNES           snes = (SNES)ctx;
518:   Vec            Xfine,Xfine_named = NULL,Xcoarse;

521:   if (PetscLogPrintInfo) {
522:     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
523:     DMGetRefineLevel(dmfine,&finelevel);
524:     DMGetCoarsenLevel(dmfine,&fineclevel);
525:     DMGetRefineLevel(dmcoarse,&coarselevel);
526:     DMGetCoarsenLevel(dmcoarse,&coarseclevel);
527:     PetscInfo4(dmfine,"Restricting SNES solution vector from level %D-%D to level %D-%D\n",finelevel,fineclevel,coarselevel,coarseclevel);
528:   }
529:   if (dmfine == snes->dm) Xfine = snes->vec_sol;
530:   else {
531:     DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);
532:     Xfine = Xfine_named;
533:   }
534:   DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
535:   if (Inject) {
536:     MatRestrict(Inject,Xfine,Xcoarse);
537:   } else {
538:     MatRestrict(Restrict,Xfine,Xcoarse);
539:     VecPointwiseMult(Xcoarse,Xcoarse,Rscale);
540:   }
541:   DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
542:   if (Xfine_named) {DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);}
543:   return(0);
544: }

546: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
547: {

551:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
552:   return(0);
553: }

555: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
556:  * safely call SNESGetDM() in their residual evaluation routine. */
557: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
558: {
559:   SNES           snes = (SNES)ctx;
561:   Mat            Asave = A,Bsave = B;
562:   Vec            X,Xnamed = NULL;
563:   DM             dmsave;
564:   void           *ctxsave;
565:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*) = NULL;

568:   dmsave = snes->dm;
569:   KSPGetDM(ksp,&snes->dm);
570:   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
571:   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
572:     DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
573:     X    = Xnamed;
574:     SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave);
575:     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
576:     if (jac == SNESComputeJacobianDefaultColor) {
577:       SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,0);
578:     }
579:   }
580:   /* put the previous context back */

582:   SNESComputeJacobian(snes,X,A,B);
583:   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
584:     SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);
585:   }

587:   if (A != Asave || B != Bsave) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_SUP,"No support for changing matrices at this time");
588:   if (Xnamed) {
589:     DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
590:   }
591:   snes->dm = dmsave;
592:   return(0);
593: }

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

598:    Collective

600:    Input Arguments:
601: .  snes - snes to configure

603:    Level: developer

605: .seealso: SNESSetUp()
606: @*/
607: PetscErrorCode SNESSetUpMatrices(SNES snes)
608: {
610:   DM             dm;
611:   DMSNES         sdm;

614:   SNESGetDM(snes,&dm);
615:   DMGetDMSNES(dm,&sdm);
616:   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_PLIB,"DMSNES not properly configured");
617:   else if (!snes->jacobian && snes->mf) {
618:     Mat  J;
619:     void *functx;
620:     MatCreateSNESMF(snes,&J);
621:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
622:     MatSetFromOptions(J);
623:     SNESGetFunction(snes,NULL,NULL,&functx);
624:     SNESSetJacobian(snes,J,J,0,0);
625:     MatDestroy(&J);
626:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
627:     Mat J,B;
628:     MatCreateSNESMF(snes,&J);
629:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
630:     MatSetFromOptions(J);
631:     DMCreateMatrix(snes->dm,&B);
632:     /* sdm->computejacobian was already set to reach here */
633:     SNESSetJacobian(snes,J,B,NULL,NULL);
634:     MatDestroy(&J);
635:     MatDestroy(&B);
636:   } else if (!snes->jacobian_pre) {
637:     PetscDS   prob;
638:     Mat       J, B;
639:     PetscBool hasPrec = PETSC_FALSE;

641:     J    = snes->jacobian;
642:     DMGetDS(dm, &prob);
643:     if (prob) {PetscDSHasJacobianPreconditioner(prob, &hasPrec);}
644:     if (J)            {PetscObjectReference((PetscObject) J);}
645:     else if (hasPrec) {DMCreateMatrix(snes->dm, &J);}
646:     DMCreateMatrix(snes->dm, &B);
647:     SNESSetJacobian(snes, J ? J : B, B, NULL, NULL);
648:     MatDestroy(&J);
649:     MatDestroy(&B);
650:   }
651:   {
652:     KSP ksp;
653:     SNESGetKSP(snes,&ksp);
654:     KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);
655:     DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
656:   }
657:   return(0);
658: }

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

663:    Collective on SNES

665:    Input Parameters:
666: +  snes - SNES object you wish to monitor
667: .  name - the monitor type one is seeking
668: .  help - message indicating what monitoring is done
669: .  manual - manual page for the monitor
670: .  monitor - the monitor function
671: -  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

673:    Level: developer

675: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
676:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
677:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
678:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
679:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
680:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
681:           PetscOptionsFList(), PetscOptionsEList()
682: @*/
683: PetscErrorCode  SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
684: {
685:   PetscErrorCode    ierr;
686:   PetscViewer       viewer;
687:   PetscViewerFormat format;
688:   PetscBool         flg;

691:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,name,&viewer,&format,&flg);
692:   if (flg) {
693:     PetscViewerAndFormat *vf;
694:     PetscViewerAndFormatCreate(viewer,format,&vf);
695:     PetscObjectDereference((PetscObject)viewer);
696:     if (monitorsetup) {
697:       (*monitorsetup)(snes,vf);
698:     }
699:     SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
700:   }
701:   return(0);
702: }

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

707:    Collective on SNES

709:    Input Parameter:
710: .  snes - the SNES context

712:    Options Database Keys:
713: +  -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
714: .  -snes_stol - convergence tolerance in terms of the norm
715:                 of the change in the solution between steps
716: .  -snes_atol <abstol> - absolute tolerance of residual norm
717: .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
718: .  -snes_divergence_tolerance <divtol> - if the residual goes above divtol*rnorm0, exit with divergence
719: .  -snes_force_iteration <force> - force SNESSolve() to take at least one iteration
720: .  -snes_max_it <max_it> - maximum number of iterations
721: .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
722: .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
723: .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
724: .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
725: .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
726: .  -snes_trtol <trtol> - trust region tolerance
727: .  -snes_no_convergence_test - skip convergence test in nonlinear
728:                                solver; hence iterations will continue until max_it
729:                                or some other criterion is reached. Saves expense
730:                                of convergence test
731: .  -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
732: .  -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
733: .  -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
734: .  -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
735: .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
736: .  -snes_monitor_lg_range - plots residual norm at each iteration
737: .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
738: .  -snes_fd_color - use finite differences with coloring to compute Jacobian
739: .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
740: -  -snes_converged_reason - print the reason for convergence/divergence after each solve

742:     Options Database for Eisenstat-Walker method:
743: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
744: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
745: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
746: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
747: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
748: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
749: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
750: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

752:    Notes:
753:    To see all options, run your program with the -help option or consult
754:    Users-Manual: ch_snes

756:    Level: beginner

758: .keywords: SNES, nonlinear, set, options, database

760: .seealso: SNESSetOptionsPrefix()
761: @*/
762: PetscErrorCode  SNESSetFromOptions(SNES snes)
763: {
764:   PetscBool      flg,pcset,persist,set;
765:   PetscInt       i,indx,lag,grids;
766:   const char     *deft        = SNESNEWTONLS;
767:   const char     *convtests[] = {"default","skip"};
768:   SNESKSPEW      *kctx        = NULL;
769:   char           type[256], monfilename[PETSC_MAX_PATH_LEN];
771:   PCSide         pcside;
772:   const char     *optionsprefix;

776:   SNESRegisterAll();
777:   PetscObjectOptionsBegin((PetscObject)snes);
778:   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
779:   PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg);
780:   if (flg) {
781:     SNESSetType(snes,type);
782:   } else if (!((PetscObject)snes)->type_name) {
783:     SNESSetType(snes,deft);
784:   }
785:   PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL);
786:   PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL);

788:   PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL);
789:   PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL);
790:   PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL);
791:   PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL);
792:   PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL);
793:   PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL);
794:   PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL);
795:   PetscOptionsBool("-snes_force_iteration","Force SNESSolve() to take at least one iteration","SNESSetForceIteration",snes->forceiteration,&snes->forceiteration,NULL);

797:   PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg);
798:   if (flg) {
799:     SNESSetLagPreconditioner(snes,lag);
800:   }
801:   PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg);
802:   if (flg) {
803:     SNESSetLagPreconditionerPersists(snes,persist);
804:   }
805:   PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg);
806:   if (flg) {
807:     SNESSetLagJacobian(snes,lag);
808:   }
809:   PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg);
810:   if (flg) {
811:     SNESSetLagJacobianPersists(snes,persist);
812:   }

814:   PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg);
815:   if (flg) {
816:     SNESSetGridSequence(snes,grids);
817:   }

819:   PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,2,"default",&indx,&flg);
820:   if (flg) {
821:     switch (indx) {
822:     case 0: SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL); break;
823:     case 1: SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL);    break;
824:     }
825:   }

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

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

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

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

837:   PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL);
838:   PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL);
839:   PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL);
840:   PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL);
841:   PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL);
842:   PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL);
843:   PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL);

845:   flg  = PETSC_FALSE;
846:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
847:   if (set && flg) {SNESMonitorCancel(snes);}

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

853:   SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp);
854:   SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL);
855:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL);
856:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL);
857:   SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL);
858:   SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL);
859:   SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL);

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


865:   flg  = PETSC_FALSE;
866:   PetscOptionsBool("-snes_monitor_lg_residualnorm","Plot function norm at each iteration","SNESMonitorLGResidualNorm",flg,&flg,NULL);
867:   if (flg) {
868:     PetscDrawLG ctx;

870:     SNESMonitorLGCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
871:     SNESMonitorSet(snes,SNESMonitorLGResidualNorm,ctx,(PetscErrorCode (*)(void**))PetscDrawLGDestroy);
872:   }
873:   flg  = PETSC_FALSE;
874:   PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);
875:   if (flg) {
876:     PetscViewer ctx;

878:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
879:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
880:   }



884:   flg  = PETSC_FALSE;
885:   PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);
886:   if (flg) {
887:     void    *functx;
888:     DM      dm;
889:     DMSNES  sdm;
890:     SNESGetDM(snes,&dm);
891:     DMGetDMSNES(dm,&sdm);
892:     sdm->jacobianctx = NULL;
893:     SNESGetFunction(snes,NULL,NULL,&functx);
894:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);
895:     PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");
896:   }

898:   flg  = PETSC_FALSE;
899:   PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);
900:   if (flg) {
901:     SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);
902:   }

904:   flg  = PETSC_FALSE;
905:   PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL);
906:   if (flg) {
907:     DM             dm;
908:     DMSNES         sdm;
909:     SNESGetDM(snes,&dm);
910:     DMGetDMSNES(dm,&sdm);
911:     sdm->jacobianctx = NULL;
912:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,0);
913:     PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n");
914:   }

916:   flg  = PETSC_FALSE;
917:   PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg);
918:   if (flg && snes->mf_operator) {
919:     snes->mf_operator = PETSC_TRUE;
920:     snes->mf          = PETSC_TRUE;
921:   }
922:   flg  = PETSC_FALSE;
923:   PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg);
924:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
925:   PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,0);

927:   flg  = PETSC_FALSE;
928:   SNESGetNPCSide(snes,&pcside);
929:   PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);
930:   if (flg) {SNESSetNPCSide(snes,pcside);}

932: #if defined(PETSC_HAVE_SAWS)
933:   /*
934:     Publish convergence information using SAWs
935:   */
936:   flg  = PETSC_FALSE;
937:   PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL);
938:   if (flg) {
939:     void *ctx;
940:     SNESMonitorSAWsCreate(snes,&ctx);
941:     SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy);
942:   }
943: #endif
944: #if defined(PETSC_HAVE_SAWS)
945:   {
946:   PetscBool set;
947:   flg  = PETSC_FALSE;
948:   PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set);
949:   if (set) {
950:     PetscObjectSAWsSetBlock((PetscObject)snes,flg);
951:   }
952:   }
953: #endif

955:   for (i = 0; i < numberofsetfromoptions; i++) {
956:     (*othersetfromoptions[i])(snes);
957:   }

959:   if (snes->ops->setfromoptions) {
960:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
961:   }

963:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
964:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
965:   PetscOptionsEnd();

967:   if (!snes->linesearch) {
968:     SNESGetLineSearch(snes, &snes->linesearch);
969:   }
970:   SNESLineSearchSetFromOptions(snes->linesearch);

972:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
973:   KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
974:   KSPSetFromOptions(snes->ksp);

976:   /* if someone has set the SNES NPC type, create it. */
977:   SNESGetOptionsPrefix(snes, &optionsprefix);
978:   PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset);
979:   if (pcset && (!snes->npc)) {
980:     SNESGetNPC(snes, &snes->npc);
981:   }
982:   return(0);
983: }

985: /*@C
986:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
987:    the nonlinear solvers.

989:    Logically Collective on SNES

991:    Input Parameters:
992: +  snes - the SNES context
993: .  compute - function to compute the context
994: -  destroy - function to destroy the context

996:    Level: intermediate

998:    Notes:
999:    This function is currently not available from Fortran.

1001: .keywords: SNES, nonlinear, set, application, context

1003: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1004: @*/
1005: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1006: {
1009:   snes->ops->usercompute = compute;
1010:   snes->ops->userdestroy = destroy;
1011:   return(0);
1012: }

1014: /*@
1015:    SNESSetApplicationContext - Sets the optional user-defined context for
1016:    the nonlinear solvers.

1018:    Logically Collective on SNES

1020:    Input Parameters:
1021: +  snes - the SNES context
1022: -  usrP - optional user context

1024:    Level: intermediate

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

1030: .keywords: SNES, nonlinear, set, application, context

1032: .seealso: SNESGetApplicationContext()
1033: @*/
1034: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1035: {
1037:   KSP            ksp;

1041:   SNESGetKSP(snes,&ksp);
1042:   KSPSetApplicationContext(ksp,usrP);
1043:   snes->user = usrP;
1044:   return(0);
1045: }

1047: /*@
1048:    SNESGetApplicationContext - Gets the user-defined context for the
1049:    nonlinear solvers.

1051:    Not Collective

1053:    Input Parameter:
1054: .  snes - SNES context

1056:    Output Parameter:
1057: .  usrP - user context

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

1063:    Level: intermediate

1065: .keywords: SNES, nonlinear, get, application, context

1067: .seealso: SNESSetApplicationContext()
1068: @*/
1069: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1070: {
1073:   *(void**)usrP = snes->user;
1074:   return(0);
1075: }

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

1081:    Collective on SNES

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

1088:    Options Database:
1089: + -snes_mf - use matrix free for both the mat and pmat operator
1090: - -snes_mf_operator - use matrix free only for the mat operator

1092:    Level: intermediate

1094: .keywords: SNES, nonlinear, get, iteration, number,

1096: .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF()
1097: @*/
1098: PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1099: {
1104:   if (mf && !mf_operator) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"If using mf must also use mf_operator");
1105:   snes->mf          = mf;
1106:   snes->mf_operator = mf_operator;
1107:   return(0);
1108: }

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

1114:    Collective on SNES

1116:    Input Parameter:
1117: .  snes - SNES context

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

1123:    Options Database:
1124: + -snes_mf - use matrix free for both the mat and pmat operator
1125: - -snes_mf_operator - use matrix free only for the mat operator

1127:    Level: intermediate

1129: .keywords: SNES, nonlinear, get, iteration, number,

1131: .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
1132: @*/
1133: PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1134: {
1137:   if (mf)          *mf          = snes->mf;
1138:   if (mf_operator) *mf_operator = snes->mf_operator;
1139:   return(0);
1140: }

1142: /*@
1143:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1144:    at this time.

1146:    Not Collective

1148:    Input Parameter:
1149: .  snes - SNES context

1151:    Output Parameter:
1152: .  iter - iteration number

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

1157:    This is useful for using lagged Jacobians (where one does not recompute the
1158:    Jacobian at each SNES iteration). For example, the code
1159: .vb
1160:       SNESGetIterationNumber(snes,&it);
1161:       if (!(it % 2)) {
1162:         [compute Jacobian here]
1163:       }
1164: .ve
1165:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1166:    recomputed every second SNES iteration.

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

1170:    Level: intermediate

1172: .keywords: SNES, nonlinear, get, iteration, number,

1174: .seealso:   SNESGetLinearSolveIterations()
1175: @*/
1176: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1177: {
1181:   *iter = snes->iter;
1182:   return(0);
1183: }

1185: /*@
1186:    SNESSetIterationNumber - Sets the current iteration number.

1188:    Not Collective

1190:    Input Parameter:
1191: .  snes - SNES context
1192: .  iter - iteration number

1194:    Level: developer

1196: .keywords: SNES, nonlinear, set, iteration, number,

1198: .seealso:   SNESGetLinearSolveIterations()
1199: @*/
1200: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1201: {

1206:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1207:   snes->iter = iter;
1208:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1209:   return(0);
1210: }

1212: /*@
1213:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1214:    attempted by the nonlinear solver.

1216:    Not Collective

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

1221:    Output Parameter:
1222: .  nfails - number of unsuccessful steps attempted

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

1227:    Level: intermediate

1229: .keywords: SNES, nonlinear, get, number, unsuccessful, steps

1231: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1232:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1233: @*/
1234: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1235: {
1239:   *nfails = snes->numFailures;
1240:   return(0);
1241: }

1243: /*@
1244:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1245:    attempted by the nonlinear solver before it gives up.

1247:    Not Collective

1249:    Input Parameters:
1250: +  snes     - SNES context
1251: -  maxFails - maximum of unsuccessful steps

1253:    Level: intermediate

1255: .keywords: SNES, nonlinear, set, maximum, unsuccessful, steps

1257: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1258:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1259: @*/
1260: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1261: {
1264:   snes->maxFailures = maxFails;
1265:   return(0);
1266: }

1268: /*@
1269:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1270:    attempted by the nonlinear solver before it gives up.

1272:    Not Collective

1274:    Input Parameter:
1275: .  snes     - SNES context

1277:    Output Parameter:
1278: .  maxFails - maximum of unsuccessful steps

1280:    Level: intermediate

1282: .keywords: SNES, nonlinear, get, maximum, unsuccessful, steps

1284: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1285:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1287: @*/
1288: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1289: {
1293:   *maxFails = snes->maxFailures;
1294:   return(0);
1295: }

1297: /*@
1298:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1299:      done by SNES.

1301:    Not Collective

1303:    Input Parameter:
1304: .  snes     - SNES context

1306:    Output Parameter:
1307: .  nfuncs - number of evaluations

1309:    Level: intermediate

1311:    Notes:
1312:     Reset every time SNESSolve is called unless SNESSetCountersReset() is used.

1314: .keywords: SNES, nonlinear, get, maximum, unsuccessful, steps

1316: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1317: @*/
1318: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1319: {
1323:   *nfuncs = snes->nfuncs;
1324:   return(0);
1325: }

1327: /*@
1328:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1329:    linear solvers.

1331:    Not Collective

1333:    Input Parameter:
1334: .  snes - SNES context

1336:    Output Parameter:
1337: .  nfails - number of failed solves

1339:    Level: intermediate

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

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

1347: .keywords: SNES, nonlinear, get, number, unsuccessful, steps

1349: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1350: @*/
1351: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1352: {
1356:   *nfails = snes->numLinearSolveFailures;
1357:   return(0);
1358: }

1360: /*@
1361:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1362:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1364:    Logically Collective on SNES

1366:    Input Parameters:
1367: +  snes     - SNES context
1368: -  maxFails - maximum allowed linear solve failures

1370:    Level: intermediate

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

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

1378: .keywords: SNES, nonlinear, set, maximum, unsuccessful, steps

1380: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1381: @*/
1382: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1383: {
1387:   snes->maxLinearSolveFailures = maxFails;
1388:   return(0);
1389: }

1391: /*@
1392:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1393:      are allowed before SNES terminates

1395:    Not Collective

1397:    Input Parameter:
1398: .  snes     - SNES context

1400:    Output Parameter:
1401: .  maxFails - maximum of unsuccessful solves allowed

1403:    Level: intermediate

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

1408: .keywords: SNES, nonlinear, get, maximum, unsuccessful, steps

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

1421: /*@
1422:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1423:    used by the nonlinear solver.

1425:    Not Collective

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

1430:    Output Parameter:
1431: .  lits - number of linear iterations

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

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

1439:    Level: intermediate

1441: .keywords: SNES, nonlinear, get, number, linear, iterations

1443: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1444: @*/
1445: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1446: {
1450:   *lits = snes->linear_its;
1451:   return(0);
1452: }

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

1458:    Logically Collective on SNES

1460:    Input Parameter:
1461: +  snes - SNES context
1462: -  reset - whether to reset the counters or not

1464:    Notes:
1465:    This defaults to PETSC_TRUE

1467:    Level: developer

1469: .keywords: SNES, nonlinear, set, reset, number, linear, iterations

1471: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1472: @*/
1473: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1474: {
1478:   snes->counters_reset = reset;
1479:   return(0);
1480: }


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

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

1488:    Input Parameters:
1489: +  snes - the SNES context
1490: -  ksp - the KSP context

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

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

1499:    Level: developer

1501: .keywords: SNES, nonlinear, get, KSP, context

1503: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1504: @*/
1505: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1506: {

1513:   PetscObjectReference((PetscObject)ksp);
1514:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1515:   snes->ksp = ksp;
1516:   return(0);
1517: }

1519: /* -----------------------------------------------------------*/
1520: /*@
1521:    SNESCreate - Creates a nonlinear solver context.

1523:    Collective on MPI_Comm

1525:    Input Parameters:
1526: .  comm - MPI communicator

1528:    Output Parameter:
1529: .  outsnes - the new SNES context

1531:    Options Database Keys:
1532: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1533:                and no preconditioning matrix
1534: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1535:                products, and a user-provided preconditioning matrix
1536:                as set by SNESSetJacobian()
1537: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1539:    Level: beginner

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

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

1551: .keywords: SNES, nonlinear, create, context

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

1555: @*/
1556: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1557: {
1559:   SNES           snes;
1560:   SNESKSPEW      *kctx;

1564:   *outsnes = NULL;
1565:   SNESInitializePackage();

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

1569:   snes->ops->converged    = SNESConvergedDefault;
1570:   snes->usesksp           = PETSC_TRUE;
1571:   snes->tolerancesset     = PETSC_FALSE;
1572:   snes->max_its           = 50;
1573:   snes->max_funcs         = 10000;
1574:   snes->norm              = 0.0;
1575:   snes->normschedule      = SNES_NORM_ALWAYS;
1576:   snes->functype          = SNES_FUNCTION_DEFAULT;
1577: #if defined(PETSC_USE_REAL_SINGLE)
1578:   snes->rtol              = 1.e-5;
1579: #else
1580:   snes->rtol              = 1.e-8;
1581: #endif
1582:   snes->ttol              = 0.0;
1583: #if defined(PETSC_USE_REAL_SINGLE)
1584:   snes->abstol            = 1.e-25;
1585: #else
1586:   snes->abstol            = 1.e-50;
1587: #endif
1588: #if defined(PETSC_USE_REAL_SINGLE)
1589:   snes->stol              = 1.e-5;
1590: #else
1591:   snes->stol              = 1.e-8;
1592: #endif
1593: #if defined(PETSC_USE_REAL_SINGLE)
1594:   snes->deltatol          = 1.e-6;
1595: #else
1596:   snes->deltatol          = 1.e-12;
1597: #endif
1598:   snes->divtol            = 1.e4;
1599:   snes->rnorm0            = 0;
1600:   snes->nfuncs            = 0;
1601:   snes->numFailures       = 0;
1602:   snes->maxFailures       = 1;
1603:   snes->linear_its        = 0;
1604:   snes->lagjacobian       = 1;
1605:   snes->jac_iter          = 0;
1606:   snes->lagjac_persist    = PETSC_FALSE;
1607:   snes->lagpreconditioner = 1;
1608:   snes->pre_iter          = 0;
1609:   snes->lagpre_persist    = PETSC_FALSE;
1610:   snes->numbermonitors    = 0;
1611:   snes->data              = 0;
1612:   snes->setupcalled       = PETSC_FALSE;
1613:   snes->ksp_ewconv        = PETSC_FALSE;
1614:   snes->nwork             = 0;
1615:   snes->work              = 0;
1616:   snes->nvwork            = 0;
1617:   snes->vwork             = 0;
1618:   snes->conv_hist_len     = 0;
1619:   snes->conv_hist_max     = 0;
1620:   snes->conv_hist         = NULL;
1621:   snes->conv_hist_its     = NULL;
1622:   snes->conv_hist_reset   = PETSC_TRUE;
1623:   snes->counters_reset    = PETSC_TRUE;
1624:   snes->vec_func_init_set = PETSC_FALSE;
1625:   snes->reason            = SNES_CONVERGED_ITERATING;
1626:   snes->npcside           = PC_RIGHT;

1628:   snes->mf          = PETSC_FALSE;
1629:   snes->mf_operator = PETSC_FALSE;
1630:   snes->mf_version  = 1;

1632:   snes->numLinearSolveFailures = 0;
1633:   snes->maxLinearSolveFailures = 1;

1635:   snes->vizerotolerance = 1.e-8;

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

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

1643:   snes->kspconvctx  = (void*)kctx;
1644:   kctx->version     = 2;
1645:   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1646:                              this was too large for some test cases */
1647:   kctx->rtol_last   = 0.0;
1648:   kctx->rtol_max    = .9;
1649:   kctx->gamma       = 1.0;
1650:   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
1651:   kctx->alpha2      = kctx->alpha;
1652:   kctx->threshold   = .1;
1653:   kctx->lresid_last = 0.0;
1654:   kctx->norm_last   = 0.0;

1656:   *outsnes = snes;
1657:   return(0);
1658: }

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

1663:      Synopsis:
1664:      #include "petscsnes.h"
1665:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1667:      Input Parameters:
1668: +     snes - the SNES context
1669: .     x    - state at which to evaluate residual
1670: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1672:      Output Parameter:
1673: .     f  - vector to put residual (function value)

1675:    Level: intermediate

1677: .seealso:   SNESSetFunction(), SNESGetFunction()
1678: M*/

1680: /*@C
1681:    SNESSetFunction - Sets the function evaluation routine and function
1682:    vector for use by the SNES routines in solving systems of nonlinear
1683:    equations.

1685:    Logically Collective on SNES

1687:    Input Parameters:
1688: +  snes - the SNES context
1689: .  r - vector to store function value
1690: .  f - function evaluation routine; see SNESFunction for calling sequence details
1691: -  ctx - [optional] user-defined context for private data for the
1692:          function evaluation routine (may be NULL)

1694:    Notes:
1695:    The Newton-like methods typically solve linear systems of the form
1696: $      f'(x) x = -f(x),
1697:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1699:    Level: beginner

1701: .keywords: SNES, nonlinear, set, function

1703: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1704: @*/
1705: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1706: {
1708:   DM             dm;

1712:   if (r) {
1715:     PetscObjectReference((PetscObject)r);
1716:     VecDestroy(&snes->vec_func);

1718:     snes->vec_func = r;
1719:   }
1720:   SNESGetDM(snes,&dm);
1721:   DMSNESSetFunction(dm,f,ctx);
1722:   return(0);
1723: }


1726: /*@C
1727:    SNESSetInitialFunction - Sets the function vector to be used as the
1728:    function norm at the initialization of the method.  In some
1729:    instances, the user has precomputed the function before calling
1730:    SNESSolve.  This function allows one to avoid a redundant call
1731:    to SNESComputeFunction in that case.

1733:    Logically Collective on SNES

1735:    Input Parameters:
1736: +  snes - the SNES context
1737: -  f - vector to store function value

1739:    Notes:
1740:    This should not be modified during the solution procedure.

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

1744:    Level: developer

1746: .keywords: SNES, nonlinear, set, function

1748: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1749: @*/
1750: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1751: {
1753:   Vec            vec_func;

1759:   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1760:     snes->vec_func_init_set = PETSC_FALSE;
1761:     return(0);
1762:   }
1763:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1764:   VecCopy(f, vec_func);

1766:   snes->vec_func_init_set = PETSC_TRUE;
1767:   return(0);
1768: }

1770: /*@
1771:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1772:    of the SNES method.

1774:    Logically Collective on SNES

1776:    Input Parameters:
1777: +  snes - the SNES context
1778: -  normschedule - the frequency of norm computation

1780:    Options Database Key:
1781: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1792:    Level: developer

1794: .keywords: SNES, nonlinear, set, function, norm, type

1796: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1797: @*/
1798: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1799: {
1802:   snes->normschedule = normschedule;
1803:   return(0);
1804: }


1807: /*@
1808:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1809:    of the SNES method.

1811:    Logically Collective on SNES

1813:    Input Parameters:
1814: +  snes - the SNES context
1815: -  normschedule - the type of the norm used

1817:    Level: advanced

1819: .keywords: SNES, nonlinear, set, function, norm, type

1821: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1822: @*/
1823: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1824: {
1827:   *normschedule = snes->normschedule;
1828:   return(0);
1829: }


1832: /*@
1833:   SNESSetFunctionNorm - Sets the last computed residual norm.

1835:   Logically Collective on SNES

1837:   Input Parameters:
1838: + snes - the SNES context

1840: - normschedule - the frequency of norm computation

1842:   Level: developer

1844: .keywords: SNES, nonlinear, set, function, norm, type
1845: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1846: @*/
1847: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1848: {
1851:   snes->norm = norm;
1852:   return(0);
1853: }

1855: /*@
1856:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1858:   Not Collective

1860:   Input Parameter:
1861: . snes - the SNES context

1863:   Output Parameter:
1864: . norm - the last computed residual norm

1866:   Level: developer

1868: .keywords: SNES, nonlinear, set, function, norm, type
1869: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1870: @*/
1871: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1872: {
1876:   *norm = snes->norm;
1877:   return(0);
1878: }

1880: /*@C
1881:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1882:    of the SNES method.

1884:    Logically Collective on SNES

1886:    Input Parameters:
1887: +  snes - the SNES context
1888: -  normschedule - the frequency of norm computation

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

1899:    Level: developer

1901: .keywords: SNES, nonlinear, set, function, norm, type

1903: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1904: @*/
1905: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1906: {
1909:   snes->functype = type;
1910:   return(0);
1911: }


1914: /*@C
1915:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1916:    of the SNES method.

1918:    Logically Collective on SNES

1920:    Input Parameters:
1921: +  snes - the SNES context
1922: -  normschedule - the type of the norm used

1924:    Level: advanced

1926: .keywords: SNES, nonlinear, set, function, norm, type

1928: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1929: @*/
1930: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
1931: {
1934:   *type = snes->functype;
1935:   return(0);
1936: }

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

1941:      Synopsis:
1942:      #include <petscsnes.h>
1943: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1945: +  X   - solution vector
1946: .  B   - RHS vector
1947: -  ctx - optional user-defined Gauss-Seidel context

1949:    Level: intermediate

1951: .seealso:   SNESSetNGS(), SNESGetNGS()
1952: M*/

1954: /*@C
1955:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1956:    use with composed nonlinear solvers.

1958:    Input Parameters:
1959: +  snes   - the SNES context
1960: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
1961: -  ctx    - [optional] user-defined context for private data for the
1962:             smoother evaluation routine (may be NULL)

1964:    Notes:
1965:    The NGS routines are used by the composed nonlinear solver to generate
1966:     a problem appropriate update to the solution, particularly FAS.

1968:    Level: intermediate

1970: .keywords: SNES, nonlinear, set, Gauss-Seidel

1972: .seealso: SNESGetFunction(), SNESComputeNGS()
1973: @*/
1974: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1975: {
1977:   DM             dm;

1981:   SNESGetDM(snes,&dm);
1982:   DMSNESSetNGS(dm,f,ctx);
1983:   return(0);
1984: }

1986: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1987: {
1989:   DM             dm;
1990:   DMSNES         sdm;

1993:   SNESGetDM(snes,&dm);
1994:   DMGetDMSNES(dm,&sdm);
1995:   /*  A(x)*x - b(x) */
1996:   if (sdm->ops->computepfunction) {
1997:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
1998:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");

2000:   if (sdm->ops->computepjacobian) {
2001:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
2002:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard matrix.");
2003:   VecScale(f,-1.0);
2004:   MatMultAdd(snes->jacobian,x,f,f);
2005:   return(0);
2006: }

2008: PETSC_EXTERN PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
2009: {
2011:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2012:   return(0);
2013: }

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

2018:    Logically Collective on SNES

2020:    Input Parameters:
2021: +  snes - the SNES context
2022: .  r - vector to store function value
2023: .  b - function evaluation routine
2024: .  Amat - matrix with which A(x) x - b(x) is to be computed
2025: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2026: .  J  - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
2027: -  ctx - [optional] user-defined context for private data for the
2028:          function evaluation routine (may be NULL)

2030:    Notes:
2031:     We do not recomemend using this routine. It is far better to provide the nonlinear function F() and some approximation to the Jacobian and use
2032:     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.

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

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

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

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

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

2048:    Level: intermediate

2050: .keywords: SNES, nonlinear, set, function

2052: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2053: @*/
2054: PetscErrorCode  SNESSetPicard(SNES snes,Vec r,PetscErrorCode (*b)(SNES,Vec,Vec,void*),Mat Amat, Mat Pmat, PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2055: {
2057:   DM             dm;

2061:   SNESGetDM(snes, &dm);
2062:   DMSNESSetPicard(dm,b,J,ctx);
2063:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2064:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2065:   return(0);
2066: }

2068: /*@C
2069:    SNESGetPicard - Returns the context for the Picard iteration

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

2073:    Input Parameter:
2074: .  snes - the SNES context

2076:    Output Parameter:
2077: +  r - the function (or NULL)
2078: .  f - the function (or NULL); see SNESFunction for calling sequence details
2079: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2080: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2081: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2082: -  ctx - the function context (or NULL)

2084:    Level: advanced

2086: .keywords: SNES, nonlinear, get, function

2088: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2089: @*/
2090: 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)
2091: {
2093:   DM             dm;

2097:   SNESGetFunction(snes,r,NULL,NULL);
2098:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2099:   SNESGetDM(snes,&dm);
2100:   DMSNESGetPicard(dm,f,J,ctx);
2101:   return(0);
2102: }

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

2107:    Logically Collective on SNES

2109:    Input Parameters:
2110: +  snes - the SNES context
2111: .  func - function evaluation routine
2112: -  ctx - [optional] user-defined context for private data for the
2113:          function evaluation routine (may be NULL)

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

2118: .  f - function vector
2119: -  ctx - optional user-defined function context

2121:    Level: intermediate

2123: .keywords: SNES, nonlinear, set, function

2125: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2126: @*/
2127: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2128: {
2131:   if (func) snes->ops->computeinitialguess = func;
2132:   if (ctx)  snes->initialguessP            = ctx;
2133:   return(0);
2134: }

2136: /* --------------------------------------------------------------- */
2137: /*@C
2138:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2139:    it assumes a zero right hand side.

2141:    Logically Collective on SNES

2143:    Input Parameter:
2144: .  snes - the SNES context

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

2149:    Level: intermediate

2151: .keywords: SNES, nonlinear, get, function, right hand side

2153: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2154: @*/
2155: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2156: {
2160:   *rhs = snes->vec_rhs;
2161:   return(0);
2162: }

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

2167:    Collective on SNES

2169:    Input Parameters:
2170: +  snes - the SNES context
2171: -  x - input vector

2173:    Output Parameter:
2174: .  y - function vector, as set by SNESSetFunction()

2176:    Notes:
2177:    SNESComputeFunction() is typically used within nonlinear solvers
2178:    implementations, so most users would not generally call this routine
2179:    themselves.

2181:    Level: developer

2183: .keywords: SNES, nonlinear, compute, function

2185: .seealso: SNESSetFunction(), SNESGetFunction()
2186: @*/
2187: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2188: {
2190:   DM             dm;
2191:   DMSNES         sdm;

2199:   VecValidValues(x,2,PETSC_TRUE);

2201:   SNESGetDM(snes,&dm);
2202:   DMGetDMSNES(dm,&sdm);
2203:   if (sdm->ops->computefunction) {
2204:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2205:       PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2206:     }
2207:     VecLockPush(x);
2208:     PetscStackPush("SNES user function");
2209:     (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);
2210:     PetscStackPop;
2211:     VecLockPop(x);
2212:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2213:       PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2214:     }
2215:   } else if (snes->vec_rhs) {
2216:     MatMult(snes->jacobian, x, y);
2217:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2218:   if (snes->vec_rhs) {
2219:     VecAXPY(y,-1.0,snes->vec_rhs);
2220:   }
2221:   snes->nfuncs++;
2222:   /*
2223:      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2224:      propagate the value to all processes
2225:   */
2226:   if (snes->domainerror) {
2227:     VecSetInf(y);
2228:   }
2229:   return(0);
2230: }

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

2235:    Collective on SNES

2237:    Input Parameters:
2238: +  snes - the SNES context
2239: .  x - input vector
2240: -  b - rhs vector

2242:    Output Parameter:
2243: .  x - new solution vector

2245:    Notes:
2246:    SNESComputeNGS() is typically used within composed nonlinear solver
2247:    implementations, so most users would not generally call this routine
2248:    themselves.

2250:    Level: developer

2252: .keywords: SNES, nonlinear, compute, function

2254: .seealso: SNESSetNGS(), SNESComputeFunction()
2255: @*/
2256: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2257: {
2259:   DM             dm;
2260:   DMSNES         sdm;

2268:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2269:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2270:   SNESGetDM(snes,&dm);
2271:   DMGetDMSNES(dm,&sdm);
2272:   if (sdm->ops->computegs) {
2273:     if (b) {VecLockPush(b);}
2274:     PetscStackPush("SNES user NGS");
2275:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2276:     PetscStackPop;
2277:     if (b) {VecLockPop(b);}
2278:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2279:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2280:   return(0);
2281: }

2283: PetscErrorCode SNESTestJacobian(SNES snes)
2284: {
2285:   Mat               A,B,C,D,jacobian;
2286:   Vec               x = snes->vec_sol,f = snes->vec_func;
2287:   PetscErrorCode    ierr;
2288:   PetscReal         nrm,gnorm;
2289:   PetscReal         threshold = 1.e-5;
2290:   PetscInt          m,n,M,N;
2291:   void              *functx;
2292:   PetscBool         complete_print = PETSC_FALSE,test = PETSC_FALSE,flg;
2293:   PetscViewer       viewer,mviewer;
2294:   MPI_Comm          comm;
2295:   PetscInt          tabs;
2296:   static PetscBool  directionsprinted = PETSC_FALSE;
2297:   PetscViewerFormat format;

2300:   PetscObjectOptionsBegin((PetscObject)snes);
2301:   PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test);
2302:   PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL);
2303:   PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print);
2304:   PetscOptionsEnd();
2305:   if (!test) return(0);

2307:   PetscObjectGetComm((PetscObject)snes,&comm);
2308:   PetscViewerASCIIGetStdout(comm,&viewer);
2309:   PetscViewerASCIIGetTab(viewer, &tabs);
2310:   PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);
2311:   PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n");
2312:   if (!complete_print && !directionsprinted) {
2313:     PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n");
2314:     PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n");
2315:   }
2316:   if (!directionsprinted) {
2317:     PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n");
2318:     PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n");
2319:     directionsprinted = PETSC_TRUE;
2320:   }
2321:   if (complete_print) {
2322:     PetscViewerPushFormat(mviewer,format);
2323:   }

2325:   /* evaluate the function at this point because SNESComputeJacobianDefault() assumes that the function has been evaluated and put into snes->vec_func */
2326:   SNESComputeFunction(snes,x,f);

2328:   PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg);
2329:   if (!flg) jacobian = snes->jacobian;
2330:   else jacobian = snes->jacobian_pre;

2332:   while (jacobian) {
2333:     PetscObjectTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2334:     if (flg) {
2335:       A    = jacobian;
2336:       PetscObjectReference((PetscObject)A);
2337:     } else {
2338:       MatComputeExplicitOperator(jacobian,&A);
2339:     }

2341:     MatCreate(PetscObjectComm((PetscObject)A),&B);
2342:     MatGetSize(A,&M,&N);
2343:     MatGetLocalSize(A,&m,&n);
2344:     MatSetSizes(B,m,n,M,N);
2345:     MatSetType(B,((PetscObject)A)->type_name);
2346:     MatSetUp(B);
2347:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2349:     SNESGetFunction(snes,NULL,NULL,&functx);
2350:     SNESComputeJacobianDefault(snes,x,B,B,functx);

2352:     MatDuplicate(B,MAT_COPY_VALUES,&D);
2353:     MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2354:     MatNorm(D,NORM_FROBENIUS,&nrm);
2355:     MatNorm(A,NORM_FROBENIUS,&gnorm);
2356:     MatDestroy(&D);
2357:     if (!gnorm) gnorm = 1; /* just in case */
2358:     PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm);

2360:     if (complete_print) {
2361:       PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n");
2362:       MatView(jacobian,mviewer);
2363:       PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n");
2364:       MatView(B,mviewer);
2365:     }

2367:     if (complete_print) {
2368:       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2369:       PetscScalar       *cvals;
2370:       const PetscInt    *bcols;
2371:       const PetscScalar *bvals;

2373:       MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2374:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2375:       MatSetSizes(C,m,n,M,N);
2376:       MatSetType(C,((PetscObject)A)->type_name);
2377:       MatSetUp(C);
2378:       MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
2379:       MatGetOwnershipRange(B,&Istart,&Iend);

2381:       for (row = Istart; row < Iend; row++) {
2382:         MatGetRow(B,row,&bncols,&bcols,&bvals);
2383:         PetscMalloc2(bncols,&ccols,bncols,&cvals);
2384:         for (j = 0, cncols = 0; j < bncols; j++) {
2385:           if (PetscAbsScalar(bvals[j]) > threshold) {
2386:             ccols[cncols] = bcols[j];
2387:             cvals[cncols] = bvals[j];
2388:             cncols += 1;
2389:           }
2390:         }
2391:         if (cncols) {
2392:           MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES);
2393:         }
2394:         MatRestoreRow(B,row,&bncols,&bcols,&bvals);
2395:         PetscFree2(ccols,cvals);
2396:       }
2397:       MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2398:       MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
2399:       PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold);
2400:       MatView(C,mviewer);
2401:       MatDestroy(&C);
2402:     }
2403:     MatDestroy(&A);
2404:     MatDestroy(&B);

2406:     if (jacobian != snes->jacobian_pre) {
2407:       jacobian = snes->jacobian_pre;
2408:       PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n");
2409:     }
2410:     else jacobian = NULL;
2411:   }
2412:   if (complete_print) {
2413:     PetscViewerPopFormat(mviewer);
2414:   }
2415:   PetscViewerASCIISetTab(viewer,tabs);
2416:   return(0);
2417: }

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

2422:    Collective on SNES and Mat

2424:    Input Parameters:
2425: +  snes - the SNES context
2426: -  x - input vector

2428:    Output Parameters:
2429: +  A - Jacobian matrix
2430: -  B - optional preconditioning matrix

2432:   Options Database Keys:
2433: +    -snes_lag_preconditioner <lag>
2434: .    -snes_lag_jacobian <lag>
2435: .    -snes_test_jacobian - compare the user provided Jacobian with one compute via finite differences to check for errors
2436: .    -snes_test_jacobian_display - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian
2437: .    -snes_test_jacobian_display_threshold <numerical value>  - display entries in the difference between the user provided Jacobian and finite difference Jacobian that are greater than a certain value to help users detect errors
2438: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2439: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2440: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2441: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2442: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2443: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2444: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2445: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2446: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2447: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2448: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2451:    Notes:
2452:    Most users should not need to explicitly call this routine, as it
2453:    is used internally within the nonlinear solvers.

2455:    Developer Notes:
2456:     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 
2457:       for with the SNESType of test that has been removed.

2459:    Level: developer

2461: .keywords: SNES, compute, Jacobian, matrix

2463: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2464: @*/
2465: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2466: {
2468:   PetscBool      flag;
2469:   DM             dm;
2470:   DMSNES         sdm;
2471:   KSP            ksp;

2477:   VecValidValues(X,2,PETSC_TRUE);
2478:   SNESGetDM(snes,&dm);
2479:   DMGetDMSNES(dm,&sdm);

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

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

2485:   if (snes->lagjacobian == -2) {
2486:     snes->lagjacobian = -1;

2488:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2489:   } else if (snes->lagjacobian == -1) {
2490:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2491:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2492:     if (flag) {
2493:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2494:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2495:     }
2496:     return(0);
2497:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2498:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2499:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2500:     if (flag) {
2501:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2502:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2503:     }
2504:     return(0);
2505:   }
2506:   if (snes->npc && snes->npcside== PC_LEFT) {
2507:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2508:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2509:       return(0);
2510:   }

2512:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2513:   VecLockPush(X);
2514:   PetscStackPush("SNES user Jacobian function");
2515:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2516:   PetscStackPop;
2517:   VecLockPop(X);
2518:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2520:   /* the next line ensures that snes->ksp exists */
2521:   SNESGetKSP(snes,&ksp);
2522:   if (snes->lagpreconditioner == -2) {
2523:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2524:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2525:     snes->lagpreconditioner = -1;
2526:   } else if (snes->lagpreconditioner == -1) {
2527:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2528:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2529:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2530:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2531:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2532:   } else {
2533:     PetscInfo(snes,"Rebuilding preconditioner\n");
2534:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2535:   }

2537:   SNESTestJacobian(snes);
2538:   /* make sure user returned a correct Jacobian and preconditioner */
2541:   {
2542:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2543:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2544:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2545:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2546:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2547:     if (flag || flag_draw || flag_contour) {
2548:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2549:       PetscViewer  vdraw,vstdout;
2550:       PetscBool    flg;
2551:       if (flag_operator) {
2552:         MatComputeExplicitOperator(A,&Bexp_mine);
2553:         Bexp = Bexp_mine;
2554:       } else {
2555:         /* See if the preconditioning matrix can be viewed and added directly */
2556:         PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2557:         if (flg) Bexp = B;
2558:         else {
2559:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2560:           MatComputeExplicitOperator(B,&Bexp_mine);
2561:           Bexp = Bexp_mine;
2562:         }
2563:       }
2564:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2565:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2566:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2567:       if (flag_draw || flag_contour) {
2568:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2569:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2570:       } else vdraw = NULL;
2571:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2572:       if (flag) {MatView(Bexp,vstdout);}
2573:       if (vdraw) {MatView(Bexp,vdraw);}
2574:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2575:       if (flag) {MatView(FDexp,vstdout);}
2576:       if (vdraw) {MatView(FDexp,vdraw);}
2577:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2578:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2579:       if (flag) {MatView(FDexp,vstdout);}
2580:       if (vdraw) {              /* Always use contour for the difference */
2581:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2582:         MatView(FDexp,vdraw);
2583:         PetscViewerPopFormat(vdraw);
2584:       }
2585:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2586:       PetscViewerDestroy(&vdraw);
2587:       MatDestroy(&Bexp_mine);
2588:       MatDestroy(&FDexp);
2589:     }
2590:   }
2591:   {
2592:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2593:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2594:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2595:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2596:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2597:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2598:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2599:     if (flag_threshold) {
2600:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2601:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2602:     }
2603:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2604:       Mat            Bfd;
2605:       PetscViewer    vdraw,vstdout;
2606:       MatColoring    coloring;
2607:       ISColoring     iscoloring;
2608:       MatFDColoring  matfdcoloring;
2609:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2610:       void           *funcctx;
2611:       PetscReal      norm1,norm2,normmax;

2613:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2614:       MatColoringCreate(Bfd,&coloring);
2615:       MatColoringSetType(coloring,MATCOLORINGSL);
2616:       MatColoringSetFromOptions(coloring);
2617:       MatColoringApply(coloring,&iscoloring);
2618:       MatColoringDestroy(&coloring);
2619:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2620:       MatFDColoringSetFromOptions(matfdcoloring);
2621:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2622:       ISColoringDestroy(&iscoloring);

2624:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2625:       SNESGetFunction(snes,NULL,&func,&funcctx);
2626:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2627:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2628:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2629:       MatFDColoringSetFromOptions(matfdcoloring);
2630:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2631:       MatFDColoringDestroy(&matfdcoloring);

2633:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2634:       if (flag_draw || flag_contour) {
2635:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2636:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2637:       } else vdraw = NULL;
2638:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2639:       if (flag_display) {MatView(B,vstdout);}
2640:       if (vdraw) {MatView(B,vdraw);}
2641:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2642:       if (flag_display) {MatView(Bfd,vstdout);}
2643:       if (vdraw) {MatView(Bfd,vdraw);}
2644:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2645:       MatNorm(Bfd,NORM_1,&norm1);
2646:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2647:       MatNorm(Bfd,NORM_MAX,&normmax);
2648:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2649:       if (flag_display) {MatView(Bfd,vstdout);}
2650:       if (vdraw) {              /* Always use contour for the difference */
2651:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2652:         MatView(Bfd,vdraw);
2653:         PetscViewerPopFormat(vdraw);
2654:       }
2655:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2657:       if (flag_threshold) {
2658:         PetscInt bs,rstart,rend,i;
2659:         MatGetBlockSize(B,&bs);
2660:         MatGetOwnershipRange(B,&rstart,&rend);
2661:         for (i=rstart; i<rend; i++) {
2662:           const PetscScalar *ba,*ca;
2663:           const PetscInt    *bj,*cj;
2664:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2665:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2666:           MatGetRow(B,i,&bn,&bj,&ba);
2667:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2668:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2669:           for (j=0; j<bn; j++) {
2670:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2671:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2672:               maxentrycol = bj[j];
2673:               maxentry    = PetscRealPart(ba[j]);
2674:             }
2675:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2676:               maxdiffcol = bj[j];
2677:               maxdiff    = PetscRealPart(ca[j]);
2678:             }
2679:             if (rdiff > maxrdiff) {
2680:               maxrdiffcol = bj[j];
2681:               maxrdiff    = rdiff;
2682:             }
2683:           }
2684:           if (maxrdiff > 1) {
2685:             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);
2686:             for (j=0; j<bn; j++) {
2687:               PetscReal rdiff;
2688:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2689:               if (rdiff > 1) {
2690:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2691:               }
2692:             }
2693:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2694:           }
2695:           MatRestoreRow(B,i,&bn,&bj,&ba);
2696:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2697:         }
2698:       }
2699:       PetscViewerDestroy(&vdraw);
2700:       MatDestroy(&Bfd);
2701:     }
2702:   }
2703:   return(0);
2704: }

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

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

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

2718:    Level: intermediate

2720: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2721: M*/

2723: /*@C
2724:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2725:    location to store the matrix.

2727:    Logically Collective on SNES and Mat

2729:    Input Parameters:
2730: +  snes - the SNES context
2731: .  Amat - the matrix that defines the (approximate) Jacobian
2732: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2733: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2734: -  ctx - [optional] user-defined context for private data for the
2735:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2737:    Notes:
2738:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2739:    each matrix.

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

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

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

2750:    Level: beginner

2752: .keywords: SNES, nonlinear, set, Jacobian, matrix

2754: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
2755:           SNESSetPicard(), SNESJacobianFunction
2756: @*/
2757: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2758: {
2760:   DM             dm;

2768:   SNESGetDM(snes,&dm);
2769:   DMSNESSetJacobian(dm,J,ctx);
2770:   if (Amat) {
2771:     PetscObjectReference((PetscObject)Amat);
2772:     MatDestroy(&snes->jacobian);

2774:     snes->jacobian = Amat;
2775:   }
2776:   if (Pmat) {
2777:     PetscObjectReference((PetscObject)Pmat);
2778:     MatDestroy(&snes->jacobian_pre);

2780:     snes->jacobian_pre = Pmat;
2781:   }
2782:   return(0);
2783: }

2785: /*@C
2786:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2787:    provided context for evaluating the Jacobian.

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

2791:    Input Parameter:
2792: .  snes - the nonlinear solver context

2794:    Output Parameters:
2795: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2796: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2797: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2798: -  ctx - location to stash Jacobian ctx (or NULL)

2800:    Level: advanced

2802: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2803: @*/
2804: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2805: {
2807:   DM             dm;
2808:   DMSNES         sdm;

2812:   if (Amat) *Amat = snes->jacobian;
2813:   if (Pmat) *Pmat = snes->jacobian_pre;
2814:   SNESGetDM(snes,&dm);
2815:   DMGetDMSNES(dm,&sdm);
2816:   if (J) *J = sdm->ops->computejacobian;
2817:   if (ctx) *ctx = sdm->jacobianctx;
2818:   return(0);
2819: }

2821: /*@
2822:    SNESSetUp - Sets up the internal data structures for the later use
2823:    of a nonlinear solver.

2825:    Collective on SNES

2827:    Input Parameters:
2828: .  snes - the SNES context

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

2837:    Level: advanced

2839: .keywords: SNES, nonlinear, setup

2841: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2842: @*/
2843: PetscErrorCode  SNESSetUp(SNES snes)
2844: {
2846:   DM             dm;
2847:   DMSNES         sdm;
2848:   SNESLineSearch linesearch, pclinesearch;
2849:   void           *lsprectx,*lspostctx;
2850:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2851:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2852:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2853:   Vec            f,fpc;
2854:   void           *funcctx;
2855:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2856:   void           *jacctx,*appctx;
2857:   Mat            j,jpre;

2861:   if (snes->setupcalled) return(0);

2863:   if (!((PetscObject)snes)->type_name) {
2864:     SNESSetType(snes,SNESNEWTONLS);
2865:   }

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

2869:   SNESGetDM(snes,&dm);
2870:   DMGetDMSNES(dm,&sdm);
2871:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2872:   if (!sdm->ops->computejacobian) {
2873:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2874:   }
2875:   if (!snes->vec_func) {
2876:     DMCreateGlobalVector(dm,&snes->vec_func);
2877:   }

2879:   if (!snes->ksp) {
2880:     SNESGetKSP(snes, &snes->ksp);
2881:   }

2883:   if (!snes->linesearch) {
2884:     SNESGetLineSearch(snes, &snes->linesearch);
2885:   }
2886:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2888:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2889:     snes->mf          = PETSC_TRUE;
2890:     snes->mf_operator = PETSC_FALSE;
2891:   }

2893:   if (snes->npc) {
2894:     /* copy the DM over */
2895:     SNESGetDM(snes,&dm);
2896:     SNESSetDM(snes->npc,dm);

2898:     SNESGetFunction(snes,&f,&func,&funcctx);
2899:     VecDuplicate(f,&fpc);
2900:     SNESSetFunction(snes->npc,fpc,func,funcctx);
2901:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2902:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
2903:     SNESGetApplicationContext(snes,&appctx);
2904:     SNESSetApplicationContext(snes->npc,appctx);
2905:     VecDestroy(&fpc);

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

2910:     /* default to 1 iteration */
2911:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
2912:     if (snes->npcside==PC_RIGHT) {
2913:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
2914:     } else {
2915:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
2916:     }
2917:     SNESSetFromOptions(snes->npc);

2919:     /* copy the line search context over */
2920:     SNESGetLineSearch(snes,&linesearch);
2921:     SNESGetLineSearch(snes->npc,&pclinesearch);
2922:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2923:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2924:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2925:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2926:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2927:   }
2928:   if (snes->mf) {
2929:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2930:   }
2931:   if (snes->ops->usercompute && !snes->user) {
2932:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2933:   }

2935:   snes->jac_iter = 0;
2936:   snes->pre_iter = 0;

2938:   if (snes->ops->setup) {
2939:     (*snes->ops->setup)(snes);
2940:   }

2942:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2943:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2944:       SNESGetLineSearch(snes,&linesearch);
2945:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2946:     }
2947:   }

2949:   snes->setupcalled = PETSC_TRUE;
2950:   return(0);
2951: }

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

2956:    Collective on SNES

2958:    Input Parameter:
2959: .  snes - iterative context obtained from SNESCreate()

2961:    Level: intermediate

2963:    Notes:
2964:     Also calls the application context destroy routine set with SNESSetComputeApplicationContext()

2966: .keywords: SNES, destroy

2968: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
2969: @*/
2970: PetscErrorCode  SNESReset(SNES snes)
2971: {

2976:   if (snes->ops->userdestroy && snes->user) {
2977:     (*snes->ops->userdestroy)((void**)&snes->user);
2978:     snes->user = NULL;
2979:   }
2980:   if (snes->npc) {
2981:     SNESReset(snes->npc);
2982:   }

2984:   if (snes->ops->reset) {
2985:     (*snes->ops->reset)(snes);
2986:   }
2987:   if (snes->ksp) {
2988:     KSPReset(snes->ksp);
2989:   }

2991:   if (snes->linesearch) {
2992:     SNESLineSearchReset(snes->linesearch);
2993:   }

2995:   VecDestroy(&snes->vec_rhs);
2996:   VecDestroy(&snes->vec_sol);
2997:   VecDestroy(&snes->vec_sol_update);
2998:   VecDestroy(&snes->vec_func);
2999:   MatDestroy(&snes->jacobian);
3000:   MatDestroy(&snes->jacobian_pre);
3001:   VecDestroyVecs(snes->nwork,&snes->work);
3002:   VecDestroyVecs(snes->nvwork,&snes->vwork);

3004:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3006:   snes->nwork       = snes->nvwork = 0;
3007:   snes->setupcalled = PETSC_FALSE;
3008:   return(0);
3009: }

3011: /*@
3012:    SNESDestroy - Destroys the nonlinear solver context that was created
3013:    with SNESCreate().

3015:    Collective on SNES

3017:    Input Parameter:
3018: .  snes - the SNES context

3020:    Level: beginner

3022: .keywords: SNES, nonlinear, destroy

3024: .seealso: SNESCreate(), SNESSolve()
3025: @*/
3026: PetscErrorCode  SNESDestroy(SNES *snes)
3027: {

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

3035:   SNESReset((*snes));
3036:   SNESDestroy(&(*snes)->npc);

3038:   /* if memory was published with SAWs then destroy it */
3039:   PetscObjectSAWsViewOff((PetscObject)*snes);
3040:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

3042:   if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
3043:   DMDestroy(&(*snes)->dm);
3044:   KSPDestroy(&(*snes)->ksp);
3045:   SNESLineSearchDestroy(&(*snes)->linesearch);

3047:   PetscFree((*snes)->kspconvctx);
3048:   if ((*snes)->ops->convergeddestroy) {
3049:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
3050:   }
3051:   if ((*snes)->conv_malloc) {
3052:     PetscFree((*snes)->conv_hist);
3053:     PetscFree((*snes)->conv_hist_its);
3054:   }
3055:   SNESMonitorCancel((*snes));
3056:   PetscHeaderDestroy(snes);
3057:   return(0);
3058: }

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

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

3065:    Logically Collective on SNES

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

3072:    Options Database Keys:
3073: .    -snes_lag_preconditioner <lag>

3075:    Notes:
3076:    The default is 1
3077:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3078:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

3080:    Level: intermediate

3082: .keywords: SNES, nonlinear, set, convergence, tolerances

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

3086: @*/
3087: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3088: {
3091:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3092:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3094:   snes->lagpreconditioner = lag;
3095:   return(0);
3096: }

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

3101:    Logically Collective on SNES

3103:    Input Parameters:
3104: +  snes - the SNES context
3105: -  steps - the number of refinements to do, defaults to 0

3107:    Options Database Keys:
3108: .    -snes_grid_sequence <steps>

3110:    Level: intermediate

3112:    Notes:
3113:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

3115: .keywords: SNES, nonlinear, set, convergence, tolerances

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

3119: @*/
3120: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3121: {
3125:   snes->gridsequence = steps;
3126:   return(0);
3127: }

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

3132:    Logically Collective on SNES

3134:    Input Parameter:
3135: .  snes - the SNES context

3137:    Output Parameter:
3138: .  steps - the number of refinements to do, defaults to 0

3140:    Options Database Keys:
3141: .    -snes_grid_sequence <steps>

3143:    Level: intermediate

3145:    Notes:
3146:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

3148: .keywords: SNES, nonlinear, set, convergence, tolerances

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

3152: @*/
3153: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3154: {
3157:   *steps = snes->gridsequence;
3158:   return(0);
3159: }

3161: /*@
3162:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3164:    Not Collective

3166:    Input Parameter:
3167: .  snes - the SNES context

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

3173:    Options Database Keys:
3174: .    -snes_lag_preconditioner <lag>

3176:    Notes:
3177:    The default is 1
3178:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3180:    Level: intermediate

3182: .keywords: SNES, nonlinear, set, convergence, tolerances

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

3186: @*/
3187: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3188: {
3191:   *lag = snes->lagpreconditioner;
3192:   return(0);
3193: }

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

3199:    Logically Collective on SNES

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

3206:    Options Database Keys:
3207: .    -snes_lag_jacobian <lag>

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

3215:    Level: intermediate

3217: .keywords: SNES, nonlinear, set, convergence, tolerances

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

3221: @*/
3222: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3223: {
3226:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3227:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3229:   snes->lagjacobian = lag;
3230:   return(0);
3231: }

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

3236:    Not Collective

3238:    Input Parameter:
3239: .  snes - the SNES context

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

3245:    Options Database Keys:
3246: .    -snes_lag_jacobian <lag>

3248:    Notes:
3249:    The default is 1
3250:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3252:    Level: intermediate

3254: .keywords: SNES, nonlinear, set, convergence, tolerances

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

3258: @*/
3259: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3260: {
3263:   *lag = snes->lagjacobian;
3264:   return(0);
3265: }

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

3270:    Logically collective on SNES

3272:    Input Parameter:
3273: +  snes - the SNES context
3274: -   flg - jacobian lagging persists if true

3276:    Options Database Keys:
3277: .    -snes_lag_jacobian_persists <flg>

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

3284:    Level: developer

3286: .keywords: SNES, nonlinear, lag

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

3290: @*/
3291: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3292: {
3296:   snes->lagjac_persist = flg;
3297:   return(0);
3298: }

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

3303:    Logically Collective on SNES

3305:    Input Parameter:
3306: +  snes - the SNES context
3307: -   flg - preconditioner lagging persists if true

3309:    Options Database Keys:
3310: .    -snes_lag_jacobian_persists <flg>

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

3317:    Level: developer

3319: .keywords: SNES, nonlinear, lag

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

3323: @*/
3324: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3325: {
3329:   snes->lagpre_persist = flg;
3330:   return(0);
3331: }

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

3336:    Logically Collective on SNES

3338:    Input Parameters:
3339: +  snes - the SNES context
3340: -  force - PETSC_TRUE require at least one iteration

3342:    Options Database Keys:
3343: .    -snes_force_iteration <force> - Sets forcing an iteration

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

3348:    Level: intermediate

3350: .keywords: SNES, nonlinear, set, convergence, tolerances

3352: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3353: @*/
3354: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3355: {
3358:   snes->forceiteration = force;
3359:   return(0);
3360: }

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

3365:    Logically Collective on SNES

3367:    Input Parameters:
3368: .  snes - the SNES context

3370:    Output Parameter:
3371: .  force - PETSC_TRUE requires at least one iteration.

3373: .keywords: SNES, nonlinear, set, convergence, tolerances

3375: .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3376: @*/
3377: PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
3378: {
3381:   *force = snes->forceiteration;
3382:   return(0);
3383: }

3385: /*@
3386:    SNESSetTolerances - Sets various parameters used in convergence tests.

3388:    Logically Collective on SNES

3390:    Input Parameters:
3391: +  snes - the SNES context
3392: .  abstol - absolute convergence tolerance
3393: .  rtol - relative convergence tolerance
3394: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3395: .  maxit - maximum number of iterations
3396: -  maxf - maximum number of function evaluations

3398:    Options Database Keys:
3399: +    -snes_atol <abstol> - Sets abstol
3400: .    -snes_rtol <rtol> - Sets rtol
3401: .    -snes_stol <stol> - Sets stol
3402: .    -snes_max_it <maxit> - Sets maxit
3403: -    -snes_max_funcs <maxf> - Sets maxf

3405:    Notes:
3406:    The default maximum number of iterations is 50.
3407:    The default maximum number of function evaluations is 1000.

3409:    Level: intermediate

3411: .keywords: SNES, nonlinear, set, convergence, tolerances

3413: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3414: @*/
3415: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3416: {

3425:   if (abstol != PETSC_DEFAULT) {
3426:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3427:     snes->abstol = abstol;
3428:   }
3429:   if (rtol != PETSC_DEFAULT) {
3430:     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);
3431:     snes->rtol = rtol;
3432:   }
3433:   if (stol != PETSC_DEFAULT) {
3434:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3435:     snes->stol = stol;
3436:   }
3437:   if (maxit != PETSC_DEFAULT) {
3438:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3439:     snes->max_its = maxit;
3440:   }
3441:   if (maxf != PETSC_DEFAULT) {
3442:     if (maxf < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be non-negative",maxf);
3443:     snes->max_funcs = maxf;
3444:   }
3445:   snes->tolerancesset = PETSC_TRUE;
3446:   return(0);
3447: }

3449: /*@
3450:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3452:    Logically Collective on SNES

3454:    Input Parameters:
3455: +  snes - the SNES context
3456: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3458:    Options Database Keys:
3459: +    -snes_divergence_tolerance <divtol> - Sets divtol

3461:    Notes:
3462:    The default divergence tolerance is 1e4.

3464:    Level: intermediate

3466: .keywords: SNES, nonlinear, set, divergence, tolerance

3468: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3469: @*/
3470: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3471: {

3476:   if (divtol != PETSC_DEFAULT) {
3477:     snes->divtol = divtol;
3478:   }
3479:   else {
3480:     snes->divtol = 1.0e4;
3481:   }
3482:   return(0);
3483: }

3485: /*@
3486:    SNESGetTolerances - Gets various parameters used in convergence tests.

3488:    Not Collective

3490:    Input Parameters:
3491: +  snes - the SNES context
3492: .  atol - absolute convergence tolerance
3493: .  rtol - relative convergence tolerance
3494: .  stol -  convergence tolerance in terms of the norm
3495:            of the change in the solution between steps
3496: .  maxit - maximum number of iterations
3497: -  maxf - maximum number of function evaluations

3499:    Notes:
3500:    The user can specify NULL for any parameter that is not needed.

3502:    Level: intermediate

3504: .keywords: SNES, nonlinear, get, convergence, tolerances

3506: .seealso: SNESSetTolerances()
3507: @*/
3508: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3509: {
3512:   if (atol)  *atol  = snes->abstol;
3513:   if (rtol)  *rtol  = snes->rtol;
3514:   if (stol)  *stol  = snes->stol;
3515:   if (maxit) *maxit = snes->max_its;
3516:   if (maxf)  *maxf  = snes->max_funcs;
3517:   return(0);
3518: }

3520: /*@
3521:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3523:    Not Collective

3525:    Input Parameters:
3526: +  snes - the SNES context
3527: -  divtol - divergence tolerance

3529:    Level: intermediate

3531: .keywords: SNES, nonlinear, get, divergence, tolerance

3533: .seealso: SNESSetDivergenceTolerance()
3534: @*/
3535: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3536: {
3539:   if (divtol) *divtol = snes->divtol;
3540:   return(0);
3541: }

3543: /*@
3544:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3546:    Logically Collective on SNES

3548:    Input Parameters:
3549: +  snes - the SNES context
3550: -  tol - tolerance

3552:    Options Database Key:
3553: .  -snes_trtol <tol> - Sets tol

3555:    Level: intermediate

3557: .keywords: SNES, nonlinear, set, trust region, tolerance

3559: .seealso: SNESSetTolerances()
3560: @*/
3561: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3562: {
3566:   snes->deltatol = tol;
3567:   return(0);
3568: }

3570: /*
3571:    Duplicate the lg monitors for SNES from KSP; for some reason with
3572:    dynamic libraries things don't work under Sun4 if we just use
3573:    macros instead of functions
3574: */
3575: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3576: {

3581:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3582:   return(0);
3583: }

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

3590:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3591:   return(0);
3592: }

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

3596: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3597: {
3598:   PetscDrawLG      lg;
3599:   PetscErrorCode   ierr;
3600:   PetscReal        x,y,per;
3601:   PetscViewer      v = (PetscViewer)monctx;
3602:   static PetscReal prev; /* should be in the context */
3603:   PetscDraw        draw;

3607:   PetscViewerDrawGetDrawLG(v,0,&lg);
3608:   if (!n) {PetscDrawLGReset(lg);}
3609:   PetscDrawLGGetDraw(lg,&draw);
3610:   PetscDrawSetTitle(draw,"Residual norm");
3611:   x    = (PetscReal)n;
3612:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3613:   else y = -15.0;
3614:   PetscDrawLGAddPoint(lg,&x,&y);
3615:   if (n < 20 || !(n % 5) || snes->reason) {
3616:     PetscDrawLGDraw(lg);
3617:     PetscDrawLGSave(lg);
3618:   }

3620:   PetscViewerDrawGetDrawLG(v,1,&lg);
3621:   if (!n) {PetscDrawLGReset(lg);}
3622:   PetscDrawLGGetDraw(lg,&draw);
3623:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3624:    SNESMonitorRange_Private(snes,n,&per);
3625:   x    = (PetscReal)n;
3626:   y    = 100.0*per;
3627:   PetscDrawLGAddPoint(lg,&x,&y);
3628:   if (n < 20 || !(n % 5) || snes->reason) {
3629:     PetscDrawLGDraw(lg);
3630:     PetscDrawLGSave(lg);
3631:   }

3633:   PetscViewerDrawGetDrawLG(v,2,&lg);
3634:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3635:   PetscDrawLGGetDraw(lg,&draw);
3636:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3637:   x    = (PetscReal)n;
3638:   y    = (prev - rnorm)/prev;
3639:   PetscDrawLGAddPoint(lg,&x,&y);
3640:   if (n < 20 || !(n % 5) || snes->reason) {
3641:     PetscDrawLGDraw(lg);
3642:     PetscDrawLGSave(lg);
3643:   }

3645:   PetscViewerDrawGetDrawLG(v,3,&lg);
3646:   if (!n) {PetscDrawLGReset(lg);}
3647:   PetscDrawLGGetDraw(lg,&draw);
3648:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3649:   x    = (PetscReal)n;
3650:   y    = (prev - rnorm)/(prev*per);
3651:   if (n > 2) { /*skip initial crazy value */
3652:     PetscDrawLGAddPoint(lg,&x,&y);
3653:   }
3654:   if (n < 20 || !(n % 5) || snes->reason) {
3655:     PetscDrawLGDraw(lg);
3656:     PetscDrawLGSave(lg);
3657:   }
3658:   prev = rnorm;
3659:   return(0);
3660: }

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

3665:    Collective on SNES

3667:    Input Parameters:
3668: +  snes - nonlinear solver context obtained from SNESCreate()
3669: .  iter - iteration number
3670: -  rnorm - relative norm of the residual

3672:    Notes:
3673:    This routine is called by the SNES implementations.
3674:    It does not typically need to be called by the user.

3676:    Level: developer

3678: .seealso: SNESMonitorSet()
3679: @*/
3680: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3681: {
3683:   PetscInt       i,n = snes->numbermonitors;

3686:   VecLockPush(snes->vec_sol);
3687:   for (i=0; i<n; i++) {
3688:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3689:   }
3690:   VecLockPop(snes->vec_sol);
3691:   return(0);
3692: }

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

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

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

3703: +    snes - the SNES context
3704: .    its - iteration number
3705: .    norm - 2-norm function value (may be estimated)
3706: -    mctx - [optional] monitoring context

3708:    Level: advanced

3710: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3711: M*/

3713: /*@C
3714:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3715:    iteration of the nonlinear solver to display the iteration's
3716:    progress.

3718:    Logically Collective on SNES

3720:    Input Parameters:
3721: +  snes - the SNES context
3722: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3723: .  mctx - [optional] user-defined context for private data for the
3724:           monitor routine (use NULL if no context is desired)
3725: -  monitordestroy - [optional] routine that frees monitor context
3726:           (may be NULL)

3728:    Options Database Keys:
3729: +    -snes_monitor        - sets SNESMonitorDefault()
3730: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3731:                             uses SNESMonitorLGCreate()
3732: -    -snes_monitor_cancel - cancels all monitors that have
3733:                             been hardwired into a code by
3734:                             calls to SNESMonitorSet(), but
3735:                             does not cancel those set via
3736:                             the options database.

3738:    Notes:
3739:    Several different monitoring routines may be set by calling
3740:    SNESMonitorSet() multiple times; all will be called in the
3741:    order in which they were set.

3743:    Fortran Notes:
3744:     Only a single monitor function can be set for each SNES object

3746:    Level: intermediate

3748: .keywords: SNES, nonlinear, set, monitor

3750: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3751: @*/
3752: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3753: {
3754:   PetscInt       i;
3756:   PetscBool      identical;

3760:   for (i=0; i<snes->numbermonitors;i++) {
3761:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3762:     if (identical) return(0);
3763:   }
3764:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3765:   snes->monitor[snes->numbermonitors]          = f;
3766:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3767:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3768:   return(0);
3769: }

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

3774:    Logically Collective on SNES

3776:    Input Parameters:
3777: .  snes - the SNES context

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

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

3787:    Level: intermediate

3789: .keywords: SNES, nonlinear, set, monitor

3791: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3792: @*/
3793: PetscErrorCode  SNESMonitorCancel(SNES snes)
3794: {
3796:   PetscInt       i;

3800:   for (i=0; i<snes->numbermonitors; i++) {
3801:     if (snes->monitordestroy[i]) {
3802:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3803:     }
3804:   }
3805:   snes->numbermonitors = 0;
3806:   return(0);
3807: }

3809: /*MC
3810:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3816: +    snes - the SNES context
3817: .    it - current iteration (0 is the first and is before any Newton step)
3818: .    cctx - [optional] convergence context
3819: .    reason - reason for convergence/divergence
3820: .    xnorm - 2-norm of current iterate
3821: .    gnorm - 2-norm of current step
3822: -    f - 2-norm of function

3824:    Level: intermediate

3826: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3827: M*/

3829: /*@C
3830:    SNESSetConvergenceTest - Sets the function that is to be used
3831:    to test for convergence of the nonlinear iterative solution.

3833:    Logically Collective on SNES

3835:    Input Parameters:
3836: +  snes - the SNES context
3837: .  SNESConvergenceTestFunction - routine to test for convergence
3838: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3839: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3841:    Level: advanced

3843: .keywords: SNES, nonlinear, set, convergence, test

3845: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3846: @*/
3847: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3848: {

3853:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3854:   if (snes->ops->convergeddestroy) {
3855:     (*snes->ops->convergeddestroy)(snes->cnvP);
3856:   }
3857:   snes->ops->converged        = SNESConvergenceTestFunction;
3858:   snes->ops->convergeddestroy = destroy;
3859:   snes->cnvP                  = cctx;
3860:   return(0);
3861: }

3863: /*@
3864:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3866:    Not Collective

3868:    Input Parameter:
3869: .  snes - the SNES context

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

3875:    Options Database:
3876: .   -snes_converged_reason - prints the reason to standard out

3878:    Level: intermediate

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

3883: .keywords: SNES, nonlinear, set, convergence, test

3885: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
3886: @*/
3887: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3888: {
3892:   *reason = snes->reason;
3893:   return(0);
3894: }

3896: /*@
3897:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3899:    Not Collective

3901:    Input Parameters:
3902: +  snes - the SNES context
3903: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
3904:             manual pages for the individual convergence tests for complete lists

3906:    Level: intermediate

3908: .keywords: SNES, nonlinear, set, convergence, test
3909: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
3910: @*/
3911: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
3912: {
3915:   snes->reason = reason;
3916:   return(0);
3917: }

3919: /*@
3920:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3922:    Logically Collective on SNES

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

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

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

3940:    Level: intermediate

3942: .keywords: SNES, set, convergence, history

3944: .seealso: SNESGetConvergenceHistory()

3946: @*/
3947: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3948: {

3955:   if (!a) {
3956:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3957:     PetscCalloc1(na,&a);
3958:     PetscCalloc1(na,&its);

3960:     snes->conv_malloc = PETSC_TRUE;
3961:   }
3962:   snes->conv_hist       = a;
3963:   snes->conv_hist_its   = its;
3964:   snes->conv_hist_max   = na;
3965:   snes->conv_hist_len   = 0;
3966:   snes->conv_hist_reset = reset;
3967:   return(0);
3968: }

3970: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3971: #include <engine.h>   /* MATLAB include file */
3972: #include <mex.h>      /* MATLAB include file */

3974: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3975: {
3976:   mxArray   *mat;
3977:   PetscInt  i;
3978:   PetscReal *ar;

3981:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3982:   ar  = (PetscReal*) mxGetData(mat);
3983:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3984:   PetscFunctionReturn(mat);
3985: }
3986: #endif

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

3991:    Not Collective

3993:    Input Parameter:
3994: .  snes - iterative context obtained from SNESCreate()

3996:    Output Parameters:
3997: .  a   - array to hold history
3998: .  its - integer array holds the number of linear iterations (or
3999:          negative if not converged) for each solve.
4000: -  na  - size of a and its

4002:    Notes:
4003:     The calling sequence for this routine in Fortran is
4004: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

4010:    Level: intermediate

4012: .keywords: SNES, get, convergence, history

4014: .seealso: SNESSetConvergencHistory()

4016: @*/
4017: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4018: {
4021:   if (a)   *a   = snes->conv_hist;
4022:   if (its) *its = snes->conv_hist_its;
4023:   if (na)  *na  = snes->conv_hist_len;
4024:   return(0);
4025: }

4027: /*@C
4028:   SNESSetUpdate - Sets the general-purpose update function called
4029:   at the beginning of every iteration of the nonlinear solve. Specifically
4030:   it is called just before the Jacobian is "evaluated".

4032:   Logically Collective on SNES

4034:   Input Parameters:
4035: . snes - The nonlinear solver context
4036: . func - The function

4038:   Calling sequence of func:
4039: . func (SNES snes, PetscInt step);

4041: . step - The current step of the iteration

4043:   Level: advanced

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

4048: .keywords: SNES, update

4050: .seealso SNESSetJacobian(), SNESSolve()
4051: @*/
4052: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4053: {
4056:   snes->ops->update = func;
4057:   return(0);
4058: }

4060: /*
4061:    SNESScaleStep_Private - Scales a step so that its length is less than the
4062:    positive parameter delta.

4064:     Input Parameters:
4065: +   snes - the SNES context
4066: .   y - approximate solution of linear system
4067: .   fnorm - 2-norm of current function
4068: -   delta - trust region size

4070:     Output Parameters:
4071: +   gpnorm - predicted function norm at the new point, assuming local
4072:     linearization.  The value is zero if the step lies within the trust
4073:     region, and exceeds zero otherwise.
4074: -   ynorm - 2-norm of the step

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

4080: .keywords: SNES, nonlinear, scale, step
4081: */
4082: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4083: {
4084:   PetscReal      nrm;
4085:   PetscScalar    cnorm;


4093:   VecNorm(y,NORM_2,&nrm);
4094:   if (nrm > *delta) {
4095:     nrm     = *delta/nrm;
4096:     *gpnorm = (1.0 - nrm)*(*fnorm);
4097:     cnorm   = nrm;
4098:     VecScale(y,cnorm);
4099:     *ynorm  = *delta;
4100:   } else {
4101:     *gpnorm = 0.0;
4102:     *ynorm  = nrm;
4103:   }
4104:   return(0);
4105: }

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

4110:    Collective on SNES

4112:    Parameter:
4113: +  snes - iterative context obtained from SNESCreate()
4114: -  viewer - the viewer to display the reason


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

4120:    Level: beginner

4122: .keywords: SNES, solve, linear system

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

4126: @*/
4127: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
4128: {
4129:   PetscViewerFormat format;
4130:   PetscBool         isAscii;
4131:   PetscErrorCode    ierr;

4134:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
4135:   if (isAscii) {
4136:     PetscViewerGetFormat(viewer, &format);
4137:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
4138:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4139:       DM                dm;
4140:       Vec               u;
4141:       PetscDS           prob;
4142:       PetscInt          Nf, f;
4143:       PetscErrorCode (**exactFuncs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4144:       PetscReal         error;

4146:       SNESGetDM(snes, &dm);
4147:       SNESGetSolution(snes, &u);
4148:       DMGetDS(dm, &prob);
4149:       PetscDSGetNumFields(prob, &Nf);
4150:       PetscMalloc1(Nf, &exactFuncs);
4151:       for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactFuncs[f]);}
4152:       DMComputeL2Diff(dm, 0.0, exactFuncs, NULL, u, &error);
4153:       PetscFree(exactFuncs);
4154:       if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
4155:       else                 {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
4156:     }
4157:     if (snes->reason > 0) {
4158:       if (((PetscObject) snes)->prefix) {
4159:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4160:       } else {
4161:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4162:       }
4163:     } else {
4164:       if (((PetscObject) snes)->prefix) {
4165:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4166:       } else {
4167:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4168:       }
4169:     }
4170:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4171:   }
4172:   return(0);
4173: }

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

4178:   Collective on SNES

4180:   Input Parameters:
4181: . snes   - the SNES object

4183:   Level: intermediate

4185: @*/
4186: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
4187: {
4188:   PetscErrorCode    ierr;
4189:   PetscViewer       viewer;
4190:   PetscBool         flg;
4191:   static PetscBool  incall = PETSC_FALSE;
4192:   PetscViewerFormat format;

4195:   if (incall) return(0);
4196:   incall = PETSC_TRUE;
4197:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4198:   if (flg) {
4199:     PetscViewerPushFormat(viewer,format);
4200:     SNESReasonView(snes,viewer);
4201:     PetscViewerPopFormat(viewer);
4202:     PetscViewerDestroy(&viewer);
4203:   }
4204:   incall = PETSC_FALSE;
4205:   return(0);
4206: }

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

4212:    Collective on SNES

4214:    Input Parameters:
4215: +  snes - the SNES context
4216: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4217: -  x - the solution vector.

4219:    Notes:
4220:    The user should initialize the vector,x, with the initial guess
4221:    for the nonlinear solve prior to calling SNESSolve.  In particular,
4222:    to employ an initial guess of zero, the user should explicitly set
4223:    this vector to zero by calling VecSet().

4225:    Level: beginner

4227: .keywords: SNES, nonlinear, solve

4229: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4230: @*/
4231: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4232: {
4233:   PetscErrorCode    ierr;
4234:   PetscBool         flg;
4235:   PetscInt          grid;
4236:   Vec               xcreated = NULL;
4237:   DM                dm;


4246:   /* High level operations using the nonlinear solver */
4247:   {
4248:     PetscViewer       viewer;
4249:     PetscViewerFormat format;
4250:     PetscInt          num;
4251:     PetscBool         flg;
4252:     static PetscBool  incall = PETSC_FALSE;

4254:     if (!incall) {
4255:       /* Estimate the convergence rate of the discretization */
4256:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes), ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4257:       if (flg) {
4258:         PetscConvEst conv;
4259:         PetscReal    alpha; /* Convergence rate of the solution error in the L_2 norm */

4261:         incall = PETSC_TRUE;
4262:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4263:         PetscConvEstSetSolver(conv, snes);
4264:         PetscConvEstSetFromOptions(conv);
4265:         PetscConvEstSetUp(conv);
4266:         PetscConvEstGetConvRate(conv, &alpha);
4267:         PetscViewerPushFormat(viewer, format);
4268:         PetscConvEstRateView(conv, alpha, viewer);
4269:         PetscViewerPopFormat(viewer);
4270:         PetscViewerDestroy(&viewer);
4271:         PetscConvEstDestroy(&conv);
4272:         incall = PETSC_FALSE;
4273:       }
4274:       /* Adaptively refine the initial grid */
4275:       num  = 1;
4276:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);
4277:       if (flg) {
4278:         DMAdaptor adaptor;

4280:         incall = PETSC_TRUE;
4281:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4282:         DMAdaptorSetSolver(adaptor, snes);
4283:         DMAdaptorSetSequenceLength(adaptor, num);
4284:         DMAdaptorSetFromOptions(adaptor);
4285:         DMAdaptorSetUp(adaptor);
4286:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4287:         DMAdaptorDestroy(&adaptor);
4288:         incall = PETSC_FALSE;
4289:       }
4290:       /* Use grid sequencing to adapt */
4291:       num  = 0;
4292:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4293:       if (num) {
4294:         DMAdaptor adaptor;

4296:         incall = PETSC_TRUE;
4297:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4298:         DMAdaptorSetSolver(adaptor, snes);
4299:         DMAdaptorSetSequenceLength(adaptor, num);
4300:         DMAdaptorSetFromOptions(adaptor);
4301:         DMAdaptorSetUp(adaptor);
4302:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4303:         DMAdaptorDestroy(&adaptor);
4304:         incall = PETSC_FALSE;
4305:       }
4306:     }
4307:   }
4308:   if (!x) {
4309:     SNESGetDM(snes,&dm);
4310:     DMCreateGlobalVector(dm,&xcreated);
4311:     x    = xcreated;
4312:   }
4313:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4318:     /* set solution vector */
4319:     if (!grid) {PetscObjectReference((PetscObject)x);}
4320:     VecDestroy(&snes->vec_sol);
4321:     snes->vec_sol = x;
4322:     SNESGetDM(snes,&dm);

4324:     /* set affine vector if provided */
4325:     if (b) { PetscObjectReference((PetscObject)b); }
4326:     VecDestroy(&snes->vec_rhs);
4327:     snes->vec_rhs = b;

4329:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4330:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4331:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4332:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4333:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4334:     }
4335:     DMShellSetGlobalVector(dm,snes->vec_sol);
4336:     SNESSetUp(snes);

4338:     if (!grid) {
4339:       if (snes->ops->computeinitialguess) {
4340:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4341:       }
4342:     }

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

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

4353:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4354:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

4356:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_test_local_min",NULL,NULL,&flg);
4357:     if (flg && !PetscPreLoadingOn) { SNESTestLocalMin(snes); }
4358:     SNESReasonViewFromOptions(snes);

4360:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4361:     if (snes->reason < 0) break;
4362:     if (grid <  snes->gridsequence) {
4363:       DM  fine;
4364:       Vec xnew;
4365:       Mat interp;

4367:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4368:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4369:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4370:       DMCreateGlobalVector(fine,&xnew);
4371:       MatInterpolate(interp,x,xnew);
4372:       DMInterpolate(snes->dm,interp,fine);
4373:       MatDestroy(&interp);
4374:       x    = xnew;

4376:       SNESReset(snes);
4377:       SNESSetDM(snes,fine);
4378:       DMDestroy(&fine);
4379:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4380:     }
4381:   }
4382:   SNESViewFromOptions(snes,NULL,"-snes_view");
4383:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4385:   VecDestroy(&xcreated);
4386:   PetscObjectSAWsBlock((PetscObject)snes);
4387:   return(0);
4388: }

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

4392: /*@C
4393:    SNESSetType - Sets the method for the nonlinear solver.

4395:    Collective on SNES

4397:    Input Parameters:
4398: +  snes - the SNES context
4399: -  type - a known method

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

4405:    Notes:
4406:    See "petsc/include/petscsnes.h" for available methods (for instance)
4407: +    SNESNEWTONLS - Newton's method with line search
4408:      (systems of nonlinear equations)
4409: .    SNESNEWTONTR - Newton's method with trust region
4410:      (systems of nonlinear equations)

4412:   Normally, it is best to use the SNESSetFromOptions() command and then
4413:   set the SNES solver type from the options database rather than by using
4414:   this routine.  Using the options database provides the user with
4415:   maximum flexibility in evaluating the many nonlinear solvers.
4416:   The SNESSetType() routine is provided for those situations where it
4417:   is necessary to set the nonlinear solver independently of the command
4418:   line or options database.  This might be the case, for example, when
4419:   the choice of solver changes during the execution of the program,
4420:   and the user's application is taking responsibility for choosing the
4421:   appropriate method.

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

4427:   Level: intermediate

4429: .keywords: SNES, set, type

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

4433: @*/
4434: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4435: {
4436:   PetscErrorCode ierr,(*r)(SNES);
4437:   PetscBool      match;


4443:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4444:   if (match) return(0);

4446:    PetscFunctionListFind(SNESList,type,&r);
4447:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4448:   /* Destroy the previous private SNES context */
4449:   if (snes->ops->destroy) {
4450:     (*(snes)->ops->destroy)(snes);
4451:     snes->ops->destroy = NULL;
4452:   }
4453:   /* Reinitialize function pointers in SNESOps structure */
4454:   snes->ops->setup          = 0;
4455:   snes->ops->solve          = 0;
4456:   snes->ops->view           = 0;
4457:   snes->ops->setfromoptions = 0;
4458:   snes->ops->destroy        = 0;
4459:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4460:   snes->setupcalled = PETSC_FALSE;

4462:   PetscObjectChangeTypeName((PetscObject)snes,type);
4463:   (*r)(snes);
4464:   return(0);
4465: }

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

4470:    Not Collective

4472:    Input Parameter:
4473: .  snes - nonlinear solver context

4475:    Output Parameter:
4476: .  type - SNES method (a character string)

4478:    Level: intermediate

4480: .keywords: SNES, nonlinear, get, type, name
4481: @*/
4482: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4483: {
4487:   *type = ((PetscObject)snes)->type_name;
4488:   return(0);
4489: }

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

4494:   Logically Collective on SNES and Vec

4496:   Input Parameters:
4497: + snes - the SNES context obtained from SNESCreate()
4498: - u    - the solution vector

4500:   Level: beginner

4502: .keywords: SNES, set, solution
4503: @*/
4504: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4505: {
4506:   DM             dm;

4512:   PetscObjectReference((PetscObject) u);
4513:   VecDestroy(&snes->vec_sol);

4515:   snes->vec_sol = u;

4517:   SNESGetDM(snes, &dm);
4518:   DMShellSetGlobalVector(dm, u);
4519:   return(0);
4520: }

4522: /*@
4523:    SNESGetSolution - Returns the vector where the approximate solution is
4524:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4528:    Input Parameter:
4529: .  snes - the SNES context

4531:    Output Parameter:
4532: .  x - the solution

4534:    Level: intermediate

4536: .keywords: SNES, nonlinear, get, solution

4538: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4539: @*/
4540: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4541: {
4545:   *x = snes->vec_sol;
4546:   return(0);
4547: }

4549: /*@
4550:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4551:    stored.

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

4555:    Input Parameter:
4556: .  snes - the SNES context

4558:    Output Parameter:
4559: .  x - the solution update

4561:    Level: advanced

4563: .keywords: SNES, nonlinear, get, solution, update

4565: .seealso: SNESGetSolution(), SNESGetFunction()
4566: @*/
4567: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4568: {
4572:   *x = snes->vec_sol_update;
4573:   return(0);
4574: }

4576: /*@C
4577:    SNESGetFunction - Returns the vector where the function is stored.

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

4581:    Input Parameter:
4582: .  snes - the SNES context

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

4589:    Level: advanced

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

4593: .keywords: SNES, nonlinear, get, function

4595: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4596: @*/
4597: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4598: {
4600:   DM             dm;

4604:   if (r) {
4605:     if (!snes->vec_func) {
4606:       if (snes->vec_rhs) {
4607:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4608:       } else if (snes->vec_sol) {
4609:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4610:       } else if (snes->dm) {
4611:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4612:       }
4613:     }
4614:     *r = snes->vec_func;
4615:   }
4616:   SNESGetDM(snes,&dm);
4617:   DMSNESGetFunction(dm,f,ctx);
4618:   return(0);
4619: }

4621: /*@C
4622:    SNESGetNGS - Returns the NGS function and context.

4624:    Input Parameter:
4625: .  snes - the SNES context

4627:    Output Parameter:
4628: +  f - the function (or NULL) see SNESNGSFunction for details
4629: -  ctx    - the function context (or NULL)

4631:    Level: advanced

4633: .keywords: SNES, nonlinear, get, function

4635: .seealso: SNESSetNGS(), SNESGetFunction()
4636: @*/

4638: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4639: {
4641:   DM             dm;

4645:   SNESGetDM(snes,&dm);
4646:   DMSNESGetNGS(dm,f,ctx);
4647:   return(0);
4648: }

4650: /*@C
4651:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4652:    SNES options in the database.

4654:    Logically Collective on SNES

4656:    Input Parameter:
4657: +  snes - the SNES context
4658: -  prefix - the prefix to prepend to all option names

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

4664:    Level: advanced

4666: .keywords: SNES, set, options, prefix, database

4668: .seealso: SNESSetFromOptions()
4669: @*/
4670: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4671: {

4676:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4677:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4678:   if (snes->linesearch) {
4679:     SNESGetLineSearch(snes,&snes->linesearch);
4680:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4681:   }
4682:   KSPSetOptionsPrefix(snes->ksp,prefix);
4683:   return(0);
4684: }

4686: /*@C
4687:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4688:    SNES options in the database.

4690:    Logically Collective on SNES

4692:    Input Parameters:
4693: +  snes - the SNES context
4694: -  prefix - the prefix to prepend to all option names

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

4700:    Level: advanced

4702: .keywords: SNES, append, options, prefix, database

4704: .seealso: SNESGetOptionsPrefix()
4705: @*/
4706: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4707: {

4712:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4713:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4714:   if (snes->linesearch) {
4715:     SNESGetLineSearch(snes,&snes->linesearch);
4716:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4717:   }
4718:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4719:   return(0);
4720: }

4722: /*@C
4723:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4724:    SNES options in the database.

4726:    Not Collective

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

4731:    Output Parameter:
4732: .  prefix - pointer to the prefix string used

4734:    Notes:
4735:     On the fortran side, the user should pass in a string 'prefix' of
4736:    sufficient length to hold the prefix.

4738:    Level: advanced

4740: .keywords: SNES, get, options, prefix, database

4742: .seealso: SNESAppendOptionsPrefix()
4743: @*/
4744: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4745: {

4750:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4751:   return(0);
4752: }


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

4758:    Not collective

4760:    Input Parameters:
4761: +  name_solver - name of a new user-defined solver
4762: -  routine_create - routine to create method context

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

4767:    Sample usage:
4768: .vb
4769:    SNESRegister("my_solver",MySolverCreate);
4770: .ve

4772:    Then, your solver can be chosen with the procedural interface via
4773: $     SNESSetType(snes,"my_solver")
4774:    or at runtime via the option
4775: $     -snes_type my_solver

4777:    Level: advanced

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

4781: .keywords: SNES, nonlinear, register

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

4785:   Level: advanced
4786: @*/
4787: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4788: {

4792:   PetscFunctionListAdd(&SNESList,sname,function);
4793:   return(0);
4794: }

4796: PetscErrorCode  SNESTestLocalMin(SNES snes)
4797: {
4799:   PetscInt       N,i,j;
4800:   Vec            u,uh,fh;
4801:   PetscScalar    value;
4802:   PetscReal      norm;

4805:   SNESGetSolution(snes,&u);
4806:   VecDuplicate(u,&uh);
4807:   VecDuplicate(u,&fh);

4809:   /* currently only works for sequential */
4810:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4811:   VecGetSize(u,&N);
4812:   for (i=0; i<N; i++) {
4813:     VecCopy(u,uh);
4814:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4815:     for (j=-10; j<11; j++) {
4816:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4817:       VecSetValue(uh,i,value,ADD_VALUES);
4818:       SNESComputeFunction(snes,uh,fh);
4819:       VecNorm(fh,NORM_2,&norm);
4820:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4821:       value = -value;
4822:       VecSetValue(uh,i,value,ADD_VALUES);
4823:     }
4824:   }
4825:   VecDestroy(&uh);
4826:   VecDestroy(&fh);
4827:   return(0);
4828: }

4830: /*@
4831:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4832:    computing relative tolerance for linear solvers within an inexact
4833:    Newton method.

4835:    Logically Collective on SNES

4837:    Input Parameters:
4838: +  snes - SNES context
4839: -  flag - PETSC_TRUE or PETSC_FALSE

4841:     Options Database:
4842: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4843: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4844: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4845: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4846: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4847: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4848: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4849: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4851:    Notes:
4852:    Currently, the default is to use a constant relative tolerance for
4853:    the inner linear solvers.  Alternatively, one can use the
4854:    Eisenstat-Walker method, where the relative convergence tolerance
4855:    is reset at each Newton iteration according progress of the nonlinear
4856:    solver.

4858:    Level: advanced

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

4864: .keywords: SNES, KSP, Eisenstat, Walker, convergence, test, inexact, Newton

4866: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4867: @*/
4868: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4869: {
4873:   snes->ksp_ewconv = flag;
4874:   return(0);
4875: }

4877: /*@
4878:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4879:    for computing relative tolerance for linear solvers within an
4880:    inexact Newton method.

4882:    Not Collective

4884:    Input Parameter:
4885: .  snes - SNES context

4887:    Output Parameter:
4888: .  flag - PETSC_TRUE or PETSC_FALSE

4890:    Notes:
4891:    Currently, the default is to use a constant relative tolerance for
4892:    the inner linear solvers.  Alternatively, one can use the
4893:    Eisenstat-Walker method, where the relative convergence tolerance
4894:    is reset at each Newton iteration according progress of the nonlinear
4895:    solver.

4897:    Level: advanced

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

4903: .keywords: SNES, KSP, Eisenstat, Walker, convergence, test, inexact, Newton

4905: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4906: @*/
4907: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4908: {
4912:   *flag = snes->ksp_ewconv;
4913:   return(0);
4914: }

4916: /*@
4917:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4918:    convergence criteria for the linear solvers within an inexact
4919:    Newton method.

4921:    Logically Collective on SNES

4923:    Input Parameters:
4924: +    snes - SNES context
4925: .    version - version 1, 2 (default is 2) or 3
4926: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4927: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4928: .    gamma - multiplicative factor for version 2 rtol computation
4929:              (0 <= gamma2 <= 1)
4930: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4931: .    alpha2 - power for safeguard
4932: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4934:    Note:
4935:    Version 3 was contributed by Luis Chacon, June 2006.

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

4939:    Level: advanced

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

4946: .keywords: SNES, KSP, Eisenstat, Walker, set, parameters

4948: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4949: @*/
4950: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4951: {
4952:   SNESKSPEW *kctx;

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

4966:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4967:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4968:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4969:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4970:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4971:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4972:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4974:   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);
4975:   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);
4976:   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);
4977:   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);
4978:   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);
4979:   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);
4980:   return(0);
4981: }

4983: /*@
4984:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4985:    convergence criteria for the linear solvers within an inexact
4986:    Newton method.

4988:    Not Collective

4990:    Input Parameters:
4991:      snes - SNES context

4993:    Output Parameters:
4994: +    version - version 1, 2 (default is 2) or 3
4995: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4996: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4997: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
4998: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4999: .    alpha2 - power for safeguard
5000: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5002:    Level: advanced

5004: .keywords: SNES, KSP, Eisenstat, Walker, get, parameters

5006: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
5007: @*/
5008: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
5009: {
5010:   SNESKSPEW *kctx;

5014:   kctx = (SNESKSPEW*)snes->kspconvctx;
5015:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5016:   if (version)   *version   = kctx->version;
5017:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
5018:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
5019:   if (gamma)     *gamma     = kctx->gamma;
5020:   if (alpha)     *alpha     = kctx->alpha;
5021:   if (alpha2)    *alpha2    = kctx->alpha2;
5022:   if (threshold) *threshold = kctx->threshold;
5023:   return(0);
5024: }

5026:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5027: {
5029:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5030:   PetscReal      rtol  = PETSC_DEFAULT,stol;

5033:   if (!snes->ksp_ewconv) return(0);
5034:   if (!snes->iter) {
5035:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5036:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
5037:   }
5038:   else {
5039:     if (kctx->version == 1) {
5040:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
5041:       if (rtol < 0.0) rtol = -rtol;
5042:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5043:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5044:     } else if (kctx->version == 2) {
5045:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5046:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5047:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5048:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5049:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5050:       /* safeguard: avoid sharp decrease of rtol */
5051:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5052:       stol = PetscMax(rtol,stol);
5053:       rtol = PetscMin(kctx->rtol_0,stol);
5054:       /* safeguard: avoid oversolving */
5055:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5056:       stol = PetscMax(rtol,stol);
5057:       rtol = PetscMin(kctx->rtol_0,stol);
5058:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
5059:   }
5060:   /* safeguard: avoid rtol greater than one */
5061:   rtol = PetscMin(rtol,kctx->rtol_max);
5062:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
5063:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
5064:   return(0);
5065: }

5067: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5068: {
5070:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5071:   PCSide         pcside;
5072:   Vec            lres;

5075:   if (!snes->ksp_ewconv) return(0);
5076:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
5077:   kctx->norm_last = snes->norm;
5078:   if (kctx->version == 1) {
5079:     PC        pc;
5080:     PetscBool isNone;

5082:     KSPGetPC(ksp, &pc);
5083:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
5084:     KSPGetPCSide(ksp,&pcside);
5085:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
5086:       /* KSP residual is true linear residual */
5087:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
5088:     } else {
5089:       /* KSP residual is preconditioned residual */
5090:       /* compute true linear residual norm */
5091:       VecDuplicate(b,&lres);
5092:       MatMult(snes->jacobian,x,lres);
5093:       VecAYPX(lres,-1.0,b);
5094:       VecNorm(lres,NORM_2,&kctx->lresid_last);
5095:       VecDestroy(&lres);
5096:     }
5097:   }
5098:   return(0);
5099: }

5101: /*@
5102:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

5106:    Input Parameter:
5107: .  snes - the SNES context

5109:    Output Parameter:
5110: .  ksp - the KSP context

5112:    Notes:
5113:    The user can then directly manipulate the KSP context to set various
5114:    options, etc.  Likewise, the user can then extract and manipulate the
5115:    PC contexts as well.

5117:    Level: beginner

5119: .keywords: SNES, nonlinear, get, KSP, context

5121: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5122: @*/
5123: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
5124: {


5131:   if (!snes->ksp) {
5132:     PetscBool monitor = PETSC_FALSE;

5134:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
5135:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
5136:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

5141:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
5142:     if (monitor) {
5143:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
5144:     }
5145:     monitor = PETSC_FALSE;
5146:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
5147:     if (monitor) {
5148:       PetscObject *objs;
5149:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
5150:       objs[0] = (PetscObject) snes;
5151:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
5152:     }
5153:   }
5154:   *ksp = snes->ksp;
5155:   return(0);
5156: }


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

5163:    Logically Collective on SNES

5165:    Input Parameters:
5166: +  snes - the nonlinear solver context
5167: -  dm - the dm, cannot be NULL

5169:    Level: intermediate

5171: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
5172: @*/
5173: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5174: {
5176:   KSP            ksp;
5177:   DMSNES         sdm;

5182:   PetscObjectReference((PetscObject)dm);
5183:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5184:     if (snes->dm->dmsnes && !dm->dmsnes) {
5185:       DMCopyDMSNES(snes->dm,dm);
5186:       DMGetDMSNES(snes->dm,&sdm);
5187:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5188:     }
5189:     DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5190:     DMDestroy(&snes->dm);
5191:   }
5192:   snes->dm     = dm;
5193:   snes->dmAuto = PETSC_FALSE;

5195:   SNESGetKSP(snes,&ksp);
5196:   KSPSetDM(ksp,dm);
5197:   KSPSetDMActive(ksp,PETSC_FALSE);
5198:   if (snes->npc) {
5199:     SNESSetDM(snes->npc, snes->dm);
5200:     SNESSetNPCSide(snes,snes->npcside);
5201:   }
5202:   return(0);
5203: }

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

5208:    Not Collective but DM obtained is parallel on SNES

5210:    Input Parameter:
5211: . snes - the preconditioner context

5213:    Output Parameter:
5214: .  dm - the dm

5216:    Level: intermediate

5218: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5219: @*/
5220: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5221: {

5226:   if (!snes->dm) {
5227:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5228:     snes->dmAuto = PETSC_TRUE;
5229:   }
5230:   *dm = snes->dm;
5231:   return(0);
5232: }

5234: /*@
5235:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5237:   Collective on SNES

5239:   Input Parameters:
5240: + snes - iterative context obtained from SNESCreate()
5241: - pc   - the preconditioner object

5243:   Notes:
5244:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5245:   to configure it using the API).

5247:   Level: developer

5249: .keywords: SNES, set, precondition
5250: .seealso: SNESGetNPC(), SNESHasNPC()
5251: @*/
5252: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5253: {

5260:   PetscObjectReference((PetscObject) pc);
5261:   SNESDestroy(&snes->npc);
5262:   snes->npc = pc;
5263:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5264:   return(0);
5265: }

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

5270:   Not Collective

5272:   Input Parameter:
5273: . snes - iterative context obtained from SNESCreate()

5275:   Output Parameter:
5276: . pc - preconditioner context

5278:   Notes:
5279:     If a SNES was previously set with SNESSetNPC() then that SNES is returned.

5281:   Level: developer

5283: .keywords: SNES, get, preconditioner
5284: .seealso: SNESSetNPC(), SNESHasNPC()
5285: @*/
5286: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5287: {
5289:   const char     *optionsprefix;

5294:   if (!snes->npc) {
5295:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5296:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5297:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5298:     SNESGetOptionsPrefix(snes,&optionsprefix);
5299:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5300:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5301:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5302:   }
5303:   *pc = snes->npc;
5304:   return(0);
5305: }

5307: /*@
5308:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5310:   Not Collective

5312:   Input Parameter:
5313: . snes - iterative context obtained from SNESCreate()

5315:   Output Parameter:
5316: . has_npc - whether the SNES has an NPC or not

5318:   Level: developer

5320: .keywords: SNES, has, preconditioner
5321: .seealso: SNESSetNPC(), SNESGetNPC()
5322: @*/
5323: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5324: {
5327:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5328:   return(0);
5329: }

5331: /*@
5332:     SNESSetNPCSide - Sets the preconditioning side.

5334:     Logically Collective on SNES

5336:     Input Parameter:
5337: .   snes - iterative context obtained from SNESCreate()

5339:     Output Parameter:
5340: .   side - the preconditioning side, where side is one of
5341: .vb
5342:       PC_LEFT - left preconditioning
5343:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5344: .ve

5346:     Options Database Keys:
5347: .   -snes_pc_side <right,left>

5349:     Notes:
5350:     SNESNRICHARDSON and SNESNCG only support left preconditioning.

5352:     Level: intermediate

5354: .keywords: SNES, set, right, left, side, preconditioner, flag

5356: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5357: @*/
5358: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5359: {
5363:   snes->npcside= side;
5364:   return(0);
5365: }

5367: /*@
5368:     SNESGetNPCSide - Gets the preconditioning side.

5370:     Not Collective

5372:     Input Parameter:
5373: .   snes - iterative context obtained from SNESCreate()

5375:     Output Parameter:
5376: .   side - the preconditioning side, where side is one of
5377: .vb
5378:       PC_LEFT - left preconditioning
5379:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5380: .ve

5382:     Level: intermediate

5384: .keywords: SNES, get, right, left, side, preconditioner, flag

5386: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5387: @*/
5388: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5389: {
5393:   *side = snes->npcside;
5394:   return(0);
5395: }

5397: /*@
5398:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5400:   Collective on SNES

5402:   Input Parameters:
5403: + snes - iterative context obtained from SNESCreate()
5404: - linesearch   - the linesearch object

5406:   Notes:
5407:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5408:   to configure it using the API).

5410:   Level: developer

5412: .keywords: SNES, set, linesearch
5413: .seealso: SNESGetLineSearch()
5414: @*/
5415: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5416: {

5423:   PetscObjectReference((PetscObject) linesearch);
5424:   SNESLineSearchDestroy(&snes->linesearch);

5426:   snes->linesearch = linesearch;

5428:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5429:   return(0);
5430: }

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

5436:   Not Collective

5438:   Input Parameter:
5439: . snes - iterative context obtained from SNESCreate()

5441:   Output Parameter:
5442: . linesearch - linesearch context

5444:   Level: beginner

5446: .keywords: SNES, get, linesearch
5447: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5448: @*/
5449: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5450: {
5452:   const char     *optionsprefix;

5457:   if (!snes->linesearch) {
5458:     SNESGetOptionsPrefix(snes, &optionsprefix);
5459:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5460:     SNESLineSearchSetSNES(snes->linesearch, snes);
5461:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5462:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5463:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5464:   }
5465:   *linesearch = snes->linesearch;
5466:   return(0);
5467: }

5469: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5470: #include <mex.h>

5472: typedef struct {char *funcname; mxArray *ctx;} SNESMatlabContext;

5474: /*
5475:    SNESComputeFunction_Matlab - Calls the function that has been set with SNESSetFunctionMatlab().

5477:    Collective on SNES

5479:    Input Parameters:
5480: +  snes - the SNES context
5481: -  x - input vector

5483:    Output Parameter:
5484: .  y - function vector, as set by SNESSetFunction()

5486:    Notes:
5487:    SNESComputeFunction() is typically used within nonlinear solvers
5488:    implementations, so most users would not generally call this routine
5489:    themselves.

5491:    Level: developer

5493: .keywords: SNES, nonlinear, compute, function

5495: .seealso: SNESSetFunction(), SNESGetFunction()
5496: */
5497: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5498: {
5499:   PetscErrorCode    ierr;
5500:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5501:   int               nlhs  = 1,nrhs = 5;
5502:   mxArray           *plhs[1],*prhs[5];
5503:   long long int     lx = 0,ly = 0,ls = 0;


5512:   /* call Matlab function in ctx with arguments x and y */

5514:   PetscMemcpy(&ls,&snes,sizeof(snes));
5515:   PetscMemcpy(&lx,&x,sizeof(x));
5516:   PetscMemcpy(&ly,&y,sizeof(x));
5517:   prhs[0] = mxCreateDoubleScalar((double)ls);
5518:   prhs[1] = mxCreateDoubleScalar((double)lx);
5519:   prhs[2] = mxCreateDoubleScalar((double)ly);
5520:   prhs[3] = mxCreateString(sctx->funcname);
5521:   prhs[4] = sctx->ctx;
5522:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");
5523:   mxGetScalar(plhs[0]);
5524:   mxDestroyArray(prhs[0]);
5525:   mxDestroyArray(prhs[1]);
5526:   mxDestroyArray(prhs[2]);
5527:   mxDestroyArray(prhs[3]);
5528:   mxDestroyArray(plhs[0]);
5529:   return(0);
5530: }

5532: /*
5533:    SNESSetFunctionMatlab - Sets the function evaluation routine and function
5534:    vector for use by the SNES routines in solving systems of nonlinear
5535:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

5537:    Logically Collective on SNES

5539:    Input Parameters:
5540: +  snes - the SNES context
5541: .  r - vector to store function value
5542: -  f - function evaluation routine

5544:    Notes:
5545:    The Newton-like methods typically solve linear systems of the form
5546: $      f'(x) x = -f(x),
5547:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5549:    Level: beginner

5551:    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;

5553: .keywords: SNES, nonlinear, set, function

5555: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5556: */
5557: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5558: {
5559:   PetscErrorCode    ierr;
5560:   SNESMatlabContext *sctx;

5563:   /* currently sctx is memory bleed */
5564:   PetscNew(&sctx);
5565:   PetscStrallocpy(f,&sctx->funcname);
5566:   /*
5567:      This should work, but it doesn't
5568:   sctx->ctx = ctx;
5569:   mexMakeArrayPersistent(sctx->ctx);
5570:   */
5571:   sctx->ctx = mxDuplicateArray(ctx);
5572:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5573:   return(0);
5574: }

5576: /*
5577:    SNESComputeJacobian_Matlab - Calls the function that has been set with SNESSetJacobianMatlab().

5579:    Collective on SNES

5581:    Input Parameters:
5582: +  snes - the SNES context
5583: .  x - input vector
5584: .  A, B - the matrices
5585: -  ctx - user context

5587:    Level: developer

5589: .keywords: SNES, nonlinear, compute, function

5591: .seealso: SNESSetFunction(), SNESGetFunction()
5592: @*/
5593: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5594: {
5595:   PetscErrorCode    ierr;
5596:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5597:   int               nlhs  = 2,nrhs = 6;
5598:   mxArray           *plhs[2],*prhs[6];
5599:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


5605:   /* call Matlab function in ctx with arguments x and y */

5607:   PetscMemcpy(&ls,&snes,sizeof(snes));
5608:   PetscMemcpy(&lx,&x,sizeof(x));
5609:   PetscMemcpy(&lA,A,sizeof(x));
5610:   PetscMemcpy(&lB,B,sizeof(x));
5611:   prhs[0] = mxCreateDoubleScalar((double)ls);
5612:   prhs[1] = mxCreateDoubleScalar((double)lx);
5613:   prhs[2] = mxCreateDoubleScalar((double)lA);
5614:   prhs[3] = mxCreateDoubleScalar((double)lB);
5615:   prhs[4] = mxCreateString(sctx->funcname);
5616:   prhs[5] = sctx->ctx;
5617:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5618:   mxGetScalar(plhs[0]);
5619:   mxDestroyArray(prhs[0]);
5620:   mxDestroyArray(prhs[1]);
5621:   mxDestroyArray(prhs[2]);
5622:   mxDestroyArray(prhs[3]);
5623:   mxDestroyArray(prhs[4]);
5624:   mxDestroyArray(plhs[0]);
5625:   mxDestroyArray(plhs[1]);
5626:   return(0);
5627: }

5629: /*
5630:    SNESSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
5631:    vector for use by the SNES routines in solving systems of nonlinear
5632:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

5634:    Logically Collective on SNES

5636:    Input Parameters:
5637: +  snes - the SNES context
5638: .  A,B - Jacobian matrices
5639: .  J - function evaluation routine
5640: -  ctx - user context

5642:    Level: developer

5644:    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;

5646: .keywords: SNES, nonlinear, set, function

5648: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5649: */
5650: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5651: {
5652:   PetscErrorCode    ierr;
5653:   SNESMatlabContext *sctx;

5656:   /* currently sctx is memory bleed */
5657:   PetscNew(&sctx);
5658:   PetscStrallocpy(J,&sctx->funcname);
5659:   /*
5660:      This should work, but it doesn't
5661:   sctx->ctx = ctx;
5662:   mexMakeArrayPersistent(sctx->ctx);
5663:   */
5664:   sctx->ctx = mxDuplicateArray(ctx);
5665:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5666:   return(0);
5667: }

5669: /*
5670:    SNESMonitor_Matlab - Calls the function that has been set with SNESMonitorSetMatlab().

5672:    Collective on SNES

5674: .seealso: SNESSetFunction(), SNESGetFunction()
5675: @*/
5676: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5677: {
5678:   PetscErrorCode    ierr;
5679:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5680:   int               nlhs  = 1,nrhs = 6;
5681:   mxArray           *plhs[1],*prhs[6];
5682:   long long int     lx = 0,ls = 0;
5683:   Vec               x  = snes->vec_sol;


5688:   PetscMemcpy(&ls,&snes,sizeof(snes));
5689:   PetscMemcpy(&lx,&x,sizeof(x));
5690:   prhs[0] = mxCreateDoubleScalar((double)ls);
5691:   prhs[1] = mxCreateDoubleScalar((double)it);
5692:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5693:   prhs[3] = mxCreateDoubleScalar((double)lx);
5694:   prhs[4] = mxCreateString(sctx->funcname);
5695:   prhs[5] = sctx->ctx;
5696:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5697:   mxGetScalar(plhs[0]);
5698:   mxDestroyArray(prhs[0]);
5699:   mxDestroyArray(prhs[1]);
5700:   mxDestroyArray(prhs[2]);
5701:   mxDestroyArray(prhs[3]);
5702:   mxDestroyArray(prhs[4]);
5703:   mxDestroyArray(plhs[0]);
5704:   return(0);
5705: }

5707: /*
5708:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5710:    Level: developer

5712:    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;

5714: .keywords: SNES, nonlinear, set, function

5716: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5717: */
5718: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5719: {
5720:   PetscErrorCode    ierr;
5721:   SNESMatlabContext *sctx;

5724:   /* currently sctx is memory bleed */
5725:   PetscNew(&sctx);
5726:   PetscStrallocpy(f,&sctx->funcname);
5727:   /*
5728:      This should work, but it doesn't
5729:   sctx->ctx = ctx;
5730:   mexMakeArrayPersistent(sctx->ctx);
5731:   */
5732:   sctx->ctx = mxDuplicateArray(ctx);
5733:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5734:   return(0);
5735: }

5737: #endif