Actual source code: snes.c

petsc-3.9.3 2018-07-02
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;

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

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

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

376:     PetscObjectGetName((PetscObject)snes,&name);
377:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
378:     if (!((PetscObject)snes)->amsmem && !rank) {
379:       char       dir[1024];

381:       PetscObjectViewSAWs((PetscObject)snes,viewer);
382:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);
383:       PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
384:       if (!snes->conv_hist) {
385:         SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE);
386:       }
387:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name);
388:       PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
389:     }
390: #endif
391:   }
392:   if (snes->linesearch) {
393:     SNESGetLineSearch(snes, &linesearch);
394:     PetscViewerASCIIPushTab(viewer);
395:     SNESLineSearchView(linesearch, viewer);
396:     PetscViewerASCIIPopTab(viewer);
397:   }
398:   if (snes->npc && snes->usesnpc) {
399:     PetscViewerASCIIPushTab(viewer);
400:     SNESView(snes->npc, viewer);
401:     PetscViewerASCIIPopTab(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:     PetscViewerASCIIPushTab(viewer);
410:     KSPView(ksp,viewer);
411:     PetscViewerASCIIPopTab(viewer);
412:   }
413:   if (isdraw) {
414:     PetscDraw draw;
415:     PetscViewerDrawGetDraw(viewer,0,&draw);
416:     PetscDrawPopCurrentPoint(draw);
417:   }
418:   return(0);
419: }

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

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

432:   Not Collective

434:   Input Parameter:
435: . snescheck - function that checks for options

437:   Level: developer

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

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

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


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

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

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

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

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

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

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

548: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
549: {

553:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
554:   return(0);
555: }

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

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

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

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

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

600:    Collective

602:    Input Arguments:
603: .  snes - snes to configure

605:    Level: developer

607: .seealso: SNESSetUp()
608: @*/
609: PetscErrorCode SNESSetUpMatrices(SNES snes)
610: {
612:   DM             dm;
613:   DMSNES         sdm;

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

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

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

665:    Collective on SNES

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

675:    Level: developer

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

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

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

709:    Collective on SNES

711:    Input Parameter:
712: .  snes - the SNES context

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

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

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

758:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

991:    Logically Collective on SNES

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

998:    Level: intermediate

1000:    Notes:
1001:    This function is currently not available from Fortran.

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

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

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

1020:    Logically Collective on SNES

1022:    Input Parameters:
1023: +  snes - the SNES context
1024: -  usrP - optional user context

1026:    Level: intermediate

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

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

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

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

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

1052:    Not Collective

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

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

1060:    Fortran Notes: 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: Reset every time SNESSolve is called unless SNESSetCountersReset() is used.

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

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

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

1330:    Not Collective

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

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

1338:    Level: intermediate

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

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

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

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

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

1363:    Logically Collective on SNES

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

1369:    Level: intermediate

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

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

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

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

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

1393:    Not Collective

1395:    Input Parameter:
1396: .  snes     - SNES context

1398:    Output Parameter:
1399: .  maxFails - maximum of unsuccessful solves allowed

1401:    Level: intermediate

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

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

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

1418: /*@
1419:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1420:    used by the nonlinear solver.

1422:    Not Collective

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

1427:    Output Parameter:
1428: .  lits - number of linear iterations

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

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

1436:    Level: intermediate

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

1440: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1441: @*/
1442: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1443: {
1447:   *lits = snes->linear_its;
1448:   return(0);
1449: }

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

1455:    Logically Collective on SNES

1457:    Input Parameter:
1458: +  snes - SNES context
1459: -  reset - whether to reset the counters or not

1461:    Notes:
1462:    This defaults to PETSC_TRUE

1464:    Level: developer

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

1468: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1469: @*/
1470: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1471: {
1475:   snes->counters_reset = reset;
1476:   return(0);
1477: }


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

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

1485:    Input Parameters:
1486: +  snes - the SNES context
1487: -  ksp - the KSP context

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

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

1496:    Level: developer

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

1500: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1501: @*/
1502: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1503: {

1510:   PetscObjectReference((PetscObject)ksp);
1511:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1512:   snes->ksp = ksp;
1513:   return(0);
1514: }

1516: /* -----------------------------------------------------------*/
1517: /*@
1518:    SNESCreate - Creates a nonlinear solver context.

1520:    Collective on MPI_Comm

1522:    Input Parameters:
1523: .  comm - MPI communicator

1525:    Output Parameter:
1526: .  outsnes - the new SNES context

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

1536:    Level: beginner

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

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

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

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

1551: @*/
1552: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1553: {
1555:   SNES           snes;
1556:   SNESKSPEW      *kctx;

1560:   *outsnes = NULL;
1561:   SNESInitializePackage();

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

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

1624:   snes->mf          = PETSC_FALSE;
1625:   snes->mf_operator = PETSC_FALSE;
1626:   snes->mf_version  = 1;

1628:   snes->numLinearSolveFailures = 0;
1629:   snes->maxLinearSolveFailures = 1;

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

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

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

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

1652:   *outsnes = snes;
1653:   return(0);
1654: }

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

1659:      Synopsis:
1660:      #include "petscsnes.h"
1661:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1663:      Input Parameters:
1664: +     snes - the SNES context
1665: .     x    - state at which to evaluate residual
1666: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1668:      Output Parameter:
1669: .     f  - vector to put residual (function value)

1671:    Level: intermediate

1673: .seealso:   SNESSetFunction(), SNESGetFunction()
1674: M*/

1676: /*@C
1677:    SNESSetFunction - Sets the function evaluation routine and function
1678:    vector for use by the SNES routines in solving systems of nonlinear
1679:    equations.

1681:    Logically Collective on SNES

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

1690:    Notes:
1691:    The Newton-like methods typically solve linear systems of the form
1692: $      f'(x) x = -f(x),
1693:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1695:    Level: beginner

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

1699: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1700: @*/
1701: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1702: {
1704:   DM             dm;

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

1714:     snes->vec_func = r;
1715:   }
1716:   SNESGetDM(snes,&dm);
1717:   DMSNESSetFunction(dm,f,ctx);
1718:   return(0);
1719: }


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

1729:    Logically Collective on SNES

1731:    Input Parameters:
1732: +  snes - the SNES context
1733: -  f - vector to store function value

1735:    Notes:
1736:    This should not be modified during the solution procedure.

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

1740:    Level: developer

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

1744: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1745: @*/
1746: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1747: {
1749:   Vec            vec_func;

1755:   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1756:     snes->vec_func_init_set = PETSC_FALSE;
1757:     return(0);
1758:   }
1759:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1760:   VecCopy(f, vec_func);

1762:   snes->vec_func_init_set = PETSC_TRUE;
1763:   return(0);
1764: }

1766: /*@
1767:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1768:    of the SNES method.

1770:    Logically Collective on SNES

1772:    Input Parameters:
1773: +  snes - the SNES context
1774: -  normschedule - the frequency of norm computation

1776:    Options Database Key:
1777: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1788:    Level: developer

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

1792: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1793: @*/
1794: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1795: {
1798:   snes->normschedule = normschedule;
1799:   return(0);
1800: }


1803: /*@
1804:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1805:    of the SNES method.

1807:    Logically Collective on SNES

1809:    Input Parameters:
1810: +  snes - the SNES context
1811: -  normschedule - the type of the norm used

1813:    Level: advanced

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

1817: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1818: @*/
1819: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1820: {
1823:   *normschedule = snes->normschedule;
1824:   return(0);
1825: }


1828: /*@
1829:   SNESSetFunctionNorm - Sets the last computed residual norm.

1831:   Logically Collective on SNES

1833:   Input Parameters:
1834: + snes - the SNES context

1836: - normschedule - the frequency of norm computation

1838:   Level: developer

1840: .keywords: SNES, nonlinear, set, function, norm, type
1841: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1842: @*/
1843: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1844: {
1847:   snes->norm = norm;
1848:   return(0);
1849: }

1851: /*@
1852:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1854:   Not Collective

1856:   Input Parameter:
1857: . snes - the SNES context

1859:   Output Parameter:
1860: . norm - the last computed residual norm

1862:   Level: developer

1864: .keywords: SNES, nonlinear, set, function, norm, type
1865: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1866: @*/
1867: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1868: {
1872:   *norm = snes->norm;
1873:   return(0);
1874: }

1876: /*@C
1877:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1878:    of the SNES method.

1880:    Logically Collective on SNES

1882:    Input Parameters:
1883: +  snes - the SNES context
1884: -  normschedule - the frequency of norm computation

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

1895:    Level: developer

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

1899: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1900: @*/
1901: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1902: {
1905:   snes->functype = type;
1906:   return(0);
1907: }


1910: /*@C
1911:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1912:    of the SNES method.

1914:    Logically Collective on SNES

1916:    Input Parameters:
1917: +  snes - the SNES context
1918: -  normschedule - the type of the norm used

1920:    Level: advanced

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

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

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

1937:      Synopsis:
1938:      #include <petscsnes.h>
1939: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1941: +  X   - solution vector
1942: .  B   - RHS vector
1943: -  ctx - optional user-defined Gauss-Seidel context

1945:    Level: intermediate

1947: .seealso:   SNESSetNGS(), SNESGetNGS()
1948: M*/

1950: /*@C
1951:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1952:    use with composed nonlinear solvers.

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

1960:    Notes:
1961:    The NGS routines are used by the composed nonlinear solver to generate
1962:     a problem appropriate update to the solution, particularly FAS.

1964:    Level: intermediate

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

1968: .seealso: SNESGetFunction(), SNESComputeNGS()
1969: @*/
1970: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1971: {
1973:   DM             dm;

1977:   SNESGetDM(snes,&dm);
1978:   DMSNESSetNGS(dm,f,ctx);
1979:   return(0);
1980: }

1982: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1983: {
1985:   DM             dm;
1986:   DMSNES         sdm;

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

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

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

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

2014:    Logically Collective on SNES

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

2026:    Notes:
2027:     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
2028:     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.

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

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

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

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

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

2044:    Level: intermediate

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

2048: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2049: @*/
2050: 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)
2051: {
2053:   DM             dm;

2057:   SNESGetDM(snes, &dm);
2058:   DMSNESSetPicard(dm,b,J,ctx);
2059:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2060:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2061:   return(0);
2062: }

2064: /*@C
2065:    SNESGetPicard - Returns the context for the Picard iteration

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

2069:    Input Parameter:
2070: .  snes - the SNES context

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

2080:    Level: advanced

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

2084: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2085: @*/
2086: 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)
2087: {
2089:   DM             dm;

2093:   SNESGetFunction(snes,r,NULL,NULL);
2094:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2095:   SNESGetDM(snes,&dm);
2096:   DMSNESGetPicard(dm,f,J,ctx);
2097:   return(0);
2098: }

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

2103:    Logically Collective on SNES

2105:    Input Parameters:
2106: +  snes - the SNES context
2107: .  func - function evaluation routine
2108: -  ctx - [optional] user-defined context for private data for the
2109:          function evaluation routine (may be NULL)

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

2114: .  f - function vector
2115: -  ctx - optional user-defined function context

2117:    Level: intermediate

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

2121: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2122: @*/
2123: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2124: {
2127:   if (func) snes->ops->computeinitialguess = func;
2128:   if (ctx)  snes->initialguessP            = ctx;
2129:   return(0);
2130: }

2132: /* --------------------------------------------------------------- */
2133: /*@C
2134:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2135:    it assumes a zero right hand side.

2137:    Logically Collective on SNES

2139:    Input Parameter:
2140: .  snes - the SNES context

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

2145:    Level: intermediate

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

2149: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2150: @*/
2151: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2152: {
2156:   *rhs = snes->vec_rhs;
2157:   return(0);
2158: }

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

2163:    Collective on SNES

2165:    Input Parameters:
2166: +  snes - the SNES context
2167: -  x - input vector

2169:    Output Parameter:
2170: .  y - function vector, as set by SNESSetFunction()

2172:    Notes:
2173:    SNESComputeFunction() is typically used within nonlinear solvers
2174:    implementations, so most users would not generally call this routine
2175:    themselves.

2177:    Level: developer

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

2181: .seealso: SNESSetFunction(), SNESGetFunction()
2182: @*/
2183: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2184: {
2186:   DM             dm;
2187:   DMSNES         sdm;

2195:   VecValidValues(x,2,PETSC_TRUE);

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

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

2231:    Collective on SNES

2233:    Input Parameters:
2234: +  snes - the SNES context
2235: .  x - input vector
2236: -  b - rhs vector

2238:    Output Parameter:
2239: .  x - new solution vector

2241:    Notes:
2242:    SNESComputeNGS() is typically used within composed nonlinear solver
2243:    implementations, so most users would not generally call this routine
2244:    themselves.

2246:    Level: developer

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

2250: .seealso: SNESSetNGS(), SNESComputeFunction()
2251: @*/
2252: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2253: {
2255:   DM             dm;
2256:   DMSNES         sdm;

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

2279: PetscErrorCode SNESTestJacobian(SNES snes)
2280: {
2281:   Mat            A = snes->jacobian,B,C;
2282:   Vec            x = snes->vec_sol,f = snes->vec_func;
2284:   PetscReal      nrm,gnorm;
2285:   PetscReal      threshold = 1.e-5;
2286:   PetscInt       m,n,M,N;
2287:   void           *functx;
2288:   PetscBool      complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE;
2289:   PetscViewer    viewer;
2290:   MPI_Comm       comm;
2291:   PetscInt       tabs;

2294:   PetscObjectOptionsBegin((PetscObject)snes);
2295:   PetscOptionsBool("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",test,&test,NULL);
2296:   PetscOptionsBool("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",complete_print,&complete_print,NULL);
2297:   PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print);
2298:   PetscOptionsEnd();
2299:   if (!test) return(0);

2301:   PetscObjectGetComm((PetscObject)snes,&comm);
2302:   PetscViewerASCIIGetStdout(comm,&viewer);
2303:   PetscViewerASCIIGetTab(viewer, &tabs);
2304:   PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);
2305:   if (A != snes->jacobian_pre) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Cannot test with alternative preconditioner");

2307:   PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if the ratio is\n");
2308:   PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n");
2309:   if (!complete_print) {
2310:     PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_display to show difference\n");
2311:     PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian.\n");
2312:     PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_display_threshold to show difference\n");
2313:     PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries great than threshold.\n");
2314:   }

2316:   /* evaluate the function at this point because SNESComputeJacobianDefaultColor() assumes that the function has been evaluated and put into snes->vec_func */
2317:   SNESComputeFunction(snes,x,f);
2318:   A    = snes->jacobian_pre;

2320:   MatCreate(PetscObjectComm((PetscObject)A),&B);
2321:   MatGetSize(A,&M,&N);
2322:   MatGetLocalSize(A,&m,&n);
2323:   MatSetSizes(B,m,n,M,N);
2324:   MatSetType(B,((PetscObject)A)->type_name);
2325:   MatSetUp(B);
2326:   MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2328:   SNESGetFunction(snes,NULL,NULL,&functx);
2329:   SNESComputeJacobianDefault(snes,x,B,B,functx);
2330:   if (complete_print) {
2331:     PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian\n");
2332:     MatView(B,viewer);
2333:   }
2334:   /* compare */
2335:   MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2336:   MatNorm(B,NORM_FROBENIUS,&nrm);
2337:   MatNorm(A,NORM_FROBENIUS,&gnorm);
2338:   if (complete_print) {
2339:     PetscViewerASCIIPrintf(viewer,"Hand-coded Jacobian\n");
2340:     PetscObjectGetComm((PetscObject)B,&comm);
2341:     PetscViewerASCIIGetStdout(comm,&viewer);
2342:     MatView(A,viewer);
2343:     PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian\n");
2344:     MatView(B,viewer);
2345:   }

2347:   if (threshold_print) {
2348:     PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2349:     PetscScalar       *cvals;
2350:     const PetscInt    *bcols;
2351:     const PetscScalar *bvals;

2353:     MatCreate(PetscObjectComm((PetscObject)A),&C);
2354:     MatSetSizes(C,m,n,M,N);
2355:     MatSetType(C,((PetscObject)A)->type_name);
2356:     MatSetUp(C);
2357:     MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
2358:     MatGetOwnershipRange(B,&Istart,&Iend);

2360:     for (row = Istart; row < Iend; row++) {
2361:       MatGetRow(B,row,&bncols,&bcols,&bvals);
2362:       PetscMalloc2(bncols,&ccols,bncols,&cvals);
2363:       for (j = 0, cncols = 0; j < bncols; j++) {
2364:         if (PetscAbsScalar(bvals[j]) > threshold) {
2365:           ccols[cncols] = bcols[j];
2366:           cvals[cncols] = bvals[j];
2367:           cncols += 1;
2368:         }
2369:       }
2370:       if(cncols) {
2371:         MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES);
2372:       }
2373:       MatRestoreRow(B,row,&bncols,&bcols,&bvals);
2374:       PetscFree2(ccols,cvals);
2375:     }
2376:     MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2377:     MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);

2379:     PetscViewerASCIIPrintf(viewer,"  Entries where difference is over threshold\n");
2380:     MatView(C,viewer);
2381:     MatDestroy(&C);
2382:   }

2384:   if (!gnorm) gnorm = 1; /* just in case */
2385:   PetscViewerASCIIPrintf(viewer,"||J - Jfd||_F/||J||_F %g, ||J - Jfd||_F %g\n",(double)(nrm/gnorm),(double)nrm);
2386:   MatDestroy(&B);
2387:   PetscViewerASCIISetTab(viewer,tabs);
2388:   return(0);
2389: }

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

2394:    Collective on SNES and Mat

2396:    Input Parameters:
2397: +  snes - the SNES context
2398: -  x - input vector

2400:    Output Parameters:
2401: +  A - Jacobian matrix
2402: -  B - optional preconditioning matrix

2404:   Options Database Keys:
2405: +    -snes_lag_preconditioner <lag>
2406: .    -snes_lag_jacobian <lag>
2407: .    -snes_test_jacobian - compare the user provided Jacobian with one compute via finite differences to check for errors
2408: .    -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
2409: .    -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
2410: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2411: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2412: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2413: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2414: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2415: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2416: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2417: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2418: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2419: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2420: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2423:    Notes:
2424:    Most users should not need to explicitly call this routine, as it
2425:    is used internally within the nonlinear solvers.

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

2430:    Level: developer

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

2434: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2435: @*/
2436: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2437: {
2439:   PetscBool      flag;
2440:   DM             dm;
2441:   DMSNES         sdm;
2442:   KSP            ksp;

2448:   VecValidValues(X,2,PETSC_TRUE);
2449:   SNESGetDM(snes,&dm);
2450:   DMGetDMSNES(dm,&sdm);

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

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

2456:   if (snes->lagjacobian == -2) {
2457:     snes->lagjacobian = -1;

2459:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2460:   } else if (snes->lagjacobian == -1) {
2461:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2462:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2463:     if (flag) {
2464:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2465:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2466:     }
2467:     return(0);
2468:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2469:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2470:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2471:     if (flag) {
2472:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2473:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2474:     }
2475:     return(0);
2476:   }
2477:   if (snes->npc && snes->npcside== PC_LEFT) {
2478:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2479:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2480:       return(0);
2481:   }

2483:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2484:   VecLockPush(X);
2485:   PetscStackPush("SNES user Jacobian function");
2486:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2487:   PetscStackPop;
2488:   VecLockPop(X);
2489:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2491:   /* the next line ensures that snes->ksp exists */
2492:   SNESGetKSP(snes,&ksp);
2493:   if (snes->lagpreconditioner == -2) {
2494:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2495:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2496:     snes->lagpreconditioner = -1;
2497:   } else if (snes->lagpreconditioner == -1) {
2498:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2499:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2500:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2501:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2502:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2503:   } else {
2504:     PetscInfo(snes,"Rebuilding preconditioner\n");
2505:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2506:   }

2508:   SNESTestJacobian(snes);
2509:   /* make sure user returned a correct Jacobian and preconditioner */
2512:   {
2513:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2514:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2515:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2516:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2517:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2518:     if (flag || flag_draw || flag_contour) {
2519:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2520:       PetscViewer  vdraw,vstdout;
2521:       PetscBool    flg;
2522:       if (flag_operator) {
2523:         MatComputeExplicitOperator(A,&Bexp_mine);
2524:         Bexp = Bexp_mine;
2525:       } else {
2526:         /* See if the preconditioning matrix can be viewed and added directly */
2527:         PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2528:         if (flg) Bexp = B;
2529:         else {
2530:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2531:           MatComputeExplicitOperator(B,&Bexp_mine);
2532:           Bexp = Bexp_mine;
2533:         }
2534:       }
2535:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2536:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2537:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2538:       if (flag_draw || flag_contour) {
2539:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2540:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2541:       } else vdraw = NULL;
2542:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2543:       if (flag) {MatView(Bexp,vstdout);}
2544:       if (vdraw) {MatView(Bexp,vdraw);}
2545:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2546:       if (flag) {MatView(FDexp,vstdout);}
2547:       if (vdraw) {MatView(FDexp,vdraw);}
2548:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2549:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2550:       if (flag) {MatView(FDexp,vstdout);}
2551:       if (vdraw) {              /* Always use contour for the difference */
2552:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2553:         MatView(FDexp,vdraw);
2554:         PetscViewerPopFormat(vdraw);
2555:       }
2556:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2557:       PetscViewerDestroy(&vdraw);
2558:       MatDestroy(&Bexp_mine);
2559:       MatDestroy(&FDexp);
2560:     }
2561:   }
2562:   {
2563:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2564:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2565:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2566:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2567:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2568:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2569:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2570:     if (flag_threshold) {
2571:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2572:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2573:     }
2574:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2575:       Mat            Bfd;
2576:       PetscViewer    vdraw,vstdout;
2577:       MatColoring    coloring;
2578:       ISColoring     iscoloring;
2579:       MatFDColoring  matfdcoloring;
2580:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2581:       void           *funcctx;
2582:       PetscReal      norm1,norm2,normmax;

2584:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2585:       MatColoringCreate(Bfd,&coloring);
2586:       MatColoringSetType(coloring,MATCOLORINGSL);
2587:       MatColoringSetFromOptions(coloring);
2588:       MatColoringApply(coloring,&iscoloring);
2589:       MatColoringDestroy(&coloring);
2590:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2591:       MatFDColoringSetFromOptions(matfdcoloring);
2592:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2593:       ISColoringDestroy(&iscoloring);

2595:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2596:       SNESGetFunction(snes,NULL,&func,&funcctx);
2597:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2598:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2599:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2600:       MatFDColoringSetFromOptions(matfdcoloring);
2601:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2602:       MatFDColoringDestroy(&matfdcoloring);

2604:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2605:       if (flag_draw || flag_contour) {
2606:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2607:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2608:       } else vdraw = NULL;
2609:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2610:       if (flag_display) {MatView(B,vstdout);}
2611:       if (vdraw) {MatView(B,vdraw);}
2612:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2613:       if (flag_display) {MatView(Bfd,vstdout);}
2614:       if (vdraw) {MatView(Bfd,vdraw);}
2615:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2616:       MatNorm(Bfd,NORM_1,&norm1);
2617:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2618:       MatNorm(Bfd,NORM_MAX,&normmax);
2619:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2620:       if (flag_display) {MatView(Bfd,vstdout);}
2621:       if (vdraw) {              /* Always use contour for the difference */
2622:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2623:         MatView(Bfd,vdraw);
2624:         PetscViewerPopFormat(vdraw);
2625:       }
2626:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2628:       if (flag_threshold) {
2629:         PetscInt bs,rstart,rend,i;
2630:         MatGetBlockSize(B,&bs);
2631:         MatGetOwnershipRange(B,&rstart,&rend);
2632:         for (i=rstart; i<rend; i++) {
2633:           const PetscScalar *ba,*ca;
2634:           const PetscInt    *bj,*cj;
2635:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2636:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2637:           MatGetRow(B,i,&bn,&bj,&ba);
2638:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2639:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2640:           for (j=0; j<bn; j++) {
2641:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2642:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2643:               maxentrycol = bj[j];
2644:               maxentry    = PetscRealPart(ba[j]);
2645:             }
2646:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2647:               maxdiffcol = bj[j];
2648:               maxdiff    = PetscRealPart(ca[j]);
2649:             }
2650:             if (rdiff > maxrdiff) {
2651:               maxrdiffcol = bj[j];
2652:               maxrdiff    = rdiff;
2653:             }
2654:           }
2655:           if (maxrdiff > 1) {
2656:             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);
2657:             for (j=0; j<bn; j++) {
2658:               PetscReal rdiff;
2659:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2660:               if (rdiff > 1) {
2661:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2662:               }
2663:             }
2664:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2665:           }
2666:           MatRestoreRow(B,i,&bn,&bj,&ba);
2667:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2668:         }
2669:       }
2670:       PetscViewerDestroy(&vdraw);
2671:       MatDestroy(&Bfd);
2672:     }
2673:   }
2674:   return(0);
2675: }

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

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

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

2689:    Level: intermediate

2691: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2692: M*/

2694: /*@C
2695:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2696:    location to store the matrix.

2698:    Logically Collective on SNES and Mat

2700:    Input Parameters:
2701: +  snes - the SNES context
2702: .  Amat - the matrix that defines the (approximate) Jacobian
2703: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2704: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2705: -  ctx - [optional] user-defined context for private data for the
2706:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2708:    Notes:
2709:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2710:    each matrix.

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

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

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

2721:    Level: beginner

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

2725: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
2726:           SNESSetPicard(), SNESJacobianFunction
2727: @*/
2728: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2729: {
2731:   DM             dm;

2739:   SNESGetDM(snes,&dm);
2740:   DMSNESSetJacobian(dm,J,ctx);
2741:   if (Amat) {
2742:     PetscObjectReference((PetscObject)Amat);
2743:     MatDestroy(&snes->jacobian);

2745:     snes->jacobian = Amat;
2746:   }
2747:   if (Pmat) {
2748:     PetscObjectReference((PetscObject)Pmat);
2749:     MatDestroy(&snes->jacobian_pre);

2751:     snes->jacobian_pre = Pmat;
2752:   }
2753:   return(0);
2754: }

2756: /*@C
2757:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2758:    provided context for evaluating the Jacobian.

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

2762:    Input Parameter:
2763: .  snes - the nonlinear solver context

2765:    Output Parameters:
2766: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2767: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2768: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2769: -  ctx - location to stash Jacobian ctx (or NULL)

2771:    Level: advanced

2773: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2774: @*/
2775: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2776: {
2778:   DM             dm;
2779:   DMSNES         sdm;

2783:   if (Amat) *Amat = snes->jacobian;
2784:   if (Pmat) *Pmat = snes->jacobian_pre;
2785:   SNESGetDM(snes,&dm);
2786:   DMGetDMSNES(dm,&sdm);
2787:   if (J) *J = sdm->ops->computejacobian;
2788:   if (ctx) *ctx = sdm->jacobianctx;
2789:   return(0);
2790: }

2792: /*@
2793:    SNESSetUp - Sets up the internal data structures for the later use
2794:    of a nonlinear solver.

2796:    Collective on SNES

2798:    Input Parameters:
2799: .  snes - the SNES context

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

2808:    Level: advanced

2810: .keywords: SNES, nonlinear, setup

2812: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2813: @*/
2814: PetscErrorCode  SNESSetUp(SNES snes)
2815: {
2817:   DM             dm;
2818:   DMSNES         sdm;
2819:   SNESLineSearch linesearch, pclinesearch;
2820:   void           *lsprectx,*lspostctx;
2821:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2822:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2823:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2824:   Vec            f,fpc;
2825:   void           *funcctx;
2826:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2827:   void           *jacctx,*appctx;
2828:   Mat            j,jpre;

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

2834:   if (!((PetscObject)snes)->type_name) {
2835:     SNESSetType(snes,SNESNEWTONLS);
2836:   }

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

2840:   SNESGetDM(snes,&dm);
2841:   DMGetDMSNES(dm,&sdm);
2842:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2843:   if (!sdm->ops->computejacobian) {
2844:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2845:   }
2846:   if (!snes->vec_func) {
2847:     DMCreateGlobalVector(dm,&snes->vec_func);
2848:   }

2850:   if (!snes->ksp) {
2851:     SNESGetKSP(snes, &snes->ksp);
2852:   }

2854:   if (!snes->linesearch) {
2855:     SNESGetLineSearch(snes, &snes->linesearch);
2856:   }
2857:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2859:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2860:     snes->mf          = PETSC_TRUE;
2861:     snes->mf_operator = PETSC_FALSE;
2862:   }

2864:   if (snes->npc) {
2865:     /* copy the DM over */
2866:     SNESGetDM(snes,&dm);
2867:     SNESSetDM(snes->npc,dm);

2869:     SNESGetFunction(snes,&f,&func,&funcctx);
2870:     VecDuplicate(f,&fpc);
2871:     SNESSetFunction(snes->npc,fpc,func,funcctx);
2872:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2873:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
2874:     SNESGetApplicationContext(snes,&appctx);
2875:     SNESSetApplicationContext(snes->npc,appctx);
2876:     VecDestroy(&fpc);

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

2881:     /* default to 1 iteration */
2882:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
2883:     if (snes->npcside==PC_RIGHT) {
2884:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
2885:     } else {
2886:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
2887:     }
2888:     SNESSetFromOptions(snes->npc);

2890:     /* copy the line search context over */
2891:     SNESGetLineSearch(snes,&linesearch);
2892:     SNESGetLineSearch(snes->npc,&pclinesearch);
2893:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2894:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2895:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2896:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2897:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2898:   }
2899:   if (snes->mf) {
2900:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2901:   }
2902:   if (snes->ops->usercompute && !snes->user) {
2903:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2904:   }

2906:   snes->jac_iter = 0;
2907:   snes->pre_iter = 0;

2909:   if (snes->ops->setup) {
2910:     (*snes->ops->setup)(snes);
2911:   }

2913:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2914:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2915:       SNESGetLineSearch(snes,&linesearch);
2916:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2917:     }
2918:   }

2920:   snes->setupcalled = PETSC_TRUE;
2921:   return(0);
2922: }

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

2927:    Collective on SNES

2929:    Input Parameter:
2930: .  snes - iterative context obtained from SNESCreate()

2932:    Level: intermediate

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

2936: .keywords: SNES, destroy

2938: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
2939: @*/
2940: PetscErrorCode  SNESReset(SNES snes)
2941: {

2946:   if (snes->ops->userdestroy && snes->user) {
2947:     (*snes->ops->userdestroy)((void**)&snes->user);
2948:     snes->user = NULL;
2949:   }
2950:   if (snes->npc) {
2951:     SNESReset(snes->npc);
2952:   }

2954:   if (snes->ops->reset) {
2955:     (*snes->ops->reset)(snes);
2956:   }
2957:   if (snes->ksp) {
2958:     KSPReset(snes->ksp);
2959:   }

2961:   if (snes->linesearch) {
2962:     SNESLineSearchReset(snes->linesearch);
2963:   }

2965:   VecDestroy(&snes->vec_rhs);
2966:   VecDestroy(&snes->vec_sol);
2967:   VecDestroy(&snes->vec_sol_update);
2968:   VecDestroy(&snes->vec_func);
2969:   MatDestroy(&snes->jacobian);
2970:   MatDestroy(&snes->jacobian_pre);
2971:   VecDestroyVecs(snes->nwork,&snes->work);
2972:   VecDestroyVecs(snes->nvwork,&snes->vwork);

2974:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

2976:   snes->nwork       = snes->nvwork = 0;
2977:   snes->setupcalled = PETSC_FALSE;
2978:   return(0);
2979: }

2981: /*@
2982:    SNESDestroy - Destroys the nonlinear solver context that was created
2983:    with SNESCreate().

2985:    Collective on SNES

2987:    Input Parameter:
2988: .  snes - the SNES context

2990:    Level: beginner

2992: .keywords: SNES, nonlinear, destroy

2994: .seealso: SNESCreate(), SNESSolve()
2995: @*/
2996: PetscErrorCode  SNESDestroy(SNES *snes)
2997: {

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

3005:   SNESReset((*snes));
3006:   SNESDestroy(&(*snes)->npc);

3008:   /* if memory was published with SAWs then destroy it */
3009:   PetscObjectSAWsViewOff((PetscObject)*snes);
3010:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

3012:   if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
3013:   DMDestroy(&(*snes)->dm);
3014:   KSPDestroy(&(*snes)->ksp);
3015:   SNESLineSearchDestroy(&(*snes)->linesearch);

3017:   PetscFree((*snes)->kspconvctx);
3018:   if ((*snes)->ops->convergeddestroy) {
3019:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
3020:   }
3021:   if ((*snes)->conv_malloc) {
3022:     PetscFree((*snes)->conv_hist);
3023:     PetscFree((*snes)->conv_hist_its);
3024:   }
3025:   SNESMonitorCancel((*snes));
3026:   PetscHeaderDestroy(snes);
3027:   return(0);
3028: }

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

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

3035:    Logically Collective on SNES

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

3042:    Options Database Keys:
3043: .    -snes_lag_preconditioner <lag>

3045:    Notes:
3046:    The default is 1
3047:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3048:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

3050:    Level: intermediate

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

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

3056: @*/
3057: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3058: {
3061:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3062:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3064:   snes->lagpreconditioner = lag;
3065:   return(0);
3066: }

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

3071:    Logically Collective on SNES

3073:    Input Parameters:
3074: +  snes - the SNES context
3075: -  steps - the number of refinements to do, defaults to 0

3077:    Options Database Keys:
3078: .    -snes_grid_sequence <steps>

3080:    Level: intermediate

3082:    Notes:
3083:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

3089: @*/
3090: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3091: {
3095:   snes->gridsequence = steps;
3096:   return(0);
3097: }

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

3102:    Logically Collective on SNES

3104:    Input Parameter:
3105: .  snes - the SNES context

3107:    Output Parameter:
3108: .  steps - the number of refinements to do, defaults to 0

3110:    Options Database Keys:
3111: .    -snes_grid_sequence <steps>

3113:    Level: intermediate

3115:    Notes:
3116:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

3122: @*/
3123: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3124: {
3127:   *steps = snes->gridsequence;
3128:   return(0);
3129: }

3131: /*@
3132:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3134:    Not Collective

3136:    Input Parameter:
3137: .  snes - the SNES context

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

3143:    Options Database Keys:
3144: .    -snes_lag_preconditioner <lag>

3146:    Notes:
3147:    The default is 1
3148:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3150:    Level: intermediate

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

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

3156: @*/
3157: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3158: {
3161:   *lag = snes->lagpreconditioner;
3162:   return(0);
3163: }

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

3169:    Logically Collective on SNES

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

3176:    Options Database Keys:
3177: .    -snes_lag_jacobian <lag>

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

3185:    Level: intermediate

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

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

3191: @*/
3192: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3193: {
3196:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3197:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3199:   snes->lagjacobian = lag;
3200:   return(0);
3201: }

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

3206:    Not Collective

3208:    Input Parameter:
3209: .  snes - the SNES context

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

3215:    Options Database Keys:
3216: .    -snes_lag_jacobian <lag>

3218:    Notes:
3219:    The default is 1
3220:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3222:    Level: intermediate

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

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

3228: @*/
3229: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3230: {
3233:   *lag = snes->lagjacobian;
3234:   return(0);
3235: }

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

3240:    Logically collective on SNES

3242:    Input Parameter:
3243: +  snes - the SNES context
3244: -   flg - jacobian lagging persists if true

3246:    Options Database Keys:
3247: .    -snes_lag_jacobian_persists <flg>

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

3253:    Level: developer

3255: .keywords: SNES, nonlinear, lag

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

3259: @*/
3260: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3261: {
3265:   snes->lagjac_persist = flg;
3266:   return(0);
3267: }

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

3272:    Logically Collective on SNES

3274:    Input Parameter:
3275: +  snes - the SNES context
3276: -   flg - preconditioner lagging persists if true

3278:    Options Database Keys:
3279: .    -snes_lag_jacobian_persists <flg>

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

3285:    Level: developer

3287: .keywords: SNES, nonlinear, lag

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

3291: @*/
3292: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3293: {
3297:   snes->lagpre_persist = flg;
3298:   return(0);
3299: }

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

3304:    Logically Collective on SNES

3306:    Input Parameters:
3307: +  snes - the SNES context
3308: -  force - PETSC_TRUE require at least one iteration

3310:    Options Database Keys:
3311: .    -snes_force_iteration <force> - Sets forcing an iteration

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

3316:    Level: intermediate

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

3320: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3321: @*/
3322: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3323: {
3326:   snes->forceiteration = force;
3327:   return(0);
3328: }

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

3333:    Logically Collective on SNES

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

3338:    Output Parameter:
3339: .  force - PETSC_TRUE requires at least one iteration.

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

3343: .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3344: @*/
3345: PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
3346: {
3349:   *force = snes->forceiteration;
3350:   return(0);
3351: }

3353: /*@
3354:    SNESSetTolerances - Sets various parameters used in convergence tests.

3356:    Logically Collective on SNES

3358:    Input Parameters:
3359: +  snes - the SNES context
3360: .  abstol - absolute convergence tolerance
3361: .  rtol - relative convergence tolerance
3362: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3363: .  maxit - maximum number of iterations
3364: -  maxf - maximum number of function evaluations

3366:    Options Database Keys:
3367: +    -snes_atol <abstol> - Sets abstol
3368: .    -snes_rtol <rtol> - Sets rtol
3369: .    -snes_stol <stol> - Sets stol
3370: .    -snes_max_it <maxit> - Sets maxit
3371: -    -snes_max_funcs <maxf> - Sets maxf

3373:    Notes:
3374:    The default maximum number of iterations is 50.
3375:    The default maximum number of function evaluations is 1000.

3377:    Level: intermediate

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

3381: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3382: @*/
3383: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3384: {

3393:   if (abstol != PETSC_DEFAULT) {
3394:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3395:     snes->abstol = abstol;
3396:   }
3397:   if (rtol != PETSC_DEFAULT) {
3398:     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);
3399:     snes->rtol = rtol;
3400:   }
3401:   if (stol != PETSC_DEFAULT) {
3402:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3403:     snes->stol = stol;
3404:   }
3405:   if (maxit != PETSC_DEFAULT) {
3406:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3407:     snes->max_its = maxit;
3408:   }
3409:   if (maxf != PETSC_DEFAULT) {
3410:     if (maxf < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be non-negative",maxf);
3411:     snes->max_funcs = maxf;
3412:   }
3413:   snes->tolerancesset = PETSC_TRUE;
3414:   return(0);
3415: }

3417: /*@
3418:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3420:    Logically Collective on SNES

3422:    Input Parameters:
3423: +  snes - the SNES context
3424: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3426:    Options Database Keys:
3427: +    -snes_divergence_tolerance <divtol> - Sets divtol

3429:    Notes:
3430:    The default divergence tolerance is 1e4.

3432:    Level: intermediate

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

3436: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3437: @*/
3438: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3439: {

3444:   if (divtol != PETSC_DEFAULT) {
3445:     snes->divtol = divtol;
3446:   }
3447:   else {
3448:     snes->divtol = 1.0e4;
3449:   }
3450:   return(0);
3451: }

3453: /*@
3454:    SNESGetTolerances - Gets various parameters used in convergence tests.

3456:    Not Collective

3458:    Input Parameters:
3459: +  snes - the SNES context
3460: .  atol - absolute convergence tolerance
3461: .  rtol - relative convergence tolerance
3462: .  stol -  convergence tolerance in terms of the norm
3463:            of the change in the solution between steps
3464: .  maxit - maximum number of iterations
3465: -  maxf - maximum number of function evaluations

3467:    Notes:
3468:    The user can specify NULL for any parameter that is not needed.

3470:    Level: intermediate

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

3474: .seealso: SNESSetTolerances()
3475: @*/
3476: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3477: {
3480:   if (atol)  *atol  = snes->abstol;
3481:   if (rtol)  *rtol  = snes->rtol;
3482:   if (stol)  *stol  = snes->stol;
3483:   if (maxit) *maxit = snes->max_its;
3484:   if (maxf)  *maxf  = snes->max_funcs;
3485:   return(0);
3486: }

3488: /*@
3489:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3491:    Not Collective

3493:    Input Parameters:
3494: +  snes - the SNES context
3495: -  divtol - divergence tolerance

3497:    Level: intermediate

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

3501: .seealso: SNESSetDivergenceTolerance()
3502: @*/
3503: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3504: {
3507:   if (divtol) *divtol = snes->divtol;
3508:   return(0);
3509: }

3511: /*@
3512:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3514:    Logically Collective on SNES

3516:    Input Parameters:
3517: +  snes - the SNES context
3518: -  tol - tolerance

3520:    Options Database Key:
3521: .  -snes_trtol <tol> - Sets tol

3523:    Level: intermediate

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

3527: .seealso: SNESSetTolerances()
3528: @*/
3529: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3530: {
3534:   snes->deltatol = tol;
3535:   return(0);
3536: }

3538: /*
3539:    Duplicate the lg monitors for SNES from KSP; for some reason with
3540:    dynamic libraries things don't work under Sun4 if we just use
3541:    macros instead of functions
3542: */
3543: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3544: {

3549:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3550:   return(0);
3551: }

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

3558:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3559:   return(0);
3560: }

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

3564: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3565: {
3566:   PetscDrawLG      lg;
3567:   PetscErrorCode   ierr;
3568:   PetscReal        x,y,per;
3569:   PetscViewer      v = (PetscViewer)monctx;
3570:   static PetscReal prev; /* should be in the context */
3571:   PetscDraw        draw;

3575:   PetscViewerDrawGetDrawLG(v,0,&lg);
3576:   if (!n) {PetscDrawLGReset(lg);}
3577:   PetscDrawLGGetDraw(lg,&draw);
3578:   PetscDrawSetTitle(draw,"Residual norm");
3579:   x    = (PetscReal)n;
3580:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3581:   else y = -15.0;
3582:   PetscDrawLGAddPoint(lg,&x,&y);
3583:   if (n < 20 || !(n % 5) || snes->reason) {
3584:     PetscDrawLGDraw(lg);
3585:     PetscDrawLGSave(lg);
3586:   }

3588:   PetscViewerDrawGetDrawLG(v,1,&lg);
3589:   if (!n) {PetscDrawLGReset(lg);}
3590:   PetscDrawLGGetDraw(lg,&draw);
3591:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3592:    SNESMonitorRange_Private(snes,n,&per);
3593:   x    = (PetscReal)n;
3594:   y    = 100.0*per;
3595:   PetscDrawLGAddPoint(lg,&x,&y);
3596:   if (n < 20 || !(n % 5) || snes->reason) {
3597:     PetscDrawLGDraw(lg);
3598:     PetscDrawLGSave(lg);
3599:   }

3601:   PetscViewerDrawGetDrawLG(v,2,&lg);
3602:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3603:   PetscDrawLGGetDraw(lg,&draw);
3604:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3605:   x    = (PetscReal)n;
3606:   y    = (prev - rnorm)/prev;
3607:   PetscDrawLGAddPoint(lg,&x,&y);
3608:   if (n < 20 || !(n % 5) || snes->reason) {
3609:     PetscDrawLGDraw(lg);
3610:     PetscDrawLGSave(lg);
3611:   }

3613:   PetscViewerDrawGetDrawLG(v,3,&lg);
3614:   if (!n) {PetscDrawLGReset(lg);}
3615:   PetscDrawLGGetDraw(lg,&draw);
3616:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3617:   x    = (PetscReal)n;
3618:   y    = (prev - rnorm)/(prev*per);
3619:   if (n > 2) { /*skip initial crazy value */
3620:     PetscDrawLGAddPoint(lg,&x,&y);
3621:   }
3622:   if (n < 20 || !(n % 5) || snes->reason) {
3623:     PetscDrawLGDraw(lg);
3624:     PetscDrawLGSave(lg);
3625:   }
3626:   prev = rnorm;
3627:   return(0);
3628: }

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

3633:    Collective on SNES

3635:    Input Parameters:
3636: +  snes - nonlinear solver context obtained from SNESCreate()
3637: .  iter - iteration number
3638: -  rnorm - relative norm of the residual

3640:    Notes:
3641:    This routine is called by the SNES implementations.
3642:    It does not typically need to be called by the user.

3644:    Level: developer

3646: .seealso: SNESMonitorSet()
3647: @*/
3648: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3649: {
3651:   PetscInt       i,n = snes->numbermonitors;

3654:   VecLockPush(snes->vec_sol);
3655:   for (i=0; i<n; i++) {
3656:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3657:   }
3658:   VecLockPop(snes->vec_sol);
3659:   return(0);
3660: }

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

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

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

3671: +    snes - the SNES context
3672: .    its - iteration number
3673: .    norm - 2-norm function value (may be estimated)
3674: -    mctx - [optional] monitoring context

3676:    Level: advanced

3678: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3679: M*/

3681: /*@C
3682:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3683:    iteration of the nonlinear solver to display the iteration's
3684:    progress.

3686:    Logically Collective on SNES

3688:    Input Parameters:
3689: +  snes - the SNES context
3690: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3691: .  mctx - [optional] user-defined context for private data for the
3692:           monitor routine (use NULL if no context is desired)
3693: -  monitordestroy - [optional] routine that frees monitor context
3694:           (may be NULL)

3696:    Options Database Keys:
3697: +    -snes_monitor        - sets SNESMonitorDefault()
3698: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3699:                             uses SNESMonitorLGCreate()
3700: -    -snes_monitor_cancel - cancels all monitors that have
3701:                             been hardwired into a code by
3702:                             calls to SNESMonitorSet(), but
3703:                             does not cancel those set via
3704:                             the options database.

3706:    Notes:
3707:    Several different monitoring routines may be set by calling
3708:    SNESMonitorSet() multiple times; all will be called in the
3709:    order in which they were set.

3711:    Fortran notes: Only a single monitor function can be set for each SNES object

3713:    Level: intermediate

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

3717: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3718: @*/
3719: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3720: {
3721:   PetscInt       i;
3723:   PetscBool      identical;

3727:   for (i=0; i<snes->numbermonitors;i++) {
3728:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3729:     if (identical) return(0);
3730:   }
3731:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3732:   snes->monitor[snes->numbermonitors]          = f;
3733:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3734:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3735:   return(0);
3736: }

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

3741:    Logically Collective on SNES

3743:    Input Parameters:
3744: .  snes - the SNES context

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

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

3754:    Level: intermediate

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

3758: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3759: @*/
3760: PetscErrorCode  SNESMonitorCancel(SNES snes)
3761: {
3763:   PetscInt       i;

3767:   for (i=0; i<snes->numbermonitors; i++) {
3768:     if (snes->monitordestroy[i]) {
3769:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3770:     }
3771:   }
3772:   snes->numbermonitors = 0;
3773:   return(0);
3774: }

3776: /*MC
3777:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3783: +    snes - the SNES context
3784: .    it - current iteration (0 is the first and is before any Newton step)
3785: .    cctx - [optional] convergence context
3786: .    reason - reason for convergence/divergence
3787: .    xnorm - 2-norm of current iterate
3788: .    gnorm - 2-norm of current step
3789: -    f - 2-norm of function

3791:    Level: intermediate

3793: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3794: M*/

3796: /*@C
3797:    SNESSetConvergenceTest - Sets the function that is to be used
3798:    to test for convergence of the nonlinear iterative solution.

3800:    Logically Collective on SNES

3802:    Input Parameters:
3803: +  snes - the SNES context
3804: .  SNESConvergenceTestFunction - routine to test for convergence
3805: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3806: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3808:    Level: advanced

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

3812: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3813: @*/
3814: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3815: {

3820:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3821:   if (snes->ops->convergeddestroy) {
3822:     (*snes->ops->convergeddestroy)(snes->cnvP);
3823:   }
3824:   snes->ops->converged        = SNESConvergenceTestFunction;
3825:   snes->ops->convergeddestroy = destroy;
3826:   snes->cnvP                  = cctx;
3827:   return(0);
3828: }

3830: /*@
3831:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3833:    Not Collective

3835:    Input Parameter:
3836: .  snes - the SNES context

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

3842:    Options Database:
3843: .   -snes_converged_reason - prints the reason to standard out

3845:    Level: intermediate

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

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

3851: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
3852: @*/
3853: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3854: {
3858:   *reason = snes->reason;
3859:   return(0);
3860: }

3862: /*@
3863:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3865:    Not Collective

3867:    Input Parameters:
3868: +  snes - the SNES context
3869: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
3870:             manual pages for the individual convergence tests for complete lists

3872:    Level: intermediate

3874: .keywords: SNES, nonlinear, set, convergence, test
3875: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
3876: @*/
3877: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
3878: {
3881:   snes->reason = reason;
3882:   return(0);
3883: }

3885: /*@
3886:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3888:    Logically Collective on SNES

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

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

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

3906:    Level: intermediate

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

3910: .seealso: SNESGetConvergenceHistory()

3912: @*/
3913: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3914: {

3921:   if (!a) {
3922:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3923:     PetscCalloc1(na,&a);
3924:     PetscCalloc1(na,&its);

3926:     snes->conv_malloc = PETSC_TRUE;
3927:   }
3928:   snes->conv_hist       = a;
3929:   snes->conv_hist_its   = its;
3930:   snes->conv_hist_max   = na;
3931:   snes->conv_hist_len   = 0;
3932:   snes->conv_hist_reset = reset;
3933:   return(0);
3934: }

3936: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3937: #include <engine.h>   /* MATLAB include file */
3938: #include <mex.h>      /* MATLAB include file */

3940: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3941: {
3942:   mxArray   *mat;
3943:   PetscInt  i;
3944:   PetscReal *ar;

3947:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3948:   ar  = (PetscReal*) mxGetData(mat);
3949:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3950:   PetscFunctionReturn(mat);
3951: }
3952: #endif

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

3957:    Not Collective

3959:    Input Parameter:
3960: .  snes - iterative context obtained from SNESCreate()

3962:    Output Parameters:
3963: .  a   - array to hold history
3964: .  its - integer array holds the number of linear iterations (or
3965:          negative if not converged) for each solve.
3966: -  na  - size of a and its

3968:    Notes:
3969:     The calling sequence for this routine in Fortran is
3970: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

3976:    Level: intermediate

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

3980: .seealso: SNESSetConvergencHistory()

3982: @*/
3983: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
3984: {
3987:   if (a)   *a   = snes->conv_hist;
3988:   if (its) *its = snes->conv_hist_its;
3989:   if (na)  *na  = snes->conv_hist_len;
3990:   return(0);
3991: }

3993: /*@C
3994:   SNESSetUpdate - Sets the general-purpose update function called
3995:   at the beginning of every iteration of the nonlinear solve. Specifically
3996:   it is called just before the Jacobian is "evaluated".

3998:   Logically Collective on SNES

4000:   Input Parameters:
4001: . snes - The nonlinear solver context
4002: . func - The function

4004:   Calling sequence of func:
4005: . func (SNES snes, PetscInt step);

4007: . step - The current step of the iteration

4009:   Level: advanced

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

4014: .keywords: SNES, update

4016: .seealso SNESSetJacobian(), SNESSolve()
4017: @*/
4018: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4019: {
4022:   snes->ops->update = func;
4023:   return(0);
4024: }

4026: /*
4027:    SNESScaleStep_Private - Scales a step so that its length is less than the
4028:    positive parameter delta.

4030:     Input Parameters:
4031: +   snes - the SNES context
4032: .   y - approximate solution of linear system
4033: .   fnorm - 2-norm of current function
4034: -   delta - trust region size

4036:     Output Parameters:
4037: +   gpnorm - predicted function norm at the new point, assuming local
4038:     linearization.  The value is zero if the step lies within the trust
4039:     region, and exceeds zero otherwise.
4040: -   ynorm - 2-norm of the step

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

4046: .keywords: SNES, nonlinear, scale, step
4047: */
4048: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4049: {
4050:   PetscReal      nrm;
4051:   PetscScalar    cnorm;


4059:   VecNorm(y,NORM_2,&nrm);
4060:   if (nrm > *delta) {
4061:     nrm     = *delta/nrm;
4062:     *gpnorm = (1.0 - nrm)*(*fnorm);
4063:     cnorm   = nrm;
4064:     VecScale(y,cnorm);
4065:     *ynorm  = *delta;
4066:   } else {
4067:     *gpnorm = 0.0;
4068:     *ynorm  = nrm;
4069:   }
4070:   return(0);
4071: }

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

4076:    Collective on SNES

4078:    Parameter:
4079: +  snes - iterative context obtained from SNESCreate()
4080: -  viewer - the viewer to display the reason


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

4086:    Level: beginner

4088: .keywords: SNES, solve, linear system

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

4092: @*/
4093: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
4094: {
4095:   PetscViewerFormat format;
4096:   PetscBool         isAscii;
4097:   PetscErrorCode    ierr;

4100:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
4101:   if (isAscii) {
4102:     PetscViewerGetFormat(viewer, &format);
4103:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
4104:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4105:       DM                dm;
4106:       Vec               u;
4107:       PetscDS           prob;
4108:       PetscInt          Nf, f;
4109:       PetscErrorCode (**exactFuncs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4110:       PetscReal         error;

4112:       SNESGetDM(snes, &dm);
4113:       SNESGetSolution(snes, &u);
4114:       DMGetDS(dm, &prob);
4115:       PetscDSGetNumFields(prob, &Nf);
4116:       PetscMalloc1(Nf, &exactFuncs);
4117:       for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactFuncs[f]);}
4118:       DMComputeL2Diff(dm, 0.0, exactFuncs, NULL, u, &error);
4119:       PetscFree(exactFuncs);
4120:       if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
4121:       else                 {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
4122:     }
4123:     if (snes->reason > 0) {
4124:       if (((PetscObject) snes)->prefix) {
4125:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4126:       } else {
4127:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4128:       }
4129:     } else {
4130:       if (((PetscObject) snes)->prefix) {
4131:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4132:       } else {
4133:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4134:       }
4135:     }
4136:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4137:   }
4138:   return(0);
4139: }

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

4144:   Collective on SNES

4146:   Input Parameters:
4147: . snes   - the SNES object

4149:   Level: intermediate

4151: @*/
4152: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
4153: {
4154:   PetscErrorCode    ierr;
4155:   PetscViewer       viewer;
4156:   PetscBool         flg;
4157:   static PetscBool  incall = PETSC_FALSE;
4158:   PetscViewerFormat format;

4161:   if (incall) return(0);
4162:   incall = PETSC_TRUE;
4163:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4164:   if (flg) {
4165:     PetscViewerPushFormat(viewer,format);
4166:     SNESReasonView(snes,viewer);
4167:     PetscViewerPopFormat(viewer);
4168:     PetscViewerDestroy(&viewer);
4169:   }
4170:   incall = PETSC_FALSE;
4171:   return(0);
4172: }

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

4178:    Collective on SNES

4180:    Input Parameters:
4181: +  snes - the SNES context
4182: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4183: -  x - the solution vector.

4185:    Notes:
4186:    The user should initialize the vector,x, with the initial guess
4187:    for the nonlinear solve prior to calling SNESSolve.  In particular,
4188:    to employ an initial guess of zero, the user should explicitly set
4189:    this vector to zero by calling VecSet().

4191:    Level: beginner

4193: .keywords: SNES, nonlinear, solve

4195: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4196: @*/
4197: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4198: {
4199:   PetscErrorCode    ierr;
4200:   PetscBool         flg;
4201:   PetscInt          grid;
4202:   Vec               xcreated = NULL;
4203:   DM                dm;


4212:   /* High level operations using the nonlinear solver */
4213:   {
4214:     PetscViewer       viewer;
4215:     PetscViewerFormat format;
4216:     PetscInt          num;
4217:     PetscBool         flg;
4218:     static PetscBool  incall = PETSC_FALSE;

4220:     if (!incall) {
4221:       /* Estimate the convergence rate of the discretization */
4222:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes), ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4223:       if (flg) {
4224:         PetscConvEst conv;
4225:         PetscReal    alpha; /* Convergence rate of the solution error in the L_2 norm */

4227:         incall = PETSC_TRUE;
4228:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4229:         PetscConvEstSetSolver(conv, snes);
4230:         PetscConvEstSetFromOptions(conv);
4231:         PetscConvEstSetUp(conv);
4232:         PetscConvEstGetConvRate(conv, &alpha);
4233:         PetscViewerPushFormat(viewer, format);
4234:         PetscConvEstRateView(conv, alpha, viewer);
4235:         PetscViewerPopFormat(viewer);
4236:         PetscViewerDestroy(&viewer);
4237:         PetscConvEstDestroy(&conv);
4238:         incall = PETSC_FALSE;
4239:       }
4240:       /* Adaptively refine the initial grid */
4241:       num  = 1;
4242:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);
4243:       if (flg) {
4244:         DMAdaptor adaptor;

4246:         incall = PETSC_TRUE;
4247:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4248:         DMAdaptorSetSolver(adaptor, snes);
4249:         DMAdaptorSetSequenceLength(adaptor, num);
4250:         DMAdaptorSetFromOptions(adaptor);
4251:         DMAdaptorSetUp(adaptor);
4252:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4253:         DMAdaptorDestroy(&adaptor);
4254:         incall = PETSC_FALSE;
4255:       }
4256:       /* Use grid sequencing to adapt */
4257:       num  = 0;
4258:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4259:       if (num) {
4260:         DMAdaptor adaptor;

4262:         incall = PETSC_TRUE;
4263:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4264:         DMAdaptorSetSolver(adaptor, snes);
4265:         DMAdaptorSetSequenceLength(adaptor, num);
4266:         DMAdaptorSetFromOptions(adaptor);
4267:         DMAdaptorSetUp(adaptor);
4268:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4269:         DMAdaptorDestroy(&adaptor);
4270:         incall = PETSC_FALSE;
4271:       }
4272:     }
4273:   }
4274:   if (!x) {
4275:     SNESGetDM(snes,&dm);
4276:     DMCreateGlobalVector(dm,&xcreated);
4277:     x    = xcreated;
4278:   }
4279:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4284:     /* set solution vector */
4285:     if (!grid) {PetscObjectReference((PetscObject)x);}
4286:     VecDestroy(&snes->vec_sol);
4287:     snes->vec_sol = x;
4288:     SNESGetDM(snes,&dm);

4290:     /* set affine vector if provided */
4291:     if (b) { PetscObjectReference((PetscObject)b); }
4292:     VecDestroy(&snes->vec_rhs);
4293:     snes->vec_rhs = b;

4295:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4296:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4297:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4298:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4299:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4300:     }
4301:     DMShellSetGlobalVector(dm,snes->vec_sol);
4302:     SNESSetUp(snes);

4304:     if (!grid) {
4305:       if (snes->ops->computeinitialguess) {
4306:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4307:       }
4308:     }

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

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

4319:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4320:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4326:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4327:     if (snes->reason < 0) break;
4328:     if (grid <  snes->gridsequence) {
4329:       DM  fine;
4330:       Vec xnew;
4331:       Mat interp;

4333:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4334:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4335:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4336:       DMCreateGlobalVector(fine,&xnew);
4337:       MatInterpolate(interp,x,xnew);
4338:       DMInterpolate(snes->dm,interp,fine);
4339:       MatDestroy(&interp);
4340:       x    = xnew;

4342:       SNESReset(snes);
4343:       SNESSetDM(snes,fine);
4344:       DMDestroy(&fine);
4345:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4346:     }
4347:   }
4348:   SNESViewFromOptions(snes,NULL,"-snes_view");
4349:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4351:   VecDestroy(&xcreated);
4352:   PetscObjectSAWsBlock((PetscObject)snes);
4353:   return(0);
4354: }

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

4358: /*@C
4359:    SNESSetType - Sets the method for the nonlinear solver.

4361:    Collective on SNES

4363:    Input Parameters:
4364: +  snes - the SNES context
4365: -  type - a known method

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

4371:    Notes:
4372:    See "petsc/include/petscsnes.h" for available methods (for instance)
4373: +    SNESNEWTONLS - Newton's method with line search
4374:      (systems of nonlinear equations)
4375: .    SNESNEWTONTR - Newton's method with trust region
4376:      (systems of nonlinear equations)

4378:   Normally, it is best to use the SNESSetFromOptions() command and then
4379:   set the SNES solver type from the options database rather than by using
4380:   this routine.  Using the options database provides the user with
4381:   maximum flexibility in evaluating the many nonlinear solvers.
4382:   The SNESSetType() routine is provided for those situations where it
4383:   is necessary to set the nonlinear solver independently of the command
4384:   line or options database.  This might be the case, for example, when
4385:   the choice of solver changes during the execution of the program,
4386:   and the user's application is taking responsibility for choosing the
4387:   appropriate method.

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

4392:   Level: intermediate

4394: .keywords: SNES, set, type

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

4398: @*/
4399: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4400: {
4401:   PetscErrorCode ierr,(*r)(SNES);
4402:   PetscBool      match;


4408:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4409:   if (match) return(0);

4411:    PetscFunctionListFind(SNESList,type,&r);
4412:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4413:   /* Destroy the previous private SNES context */
4414:   if (snes->ops->destroy) {
4415:     (*(snes)->ops->destroy)(snes);
4416:     snes->ops->destroy = NULL;
4417:   }
4418:   /* Reinitialize function pointers in SNESOps structure */
4419:   snes->ops->setup          = 0;
4420:   snes->ops->solve          = 0;
4421:   snes->ops->view           = 0;
4422:   snes->ops->setfromoptions = 0;
4423:   snes->ops->destroy        = 0;
4424:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4425:   snes->setupcalled = PETSC_FALSE;

4427:   PetscObjectChangeTypeName((PetscObject)snes,type);
4428:   (*r)(snes);
4429:   return(0);
4430: }

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

4435:    Not Collective

4437:    Input Parameter:
4438: .  snes - nonlinear solver context

4440:    Output Parameter:
4441: .  type - SNES method (a character string)

4443:    Level: intermediate

4445: .keywords: SNES, nonlinear, get, type, name
4446: @*/
4447: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4448: {
4452:   *type = ((PetscObject)snes)->type_name;
4453:   return(0);
4454: }

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

4459:   Logically Collective on SNES and Vec

4461:   Input Parameters:
4462: + snes - the SNES context obtained from SNESCreate()
4463: - u    - the solution vector

4465:   Level: beginner

4467: .keywords: SNES, set, solution
4468: @*/
4469: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4470: {
4471:   DM             dm;

4477:   PetscObjectReference((PetscObject) u);
4478:   VecDestroy(&snes->vec_sol);

4480:   snes->vec_sol = u;

4482:   SNESGetDM(snes, &dm);
4483:   DMShellSetGlobalVector(dm, u);
4484:   return(0);
4485: }

4487: /*@
4488:    SNESGetSolution - Returns the vector where the approximate solution is
4489:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4493:    Input Parameter:
4494: .  snes - the SNES context

4496:    Output Parameter:
4497: .  x - the solution

4499:    Level: intermediate

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

4503: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4504: @*/
4505: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4506: {
4510:   *x = snes->vec_sol;
4511:   return(0);
4512: }

4514: /*@
4515:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4516:    stored.

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

4520:    Input Parameter:
4521: .  snes - the SNES context

4523:    Output Parameter:
4524: .  x - the solution update

4526:    Level: advanced

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

4530: .seealso: SNESGetSolution(), SNESGetFunction()
4531: @*/
4532: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4533: {
4537:   *x = snes->vec_sol_update;
4538:   return(0);
4539: }

4541: /*@C
4542:    SNESGetFunction - Returns the vector where the function is stored.

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

4546:    Input Parameter:
4547: .  snes - the SNES context

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

4554:    Level: advanced

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

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

4560: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4561: @*/
4562: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4563: {
4565:   DM             dm;

4569:   if (r) {
4570:     if (!snes->vec_func) {
4571:       if (snes->vec_rhs) {
4572:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4573:       } else if (snes->vec_sol) {
4574:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4575:       } else if (snes->dm) {
4576:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4577:       }
4578:     }
4579:     *r = snes->vec_func;
4580:   }
4581:   SNESGetDM(snes,&dm);
4582:   DMSNESGetFunction(dm,f,ctx);
4583:   return(0);
4584: }

4586: /*@C
4587:    SNESGetNGS - Returns the NGS function and context.

4589:    Input Parameter:
4590: .  snes - the SNES context

4592:    Output Parameter:
4593: +  f - the function (or NULL) see SNESNGSFunction for details
4594: -  ctx    - the function context (or NULL)

4596:    Level: advanced

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

4600: .seealso: SNESSetNGS(), SNESGetFunction()
4601: @*/

4603: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4604: {
4606:   DM             dm;

4610:   SNESGetDM(snes,&dm);
4611:   DMSNESGetNGS(dm,f,ctx);
4612:   return(0);
4613: }

4615: /*@C
4616:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4617:    SNES options in the database.

4619:    Logically Collective on SNES

4621:    Input Parameter:
4622: +  snes - the SNES context
4623: -  prefix - the prefix to prepend to all option names

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

4629:    Level: advanced

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

4633: .seealso: SNESSetFromOptions()
4634: @*/
4635: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4636: {

4641:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4642:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4643:   if (snes->linesearch) {
4644:     SNESGetLineSearch(snes,&snes->linesearch);
4645:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4646:   }
4647:   KSPSetOptionsPrefix(snes->ksp,prefix);
4648:   return(0);
4649: }

4651: /*@C
4652:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4653:    SNES options in the database.

4655:    Logically Collective on SNES

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

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

4665:    Level: advanced

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

4669: .seealso: SNESGetOptionsPrefix()
4670: @*/
4671: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4672: {

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

4687: /*@C
4688:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4689:    SNES options in the database.

4691:    Not Collective

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

4696:    Output Parameter:
4697: .  prefix - pointer to the prefix string used

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

4702:    Level: advanced

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

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

4714:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4715:   return(0);
4716: }


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

4722:    Not collective

4724:    Input Parameters:
4725: +  name_solver - name of a new user-defined solver
4726: -  routine_create - routine to create method context

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

4731:    Sample usage:
4732: .vb
4733:    SNESRegister("my_solver",MySolverCreate);
4734: .ve

4736:    Then, your solver can be chosen with the procedural interface via
4737: $     SNESSetType(snes,"my_solver")
4738:    or at runtime via the option
4739: $     -snes_type my_solver

4741:    Level: advanced

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

4745: .keywords: SNES, nonlinear, register

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

4749:   Level: advanced
4750: @*/
4751: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4752: {

4756:   PetscFunctionListAdd(&SNESList,sname,function);
4757:   return(0);
4758: }

4760: PetscErrorCode  SNESTestLocalMin(SNES snes)
4761: {
4763:   PetscInt       N,i,j;
4764:   Vec            u,uh,fh;
4765:   PetscScalar    value;
4766:   PetscReal      norm;

4769:   SNESGetSolution(snes,&u);
4770:   VecDuplicate(u,&uh);
4771:   VecDuplicate(u,&fh);

4773:   /* currently only works for sequential */
4774:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4775:   VecGetSize(u,&N);
4776:   for (i=0; i<N; i++) {
4777:     VecCopy(u,uh);
4778:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4779:     for (j=-10; j<11; j++) {
4780:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4781:       VecSetValue(uh,i,value,ADD_VALUES);
4782:       SNESComputeFunction(snes,uh,fh);
4783:       VecNorm(fh,NORM_2,&norm);
4784:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4785:       value = -value;
4786:       VecSetValue(uh,i,value,ADD_VALUES);
4787:     }
4788:   }
4789:   VecDestroy(&uh);
4790:   VecDestroy(&fh);
4791:   return(0);
4792: }

4794: /*@
4795:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4796:    computing relative tolerance for linear solvers within an inexact
4797:    Newton method.

4799:    Logically Collective on SNES

4801:    Input Parameters:
4802: +  snes - SNES context
4803: -  flag - PETSC_TRUE or PETSC_FALSE

4805:     Options Database:
4806: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4807: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4808: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4809: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4810: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4811: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4812: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4813: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4815:    Notes:
4816:    Currently, the default is to use a constant relative tolerance for
4817:    the inner linear solvers.  Alternatively, one can use the
4818:    Eisenstat-Walker method, where the relative convergence tolerance
4819:    is reset at each Newton iteration according progress of the nonlinear
4820:    solver.

4822:    Level: advanced

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

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

4830: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4831: @*/
4832: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4833: {
4837:   snes->ksp_ewconv = flag;
4838:   return(0);
4839: }

4841: /*@
4842:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4843:    for computing relative tolerance for linear solvers within an
4844:    inexact Newton method.

4846:    Not Collective

4848:    Input Parameter:
4849: .  snes - SNES context

4851:    Output Parameter:
4852: .  flag - PETSC_TRUE or PETSC_FALSE

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

4861:    Level: advanced

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

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

4869: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4870: @*/
4871: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4872: {
4876:   *flag = snes->ksp_ewconv;
4877:   return(0);
4878: }

4880: /*@
4881:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4882:    convergence criteria for the linear solvers within an inexact
4883:    Newton method.

4885:    Logically Collective on SNES

4887:    Input Parameters:
4888: +    snes - SNES context
4889: .    version - version 1, 2 (default is 2) or 3
4890: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4891: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4892: .    gamma - multiplicative factor for version 2 rtol computation
4893:              (0 <= gamma2 <= 1)
4894: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4895: .    alpha2 - power for safeguard
4896: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4898:    Note:
4899:    Version 3 was contributed by Luis Chacon, June 2006.

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

4903:    Level: advanced

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

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

4912: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4913: @*/
4914: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4915: {
4916:   SNESKSPEW *kctx;

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

4930:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4931:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4932:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4933:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4934:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4935:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4936:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4938:   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);
4939:   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);
4940:   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);
4941:   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);
4942:   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);
4943:   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);
4944:   return(0);
4945: }

4947: /*@
4948:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4949:    convergence criteria for the linear solvers within an inexact
4950:    Newton method.

4952:    Not Collective

4954:    Input Parameters:
4955:      snes - SNES context

4957:    Output Parameters:
4958: +    version - version 1, 2 (default is 2) or 3
4959: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4960: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4961: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
4962: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4963: .    alpha2 - power for safeguard
4964: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4966:    Level: advanced

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

4970: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
4971: @*/
4972: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
4973: {
4974:   SNESKSPEW *kctx;

4978:   kctx = (SNESKSPEW*)snes->kspconvctx;
4979:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
4980:   if (version)   *version   = kctx->version;
4981:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
4982:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
4983:   if (gamma)     *gamma     = kctx->gamma;
4984:   if (alpha)     *alpha     = kctx->alpha;
4985:   if (alpha2)    *alpha2    = kctx->alpha2;
4986:   if (threshold) *threshold = kctx->threshold;
4987:   return(0);
4988: }

4990:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4991: {
4993:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4994:   PetscReal      rtol  = PETSC_DEFAULT,stol;

4997:   if (!snes->ksp_ewconv) return(0);
4998:   if (!snes->iter) {
4999:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5000:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
5001:   }
5002:   else {
5003:     if (kctx->version == 1) {
5004:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
5005:       if (rtol < 0.0) rtol = -rtol;
5006:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5007:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5008:     } else if (kctx->version == 2) {
5009:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5010:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5011:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5012:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5013:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5014:       /* safeguard: avoid sharp decrease of rtol */
5015:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5016:       stol = PetscMax(rtol,stol);
5017:       rtol = PetscMin(kctx->rtol_0,stol);
5018:       /* safeguard: avoid oversolving */
5019:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5020:       stol = PetscMax(rtol,stol);
5021:       rtol = PetscMin(kctx->rtol_0,stol);
5022:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
5023:   }
5024:   /* safeguard: avoid rtol greater than one */
5025:   rtol = PetscMin(rtol,kctx->rtol_max);
5026:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
5027:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
5028:   return(0);
5029: }

5031: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5032: {
5034:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5035:   PCSide         pcside;
5036:   Vec            lres;

5039:   if (!snes->ksp_ewconv) return(0);
5040:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
5041:   kctx->norm_last = snes->norm;
5042:   if (kctx->version == 1) {
5043:     PC        pc;
5044:     PetscBool isNone;

5046:     KSPGetPC(ksp, &pc);
5047:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
5048:     KSPGetPCSide(ksp,&pcside);
5049:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
5050:       /* KSP residual is true linear residual */
5051:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
5052:     } else {
5053:       /* KSP residual is preconditioned residual */
5054:       /* compute true linear residual norm */
5055:       VecDuplicate(b,&lres);
5056:       MatMult(snes->jacobian,x,lres);
5057:       VecAYPX(lres,-1.0,b);
5058:       VecNorm(lres,NORM_2,&kctx->lresid_last);
5059:       VecDestroy(&lres);
5060:     }
5061:   }
5062:   return(0);
5063: }

5065: /*@
5066:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

5070:    Input Parameter:
5071: .  snes - the SNES context

5073:    Output Parameter:
5074: .  ksp - the KSP context

5076:    Notes:
5077:    The user can then directly manipulate the KSP context to set various
5078:    options, etc.  Likewise, the user can then extract and manipulate the
5079:    PC contexts as well.

5081:    Level: beginner

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

5085: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5086: @*/
5087: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
5088: {


5095:   if (!snes->ksp) {
5096:     PetscBool monitor = PETSC_FALSE;

5098:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
5099:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
5100:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

5105:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
5106:     if (monitor) {
5107:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
5108:     }
5109:     monitor = PETSC_FALSE;
5110:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
5111:     if (monitor) {
5112:       PetscObject *objs;
5113:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
5114:       objs[0] = (PetscObject) snes;
5115:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
5116:     }
5117:   }
5118:   *ksp = snes->ksp;
5119:   return(0);
5120: }


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

5127:    Logically Collective on SNES

5129:    Input Parameters:
5130: +  snes - the nonlinear solver context
5131: -  dm - the dm, cannot be NULL

5133:    Level: intermediate

5135: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
5136: @*/
5137: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5138: {
5140:   KSP            ksp;
5141:   DMSNES         sdm;

5146:   PetscObjectReference((PetscObject)dm);
5147:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5148:     if (snes->dm->dmsnes && !dm->dmsnes) {
5149:       DMCopyDMSNES(snes->dm,dm);
5150:       DMGetDMSNES(snes->dm,&sdm);
5151:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5152:     }
5153:     DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5154:     DMDestroy(&snes->dm);
5155:   }
5156:   snes->dm     = dm;
5157:   snes->dmAuto = PETSC_FALSE;

5159:   SNESGetKSP(snes,&ksp);
5160:   KSPSetDM(ksp,dm);
5161:   KSPSetDMActive(ksp,PETSC_FALSE);
5162:   if (snes->npc) {
5163:     SNESSetDM(snes->npc, snes->dm);
5164:     SNESSetNPCSide(snes,snes->npcside);
5165:   }
5166:   return(0);
5167: }

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

5172:    Not Collective but DM obtained is parallel on SNES

5174:    Input Parameter:
5175: . snes - the preconditioner context

5177:    Output Parameter:
5178: .  dm - the dm

5180:    Level: intermediate

5182: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5183: @*/
5184: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5185: {

5190:   if (!snes->dm) {
5191:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5192:     snes->dmAuto = PETSC_TRUE;
5193:   }
5194:   *dm = snes->dm;
5195:   return(0);
5196: }

5198: /*@
5199:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5201:   Collective on SNES

5203:   Input Parameters:
5204: + snes - iterative context obtained from SNESCreate()
5205: - pc   - the preconditioner object

5207:   Notes:
5208:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5209:   to configure it using the API).

5211:   Level: developer

5213: .keywords: SNES, set, precondition
5214: .seealso: SNESGetNPC(), SNESHasNPC()
5215: @*/
5216: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5217: {

5224:   PetscObjectReference((PetscObject) pc);
5225:   SNESDestroy(&snes->npc);
5226:   snes->npc = pc;
5227:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5228:   return(0);
5229: }

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

5234:   Not Collective

5236:   Input Parameter:
5237: . snes - iterative context obtained from SNESCreate()

5239:   Output Parameter:
5240: . pc - preconditioner context

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

5244:   Level: developer

5246: .keywords: SNES, get, preconditioner
5247: .seealso: SNESSetNPC(), SNESHasNPC()
5248: @*/
5249: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5250: {
5252:   const char     *optionsprefix;

5257:   if (!snes->npc) {
5258:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5259:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5260:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5261:     SNESGetOptionsPrefix(snes,&optionsprefix);
5262:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5263:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5264:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5265:   }
5266:   *pc = snes->npc;
5267:   return(0);
5268: }

5270: /*@
5271:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5273:   Not Collective

5275:   Input Parameter:
5276: . snes - iterative context obtained from SNESCreate()

5278:   Output Parameter:
5279: . has_npc - whether the SNES has an NPC or not

5281:   Level: developer

5283: .keywords: SNES, has, preconditioner
5284: .seealso: SNESSetNPC(), SNESGetNPC()
5285: @*/
5286: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5287: {
5290:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5291:   return(0);
5292: }

5294: /*@
5295:     SNESSetNPCSide - Sets the preconditioning side.

5297:     Logically Collective on SNES

5299:     Input Parameter:
5300: .   snes - iterative context obtained from SNESCreate()

5302:     Output Parameter:
5303: .   side - the preconditioning side, where side is one of
5304: .vb
5305:       PC_LEFT - left preconditioning
5306:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5307: .ve

5309:     Options Database Keys:
5310: .   -snes_pc_side <right,left>

5312:     Notes: SNESNRICHARDSON and SNESNCG only support left preconditioning.

5314:     Level: intermediate

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

5318: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5319: @*/
5320: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5321: {
5325:   snes->npcside= side;
5326:   return(0);
5327: }

5329: /*@
5330:     SNESGetNPCSide - Gets the preconditioning side.

5332:     Not Collective

5334:     Input Parameter:
5335: .   snes - iterative context obtained from SNESCreate()

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

5344:     Level: intermediate

5346: .keywords: SNES, get, right, left, side, preconditioner, flag

5348: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5349: @*/
5350: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5351: {
5355:   *side = snes->npcside;
5356:   return(0);
5357: }

5359: /*@
5360:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5362:   Collective on SNES

5364:   Input Parameters:
5365: + snes - iterative context obtained from SNESCreate()
5366: - linesearch   - the linesearch object

5368:   Notes:
5369:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5370:   to configure it using the API).

5372:   Level: developer

5374: .keywords: SNES, set, linesearch
5375: .seealso: SNESGetLineSearch()
5376: @*/
5377: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5378: {

5385:   PetscObjectReference((PetscObject) linesearch);
5386:   SNESLineSearchDestroy(&snes->linesearch);

5388:   snes->linesearch = linesearch;

5390:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5391:   return(0);
5392: }

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

5398:   Not Collective

5400:   Input Parameter:
5401: . snes - iterative context obtained from SNESCreate()

5403:   Output Parameter:
5404: . linesearch - linesearch context

5406:   Level: beginner

5408: .keywords: SNES, get, linesearch
5409: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5410: @*/
5411: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5412: {
5414:   const char     *optionsprefix;

5419:   if (!snes->linesearch) {
5420:     SNESGetOptionsPrefix(snes, &optionsprefix);
5421:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5422:     SNESLineSearchSetSNES(snes->linesearch, snes);
5423:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5424:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5425:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5426:   }
5427:   *linesearch = snes->linesearch;
5428:   return(0);
5429: }

5431: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5432: #include <mex.h>

5434: typedef struct {char *funcname; mxArray *ctx;} SNESMatlabContext;

5436: /*
5437:    SNESComputeFunction_Matlab - Calls the function that has been set with SNESSetFunctionMatlab().

5439:    Collective on SNES

5441:    Input Parameters:
5442: +  snes - the SNES context
5443: -  x - input vector

5445:    Output Parameter:
5446: .  y - function vector, as set by SNESSetFunction()

5448:    Notes:
5449:    SNESComputeFunction() is typically used within nonlinear solvers
5450:    implementations, so most users would not generally call this routine
5451:    themselves.

5453:    Level: developer

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

5457: .seealso: SNESSetFunction(), SNESGetFunction()
5458: */
5459: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5460: {
5461:   PetscErrorCode    ierr;
5462:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5463:   int               nlhs  = 1,nrhs = 5;
5464:   mxArray           *plhs[1],*prhs[5];
5465:   long long int     lx = 0,ly = 0,ls = 0;


5474:   /* call Matlab function in ctx with arguments x and y */

5476:   PetscMemcpy(&ls,&snes,sizeof(snes));
5477:   PetscMemcpy(&lx,&x,sizeof(x));
5478:   PetscMemcpy(&ly,&y,sizeof(x));
5479:   prhs[0] = mxCreateDoubleScalar((double)ls);
5480:   prhs[1] = mxCreateDoubleScalar((double)lx);
5481:   prhs[2] = mxCreateDoubleScalar((double)ly);
5482:   prhs[3] = mxCreateString(sctx->funcname);
5483:   prhs[4] = sctx->ctx;
5484:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");
5485:   mxGetScalar(plhs[0]);
5486:   mxDestroyArray(prhs[0]);
5487:   mxDestroyArray(prhs[1]);
5488:   mxDestroyArray(prhs[2]);
5489:   mxDestroyArray(prhs[3]);
5490:   mxDestroyArray(plhs[0]);
5491:   return(0);
5492: }

5494: /*
5495:    SNESSetFunctionMatlab - Sets the function evaluation routine and function
5496:    vector for use by the SNES routines in solving systems of nonlinear
5497:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

5499:    Logically Collective on SNES

5501:    Input Parameters:
5502: +  snes - the SNES context
5503: .  r - vector to store function value
5504: -  f - function evaluation routine

5506:    Notes:
5507:    The Newton-like methods typically solve linear systems of the form
5508: $      f'(x) x = -f(x),
5509:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5511:    Level: beginner

5513:    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;

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

5517: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5518: */
5519: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5520: {
5521:   PetscErrorCode    ierr;
5522:   SNESMatlabContext *sctx;

5525:   /* currently sctx is memory bleed */
5526:   PetscNew(&sctx);
5527:   PetscStrallocpy(f,&sctx->funcname);
5528:   /*
5529:      This should work, but it doesn't
5530:   sctx->ctx = ctx;
5531:   mexMakeArrayPersistent(sctx->ctx);
5532:   */
5533:   sctx->ctx = mxDuplicateArray(ctx);
5534:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5535:   return(0);
5536: }

5538: /*
5539:    SNESComputeJacobian_Matlab - Calls the function that has been set with SNESSetJacobianMatlab().

5541:    Collective on SNES

5543:    Input Parameters:
5544: +  snes - the SNES context
5545: .  x - input vector
5546: .  A, B - the matrices
5547: -  ctx - user context

5549:    Level: developer

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

5553: .seealso: SNESSetFunction(), SNESGetFunction()
5554: @*/
5555: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5556: {
5557:   PetscErrorCode    ierr;
5558:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5559:   int               nlhs  = 2,nrhs = 6;
5560:   mxArray           *plhs[2],*prhs[6];
5561:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


5567:   /* call Matlab function in ctx with arguments x and y */

5569:   PetscMemcpy(&ls,&snes,sizeof(snes));
5570:   PetscMemcpy(&lx,&x,sizeof(x));
5571:   PetscMemcpy(&lA,A,sizeof(x));
5572:   PetscMemcpy(&lB,B,sizeof(x));
5573:   prhs[0] = mxCreateDoubleScalar((double)ls);
5574:   prhs[1] = mxCreateDoubleScalar((double)lx);
5575:   prhs[2] = mxCreateDoubleScalar((double)lA);
5576:   prhs[3] = mxCreateDoubleScalar((double)lB);
5577:   prhs[4] = mxCreateString(sctx->funcname);
5578:   prhs[5] = sctx->ctx;
5579:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5580:   mxGetScalar(plhs[0]);
5581:   mxDestroyArray(prhs[0]);
5582:   mxDestroyArray(prhs[1]);
5583:   mxDestroyArray(prhs[2]);
5584:   mxDestroyArray(prhs[3]);
5585:   mxDestroyArray(prhs[4]);
5586:   mxDestroyArray(plhs[0]);
5587:   mxDestroyArray(plhs[1]);
5588:   return(0);
5589: }

5591: /*
5592:    SNESSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
5593:    vector for use by the SNES routines in solving systems of nonlinear
5594:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

5596:    Logically Collective on SNES

5598:    Input Parameters:
5599: +  snes - the SNES context
5600: .  A,B - Jacobian matrices
5601: .  J - function evaluation routine
5602: -  ctx - user context

5604:    Level: developer

5606:    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;

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

5610: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5611: */
5612: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5613: {
5614:   PetscErrorCode    ierr;
5615:   SNESMatlabContext *sctx;

5618:   /* currently sctx is memory bleed */
5619:   PetscNew(&sctx);
5620:   PetscStrallocpy(J,&sctx->funcname);
5621:   /*
5622:      This should work, but it doesn't
5623:   sctx->ctx = ctx;
5624:   mexMakeArrayPersistent(sctx->ctx);
5625:   */
5626:   sctx->ctx = mxDuplicateArray(ctx);
5627:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5628:   return(0);
5629: }

5631: /*
5632:    SNESMonitor_Matlab - Calls the function that has been set with SNESMonitorSetMatlab().

5634:    Collective on SNES

5636: .seealso: SNESSetFunction(), SNESGetFunction()
5637: @*/
5638: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5639: {
5640:   PetscErrorCode    ierr;
5641:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5642:   int               nlhs  = 1,nrhs = 6;
5643:   mxArray           *plhs[1],*prhs[6];
5644:   long long int     lx = 0,ls = 0;
5645:   Vec               x  = snes->vec_sol;


5650:   PetscMemcpy(&ls,&snes,sizeof(snes));
5651:   PetscMemcpy(&lx,&x,sizeof(x));
5652:   prhs[0] = mxCreateDoubleScalar((double)ls);
5653:   prhs[1] = mxCreateDoubleScalar((double)it);
5654:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5655:   prhs[3] = mxCreateDoubleScalar((double)lx);
5656:   prhs[4] = mxCreateString(sctx->funcname);
5657:   prhs[5] = sctx->ctx;
5658:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5659:   mxGetScalar(plhs[0]);
5660:   mxDestroyArray(prhs[0]);
5661:   mxDestroyArray(prhs[1]);
5662:   mxDestroyArray(prhs[2]);
5663:   mxDestroyArray(prhs[3]);
5664:   mxDestroyArray(prhs[4]);
5665:   mxDestroyArray(plhs[0]);
5666:   return(0);
5667: }

5669: /*
5670:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5672:    Level: developer

5674:    Developer Note:  This bleeds the allocated memory SNESMatlabContext *sctx;

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

5678: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5679: */
5680: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5681: {
5682:   PetscErrorCode    ierr;
5683:   SNESMatlabContext *sctx;

5686:   /* currently sctx is memory bleed */
5687:   PetscNew(&sctx);
5688:   PetscStrallocpy(f,&sctx->funcname);
5689:   /*
5690:      This should work, but it doesn't
5691:   sctx->ctx = ctx;
5692:   mexMakeArrayPersistent(sctx->ctx);
5693:   */
5694:   sctx->ctx = mxDuplicateArray(ctx);
5695:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5696:   return(0);
5697: }

5699: #endif