Actual source code: snes.c

petsc-master 2014-12-27
Report Typos and Errors
  2: #include <petsc-private/snesimpl.h>      /*I "petscsnes.h"  I*/
  3: #include <petscdmshell.h>

  5: PetscBool         SNESRegisterAllCalled = PETSC_FALSE;
  6: PetscFunctionList SNESList              = NULL;

  8: /* Logging support */
  9: PetscClassId  SNES_CLASSID, DMSNES_CLASSID;
 10: PetscLogEvent SNES_Solve, SNES_FunctionEval, SNES_JacobianEval, SNES_NGSEval, SNES_NGSFuncEval, SNES_NPCSolve;

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

 17:    Logically Collective on SNES

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

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

 26:    Level: intermediate

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

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

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

 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: }

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

 79:    Logically Collective on SNES

 81:    Input Parameters:
 82: .  snes - the SNES context

 84:    Level: advanced

 86: .keywords: SNES, view

 88: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction
 89: @*/
 90: PetscErrorCode  SNESSetFunctionDomainError(SNES snes)
 91: {
 94:   snes->domainerror = PETSC_TRUE;
 95:   return(0);
 96: }

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

103:    Logically Collective on SNES

105:    Input Parameters:
106: .  snes - the SNES context

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

111:    Level: advanced

113: .keywords: SNES, view

115: .seealso: SNESSetFunctionDomainError(), SNESComputeFunction()
116: @*/
117: PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
118: {
122:   *domainerror = snes->domainerror;
123:   return(0);
124: }

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

131:   Collective on PetscViewer

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

138:    Level: intermediate

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

143:   Notes for advanced users:
144:   Most users should not need to know the details of the binary storage
145:   format, since SNESLoad() and TSView() completely hide these details.
146:   But for anyone who's interested, the standard binary matrix storage
147:   format is
148: .vb
149:      has not yet been determined
150: .ve

152: .seealso: PetscViewerBinaryOpen(), SNESView(), MatLoad(), VecLoad()
153: @*/
154: PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
155: {
157:   PetscBool      isbinary;
158:   PetscInt       classid;
159:   char           type[256];
160:   KSP            ksp;
161:   DM             dm;
162:   DMSNES         dmsnes;

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

170:   PetscViewerBinaryRead(viewer,&classid,1,PETSC_INT);
171:   if (classid != SNES_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
172:   PetscViewerBinaryRead(viewer,type,256,PETSC_CHAR);
173:   SNESSetType(snes, type);
174:   if (snes->ops->load) {
175:     (*snes->ops->load)(snes,viewer);
176:   }
177:   SNESGetDM(snes,&dm);
178:   DMGetDMSNES(dm,&dmsnes);
179:   DMSNESLoad(dmsnes,viewer);
180:   SNESGetKSP(snes,&ksp);
181:   KSPLoad(ksp,viewer);
182:   return(0);
183: }

185: #include <petscdraw.h>
186: #if defined(PETSC_HAVE_SAWS)
187: #include <petscviewersaws.h>
188: #endif
191: /*@C
192:    SNESView - Prints the SNES data structure.

194:    Collective on SNES

196:    Input Parameters:
197: +  SNES - the SNES context
198: -  viewer - visualization context

200:    Options Database Key:
201: .  -snes_view - Calls SNESView() at end of SNESSolve()

203:    Notes:
204:    The available visualization contexts include
205: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
206: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
207:          output where only the first processor opens
208:          the file.  All other processors send their
209:          data to the first processor to print.

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

214:    Level: beginner

216: .keywords: SNES, view

218: .seealso: PetscViewerASCIIOpen()
219: @*/
220: PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
221: {
222:   SNESKSPEW      *kctx;
224:   KSP            ksp;
225:   SNESLineSearch linesearch;
226:   PetscBool      iascii,isstring,isbinary,isdraw;
227:   DMSNES         dmsnes;
228: #if defined(PETSC_HAVE_SAWS)
229:   PetscBool      isams;
230: #endif

234:   if (!viewer) {
235:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer);
236:   }

240:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
241:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
242:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
243:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
244: #if defined(PETSC_HAVE_SAWS)
245:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&isams);
246: #endif
247:   if (iascii) {
248:     PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer);
249:     if (!snes->setupcalled) {
250:       PetscViewerASCIIPrintf(viewer,"  SNES has not been set up so information may be incomplete\n");
251:     }
252:     if (snes->ops->view) {
253:       PetscViewerASCIIPushTab(viewer);
254:       (*snes->ops->view)(snes,viewer);
255:       PetscViewerASCIIPopTab(viewer);
256:     }
257:     PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, maximum function evaluations=%D\n",snes->max_its,snes->max_funcs);
258:     PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol);
259:     PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",snes->linear_its);
260:     PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%D\n",snes->nfuncs);
261:     if (snes->gridsequence) {
262:       PetscViewerASCIIPrintf(viewer,"  total number of grid sequence refinements=%D\n",snes->gridsequence);
263:     }
264:     if (snes->ksp_ewconv) {
265:       kctx = (SNESKSPEW*)snes->kspconvctx;
266:       if (kctx) {
267:         PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %D)\n",kctx->version);
268:         PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold);
269:         PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2);
270:       }
271:     }
272:     if (snes->lagpreconditioner == -1) {
273:       PetscViewerASCIIPrintf(viewer,"  Preconditioned is never rebuilt\n");
274:     } else if (snes->lagpreconditioner > 1) {
275:       PetscViewerASCIIPrintf(viewer,"  Preconditioned is rebuilt every %D new Jacobians\n",snes->lagpreconditioner);
276:     }
277:     if (snes->lagjacobian == -1) {
278:       PetscViewerASCIIPrintf(viewer,"  Jacobian is never rebuilt\n");
279:     } else if (snes->lagjacobian > 1) {
280:       PetscViewerASCIIPrintf(viewer,"  Jacobian is rebuilt every %D SNES iterations\n",snes->lagjacobian);
281:     }
282:   } else if (isstring) {
283:     const char *type;
284:     SNESGetType(snes,&type);
285:     PetscViewerStringSPrintf(viewer," %-3.3s",type);
286:   } else if (isbinary) {
287:     PetscInt    classid = SNES_FILE_CLASSID;
288:     MPI_Comm    comm;
289:     PetscMPIInt rank;
290:     char        type[256];

292:     PetscObjectGetComm((PetscObject)snes,&comm);
293:     MPI_Comm_rank(comm,&rank);
294:     if (!rank) {
295:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
296:       PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));
297:       PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR,PETSC_FALSE);
298:     }
299:     if (snes->ops->view) {
300:       (*snes->ops->view)(snes,viewer);
301:     }
302:   } else if (isdraw) {
303:     PetscDraw draw;
304:     char      str[36];
305:     PetscReal x,y,bottom,h;

307:     PetscViewerDrawGetDraw(viewer,0,&draw);
308:     PetscDrawGetCurrentPoint(draw,&x,&y);
309:     PetscStrcpy(str,"SNES: ");
310:     PetscStrcat(str,((PetscObject)snes)->type_name);
311:     PetscDrawBoxedString(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h);
312:     bottom = y - h;
313:     PetscDrawPushCurrentPoint(draw,x,bottom);
314:     if (snes->ops->view) {
315:       (*snes->ops->view)(snes,viewer);
316:     }
317: #if defined(PETSC_HAVE_SAWS)
318:   } else if (isams) {
319:     PetscMPIInt rank;
320:     const char *name;

322:     PetscObjectGetName((PetscObject)snes,&name);
323:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
324:     if (!((PetscObject)snes)->amsmem && !rank) {
325:       char       dir[1024];

327:       PetscObjectViewSAWs((PetscObject)snes,viewer);
328:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);
329:       PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
330:       if (!snes->conv_hist) {
331:         SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE);
332:       }
333:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name);
334:       PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
335:     }
336: #endif
337:   }
338:   if (snes->linesearch) {
339:     PetscViewerASCIIPushTab(viewer);
340:     SNESGetLineSearch(snes, &linesearch);
341:     SNESLineSearchView(linesearch, viewer);
342:     PetscViewerASCIIPopTab(viewer);
343:   }
344:   if (snes->pc && snes->usespc) {
345:     PetscViewerASCIIPushTab(viewer);
346:     SNESView(snes->pc, viewer);
347:     PetscViewerASCIIPopTab(viewer);
348:   }
349:   PetscViewerASCIIPushTab(viewer);
350:   DMGetDMSNES(snes->dm,&dmsnes);
351:   DMSNESView(dmsnes, viewer);
352:   PetscViewerASCIIPopTab(viewer);
353:   if (snes->usesksp) {
354:     SNESGetKSP(snes,&ksp);
355:     PetscViewerASCIIPushTab(viewer);
356:     KSPView(ksp,viewer);
357:     PetscViewerASCIIPopTab(viewer);
358:   }
359:   if (isdraw) {
360:     PetscDraw draw;
361:     PetscViewerDrawGetDraw(viewer,0,&draw);
362:     PetscDrawPopCurrentPoint(draw);
363:   }
364:   return(0);
365: }

367: /*
368:   We retain a list of functions that also take SNES command
369:   line options. These are called at the end SNESSetFromOptions()
370: */
371: #define MAXSETFROMOPTIONS 5
372: static PetscInt numberofsetfromoptions;
373: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);

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

380:   Not Collective

382:   Input Parameter:
383: . snescheck - function that checks for options

385:   Level: developer

387: .seealso: SNESSetFromOptions()
388: @*/
389: PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
390: {
392:   if (numberofsetfromoptions >= MAXSETFROMOPTIONS) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %D allowed", MAXSETFROMOPTIONS);
393:   othersetfromoptions[numberofsetfromoptions++] = snescheck;
394:   return(0);
395: }

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

401: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
402: {
403:   Mat            J;
404:   KSP            ksp;
405:   PC             pc;
406:   PetscBool      match;


412:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
413:     Mat A = snes->jacobian, B = snes->jacobian_pre;
414:     MatCreateVecs(A ? A : B, NULL,&snes->vec_func);
415:   }

417:   if (version == 1) {
418:     MatCreateSNESMF(snes,&J);
419:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
420:     MatSetFromOptions(J);
421:   } else if (version == 2) {
422:     if (!snes->vec_func) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
423: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128)
424:     SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J);
425: #else
426:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator rutines (version 2)");
427: #endif
428:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator rutines, only version 1 and 2");

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

433:     /* This version replaces the user provided Jacobian matrix with a
434:        matrix-free version but still employs the user-provided preconditioner matrix. */
435:     SNESSetJacobian(snes,J,0,0,0);
436:   } else {
437:     /* This version replaces both the user-provided Jacobian and the user-
438:      provided preconditioner Jacobian with the default matrix free version. */
439:     if ((snes->pcside == PC_LEFT) && snes->pc) {
440:       if (!snes->jacobian){SNESSetJacobian(snes,J,0,0,0);}
441:     } else {
442:       SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,0);
443:     }
444:     /* Force no preconditioner */
445:     SNESGetKSP(snes,&ksp);
446:     KSPGetPC(ksp,&pc);
447:     PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&match);
448:     if (!match) {
449:       PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n");
450:       PCSetType(pc,PCNONE);
451:     }
452:   }
453:   MatDestroy(&J);
454:   return(0);
455: }

459: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
460: {
461:   SNES           snes = (SNES)ctx;
463:   Vec            Xfine,Xfine_named = NULL,Xcoarse;

466:   if (PetscLogPrintInfo) {
467:     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
468:     DMGetRefineLevel(dmfine,&finelevel);
469:     DMGetCoarsenLevel(dmfine,&fineclevel);
470:     DMGetRefineLevel(dmcoarse,&coarselevel);
471:     DMGetCoarsenLevel(dmcoarse,&coarseclevel);
472:     PetscInfo4(dmfine,"Restricting SNES solution vector from level %D-%D to level %D-%D\n",finelevel,fineclevel,coarselevel,coarseclevel);
473:   }
474:   if (dmfine == snes->dm) Xfine = snes->vec_sol;
475:   else {
476:     DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);
477:     Xfine = Xfine_named;
478:   }
479:   DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
480:   MatRestrict(Restrict,Xfine,Xcoarse);
481:   VecPointwiseMult(Xcoarse,Xcoarse,Rscale);
482:   DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
483:   if (Xfine_named) {DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);}
484:   return(0);
485: }

489: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
490: {

494:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
495:   return(0);
496: }

500: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
501:  * safely call SNESGetDM() in their residual evaluation routine. */
502: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
503: {
504:   SNES           snes = (SNES)ctx;
506:   Mat            Asave = A,Bsave = B;
507:   Vec            X,Xnamed = NULL;
508:   DM             dmsave;
509:   void           *ctxsave;
510:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);

513:   dmsave = snes->dm;
514:   KSPGetDM(ksp,&snes->dm);
515:   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
516:   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
517:     DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
518:     X    = Xnamed;
519:     SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave);
520:     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
521:     if (jac == SNESComputeJacobianDefaultColor) {
522:       SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,0);
523:     }
524:   }
525:   /* put the previous context back */

527:   SNESComputeJacobian(snes,X,A,B);
528:   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
529:     SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);
530:   }

532:   if (A != Asave || B != Bsave) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_SUP,"No support for changing matrices at this time");
533:   if (Xnamed) {
534:     DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
535:   }
536:   snes->dm = dmsave;
537:   return(0);
538: }

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

545:    Collective

547:    Input Arguments:
548: .  snes - snes to configure

550:    Level: developer

552: .seealso: SNESSetUp()
553: @*/
554: PetscErrorCode SNESSetUpMatrices(SNES snes)
555: {
557:   DM             dm;
558:   DMSNES         sdm;

561:   SNESGetDM(snes,&dm);
562:   DMGetDMSNES(dm,&sdm);
563:   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_PLIB,"DMSNES not properly configured");
564:   else if (!snes->jacobian && snes->mf) {
565:     Mat  J;
566:     void *functx;
567:     MatCreateSNESMF(snes,&J);
568:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
569:     MatSetFromOptions(J);
570:     SNESGetFunction(snes,NULL,NULL,&functx);
571:     SNESSetJacobian(snes,J,J,0,0);
572:     MatDestroy(&J);
573:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
574:     Mat J,B;
575:     MatCreateSNESMF(snes,&J);
576:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
577:     MatSetFromOptions(J);
578:     DMCreateMatrix(snes->dm,&B);
579:     /* sdm->computejacobian was already set to reach here */
580:     SNESSetJacobian(snes,J,B,NULL,NULL);
581:     MatDestroy(&J);
582:     MatDestroy(&B);
583:   } else if (!snes->jacobian_pre) {
584:     Mat J,B;
585:     J    = snes->jacobian;
586:     DMCreateMatrix(snes->dm,&B);
587:     SNESSetJacobian(snes,J ? J : B,B,NULL,NULL);
588:     MatDestroy(&B);
589:   }
590:   {
591:     KSP ksp;
592:     SNESGetKSP(snes,&ksp);
593:     KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);
594:     DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
595:   }
596:   return(0);
597: }

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

604:    Collective on SNES

606:    Input Parameter:
607: .  snes - the SNES context

609:    Options Database Keys:
610: +  -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
611: .  -snes_stol - convergence tolerance in terms of the norm
612:                 of the change in the solution between steps
613: .  -snes_atol <abstol> - absolute tolerance of residual norm
614: .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
615: .  -snes_max_it <max_it> - maximum number of iterations
616: .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
617: .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
618: .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
619: .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
620: .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
621: .  -snes_trtol <trtol> - trust region tolerance
622: .  -snes_no_convergence_test - skip convergence test in nonlinear
623:                                solver; hence iterations will continue until max_it
624:                                or some other criterion is reached. Saves expense
625:                                of convergence test
626: .  -snes_monitor <optional filename> - prints residual norm at each iteration. if no
627:                                        filename given prints to stdout
628: .  -snes_monitor_solution - plots solution at each iteration
629: .  -snes_monitor_residual - plots residual (not its norm) at each iteration
630: .  -snes_monitor_solution_update - plots update to solution at each iteration
631: .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
632: .  -snes_monitor_lg_range - plots residual norm at each iteration
633: .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
634: .  -snes_fd_color - use finite differences with coloring to compute Jacobian
635: .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
636: -  -snes_converged_reason - print the reason for convergence/divergence after each solve

638:     Options Database for Eisenstat-Walker method:
639: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
640: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
641: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
642: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
643: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
644: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
645: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
646: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

648:    Notes:
649:    To see all options, run your program with the -help option or consult
650:    Users-Manual: ch_snes

652:    Level: beginner

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

656: .seealso: SNESSetOptionsPrefix()
657: @*/
658: PetscErrorCode  SNESSetFromOptions(SNES snes)
659: {
660:   PetscBool      flg,pcset,persist,set;
661:   PetscInt       i,indx,lag,grids;
662:   const char     *deft        = SNESNEWTONLS;
663:   const char     *convtests[] = {"default","skip"};
664:   SNESKSPEW      *kctx        = NULL;
665:   char           type[256], monfilename[PETSC_MAX_PATH_LEN];
666:   PetscViewer    monviewer;
668:   PCSide         pcside;
669:   const char     *optionsprefix;

673:   if (!SNESRegisterAllCalled) {SNESRegisterAll();}
674:   PetscObjectOptionsBegin((PetscObject)snes);
675:   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
676:   PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg);
677:   if (flg) {
678:     SNESSetType(snes,type);
679:   } else if (!((PetscObject)snes)->type_name) {
680:     SNESSetType(snes,deft);
681:   }
682:   PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL);
683:   PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL);

685:   PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL);
686:   PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL);
687:   PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL);
688:   PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL);
689:   PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL);
690:   PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL);

692:   PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg);
693:   if (flg) {
694:     SNESSetLagPreconditioner(snes,lag);
695:   }
696:   PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg);
697:   if (flg) {
698:     SNESSetLagPreconditionerPersists(snes,persist);
699:   }
700:   PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg);
701:   if (flg) {
702:     SNESSetLagJacobian(snes,lag);
703:   }
704:   PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg);
705:   if (flg) {
706:     SNESSetLagJacobianPersists(snes,persist);
707:   }

709:   PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg);
710:   if (flg) {
711:     SNESSetGridSequence(snes,grids);
712:   }

714:   PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,2,"default",&indx,&flg);
715:   if (flg) {
716:     switch (indx) {
717:     case 0: SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL); break;
718:     case 1: SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL);    break;
719:     }
720:   }

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

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

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

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

732:   PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL);
733:   PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL);
734:   PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL);
735:   PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL);
736:   PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL);
737:   PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL);
738:   PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL);

740:   flg  = PETSC_FALSE;
741:   PetscOptionsBool("-snes_check_jacobian","Check each Jacobian with a differenced one","SNESUpdateCheckJacobian",flg,&flg,&set);
742:   if (set && flg) {
743:     SNESSetUpdate(snes,SNESUpdateCheckJacobian);
744:   }

746:   flg  = PETSC_FALSE;
747:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
748:   if (set && flg) {SNESMonitorCancel(snes);}

750:   PetscOptionsString("-snes_monitor","Monitor norm of function","SNESMonitorSet","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);
751:   if (flg) {
752:     PetscViewerASCIIOpen(PetscObjectComm((PetscObject)snes),monfilename,&monviewer);
753:     SNESMonitorSet(snes,SNESMonitorDefault,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);
754:   }

756:   PetscOptionsString("-snes_monitor_range","Monitor range of elements of function","SNESMonitorSet","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);
757:   if (flg) {
758:     SNESMonitorSet(snes,SNESMonitorRange,0,0);
759:   }

761:   PetscOptionsString("-snes_ratiomonitor","Monitor ratios of norms of function","SNESMonitorSetRatio","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);
762:   if (flg) {
763:     PetscViewerASCIIOpen(PetscObjectComm((PetscObject)snes),monfilename,&monviewer);
764:     SNESMonitorSetRatio(snes,monviewer);
765:   }

767:   PetscOptionsString("-snes_monitor_short","Monitor norm of function (fewer digits)","SNESMonitorSet","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);
768:   if (flg) {
769:     PetscViewerASCIIOpen(PetscObjectComm((PetscObject)snes),monfilename,&monviewer);
770:     SNESMonitorSet(snes,SNESMonitorDefaultShort,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);
771:   }

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

776:   flg  = PETSC_FALSE;
777:   PetscOptionsBool("-snes_monitor_solution","Plot solution at each iteration","SNESMonitorSolution",flg,&flg,NULL);
778:   if (flg) {SNESMonitorSet(snes,SNESMonitorSolution,0,0);}
779:   flg  = PETSC_FALSE;
780:   PetscOptionsBool("-snes_monitor_solution_update","Plot correction at each iteration","SNESMonitorSolutionUpdate",flg,&flg,NULL);
781:   if (flg) {SNESMonitorSet(snes,SNESMonitorSolutionUpdate,0,0);}
782:   flg  = PETSC_FALSE;
783:   PetscOptionsBool("-snes_monitor_residual","Plot residual at each iteration","SNESMonitorResidual",flg,&flg,NULL);
784:   if (flg) {SNESMonitorSet(snes,SNESMonitorResidual,0,0);}
785:   flg  = PETSC_FALSE;
786:   PetscOptionsBool("-snes_monitor_lg_residualnorm","Plot function norm at each iteration","SNESMonitorLGResidualNorm",flg,&flg,NULL);
787:   if (flg) {
788:     PetscObject *objs;

790:     SNESMonitorLGCreate(0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,&objs);
791:     SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))SNESMonitorLGResidualNorm,objs,(PetscErrorCode (*)(void**))SNESMonitorLGDestroy);
792:   }
793:   flg  = PETSC_FALSE;
794:   PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);
795:   if (flg) {
796:     PetscViewer ctx;

798:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,&ctx);
799:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
800:   }

802:   flg  = PETSC_FALSE;
803:   PetscOptionsBool("-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",flg,&flg,NULL);
804:   if (flg) {SNESMonitorSet(snes,SNESMonitorJacUpdateSpectrum,0,0);}


807:   PetscOptionsString("-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);
808:   if (flg) {
809:     PetscViewerASCIIOpen(PetscObjectComm((PetscObject)snes),monfilename,&monviewer);
810:     SNESMonitorSet(snes,SNESMonitorFields,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);
811:   }

813:   flg  = PETSC_FALSE;
814:   PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);
815:   if (flg) {
816:     void *functx;
817:     SNESGetFunction(snes,NULL,NULL,&functx);
818:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);
819:     PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");
820:   }

822:   flg  = PETSC_FALSE;
823:   PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);
824:   if (flg) {
825:     SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);
826:   }

828:   flg  = PETSC_FALSE;
829:   PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL);
830:   if (flg) {
831:     DM             dm;
832:     DMSNES         sdm;
833:     SNESGetDM(snes,&dm);
834:     DMGetDMSNES(dm,&sdm);
835:     sdm->jacobianctx = NULL;
836:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,0);
837:     PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n");
838:   }

840:   flg  = PETSC_FALSE;
841:   PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","MatCreateSNESMF",PETSC_FALSE,&snes->mf_operator,&flg);
842:   if (flg && snes->mf_operator) {
843:     snes->mf_operator = PETSC_TRUE;
844:     snes->mf          = PETSC_TRUE;
845:   }
846:   flg  = PETSC_FALSE;
847:   PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","MatCreateSNESMF",PETSC_FALSE,&snes->mf,&flg);
848:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
849:   PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,0);

851:   flg  = PETSC_FALSE;
852:   SNESGetNPCSide(snes,&pcside);
853:   PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);
854:   if (flg) {SNESSetNPCSide(snes,pcside);}

856: #if defined(PETSC_HAVE_SAWS)
857:   /*
858:     Publish convergence information using SAWs
859:   */
860:   flg  = PETSC_FALSE;
861:   PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL);
862:   if (flg) {
863:     void *ctx;
864:     SNESMonitorSAWsCreate(snes,&ctx);
865:     SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy);
866:   }
867: #endif
868: #if defined(PETSC_HAVE_SAWS)
869:   {
870:   PetscBool set;
871:   flg  = PETSC_FALSE;
872:   PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set);
873:   if (set) {
874:     PetscObjectSAWsSetBlock((PetscObject)snes,flg);
875:   }
876:   }
877: #endif

879:   for (i = 0; i < numberofsetfromoptions; i++) {
880:     (*othersetfromoptions[i])(snes);
881:   }

883:   if (snes->ops->setfromoptions) {
884:     (*snes->ops->setfromoptions)(snes);
885:   }

887:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
888:   PetscObjectProcessOptionsHandlers((PetscObject)snes);
889:   PetscOptionsEnd();

891:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
892:   KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
893:   KSPSetFromOptions(snes->ksp);

895:   if (!snes->linesearch) {
896:     SNESGetLineSearch(snes, &snes->linesearch);
897:   }
898:   SNESLineSearchSetFromOptions(snes->linesearch);

900:   /* if someone has set the SNES NPC type, create it. */
901:   SNESGetOptionsPrefix(snes, &optionsprefix);
902:   PetscOptionsHasName(optionsprefix, "-npc_snes_type", &pcset);
903:   if (pcset && (!snes->pc)) {
904:     SNESGetNPC(snes, &snes->pc);
905:   }
906:   return(0);
907: }

911: /*@C
912:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
913:    the nonlinear solvers.

915:    Logically Collective on SNES

917:    Input Parameters:
918: +  snes - the SNES context
919: .  compute - function to compute the context
920: -  destroy - function to destroy the context

922:    Level: intermediate

924:    Notes:
925:    This function is currently not available from Fortran.

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

929: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
930: @*/
931: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
932: {
935:   snes->ops->usercompute = compute;
936:   snes->ops->userdestroy = destroy;
937:   return(0);
938: }

942: /*@
943:    SNESSetApplicationContext - Sets the optional user-defined context for
944:    the nonlinear solvers.

946:    Logically Collective on SNES

948:    Input Parameters:
949: +  snes - the SNES context
950: -  usrP - optional user context

952:    Level: intermediate

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

956: .seealso: SNESGetApplicationContext()
957: @*/
958: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
959: {
961:   KSP            ksp;

965:   SNESGetKSP(snes,&ksp);
966:   KSPSetApplicationContext(ksp,usrP);
967:   snes->user = usrP;
968:   return(0);
969: }

973: /*@
974:    SNESGetApplicationContext - Gets the user-defined context for the
975:    nonlinear solvers.

977:    Not Collective

979:    Input Parameter:
980: .  snes - SNES context

982:    Output Parameter:
983: .  usrP - user context

985:    Level: intermediate

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

989: .seealso: SNESSetApplicationContext()
990: @*/
991: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
992: {
995:   *(void**)usrP = snes->user;
996:   return(0);
997: }

1001: /*@
1002:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1003:    at this time.

1005:    Not Collective

1007:    Input Parameter:
1008: .  snes - SNES context

1010:    Output Parameter:
1011: .  iter - iteration number

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

1016:    This is useful for using lagged Jacobians (where one does not recompute the
1017:    Jacobian at each SNES iteration). For example, the code
1018: .vb
1019:       SNESGetIterationNumber(snes,&it);
1020:       if (!(it % 2)) {
1021:         [compute Jacobian here]
1022:       }
1023: .ve
1024:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1025:    recomputed every second SNES iteration.

1027:    Level: intermediate

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

1031: .seealso:   SNESGetLinearSolveIterations()
1032: @*/
1033: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1034: {
1038:   *iter = snes->iter;
1039:   return(0);
1040: }

1044: /*@
1045:    SNESSetIterationNumber - Sets the current iteration number.

1047:    Not Collective

1049:    Input Parameter:
1050: .  snes - SNES context
1051: .  iter - iteration number

1053:    Level: developer

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

1057: .seealso:   SNESGetLinearSolveIterations()
1058: @*/
1059: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1060: {

1065:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1066:   snes->iter = iter;
1067:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1068:   return(0);
1069: }

1073: /*@
1074:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1075:    attempted by the nonlinear solver.

1077:    Not Collective

1079:    Input Parameter:
1080: .  snes - SNES context

1082:    Output Parameter:
1083: .  nfails - number of unsuccessful steps attempted

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

1088:    Level: intermediate

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

1092: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1093:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1094: @*/
1095: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1096: {
1100:   *nfails = snes->numFailures;
1101:   return(0);
1102: }

1106: /*@
1107:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1108:    attempted by the nonlinear solver before it gives up.

1110:    Not Collective

1112:    Input Parameters:
1113: +  snes     - SNES context
1114: -  maxFails - maximum of unsuccessful steps

1116:    Level: intermediate

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

1120: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1121:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1122: @*/
1123: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1124: {
1127:   snes->maxFailures = maxFails;
1128:   return(0);
1129: }

1133: /*@
1134:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1135:    attempted by the nonlinear solver before it gives up.

1137:    Not Collective

1139:    Input Parameter:
1140: .  snes     - SNES context

1142:    Output Parameter:
1143: .  maxFails - maximum of unsuccessful steps

1145:    Level: intermediate

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

1149: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1150:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1152: @*/
1153: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1154: {
1158:   *maxFails = snes->maxFailures;
1159:   return(0);
1160: }

1164: /*@
1165:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1166:      done by SNES.

1168:    Not Collective

1170:    Input Parameter:
1171: .  snes     - SNES context

1173:    Output Parameter:
1174: .  nfuncs - number of evaluations

1176:    Level: intermediate

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

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

1182: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1183: @*/
1184: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1185: {
1189:   *nfuncs = snes->nfuncs;
1190:   return(0);
1191: }

1195: /*@
1196:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1197:    linear solvers.

1199:    Not Collective

1201:    Input Parameter:
1202: .  snes - SNES context

1204:    Output Parameter:
1205: .  nfails - number of failed solves

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

1210:    Level: intermediate

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

1214: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1215: @*/
1216: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1217: {
1221:   *nfails = snes->numLinearSolveFailures;
1222:   return(0);
1223: }

1227: /*@
1228:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1229:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1231:    Logically Collective on SNES

1233:    Input Parameters:
1234: +  snes     - SNES context
1235: -  maxFails - maximum allowed linear solve failures

1237:    Level: intermediate

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

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

1243: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1244: @*/
1245: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1246: {
1250:   snes->maxLinearSolveFailures = maxFails;
1251:   return(0);
1252: }

1256: /*@
1257:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1258:      are allowed before SNES terminates

1260:    Not Collective

1262:    Input Parameter:
1263: .  snes     - SNES context

1265:    Output Parameter:
1266: .  maxFails - maximum of unsuccessful solves allowed

1268:    Level: intermediate

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

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

1274: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1275: @*/
1276: PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1277: {
1281:   *maxFails = snes->maxLinearSolveFailures;
1282:   return(0);
1283: }

1287: /*@
1288:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1289:    used by the nonlinear solver.

1291:    Not Collective

1293:    Input Parameter:
1294: .  snes - SNES context

1296:    Output Parameter:
1297: .  lits - number of linear iterations

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

1302:    Level: intermediate

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

1306: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1307: @*/
1308: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1309: {
1313:   *lits = snes->linear_its;
1314:   return(0);
1315: }

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

1323:    Logically Collective on SNES

1325:    Input Parameter:
1326: +  snes - SNES context
1327: -  reset - whether to reset the counters or not

1329:    Notes:
1330:    This is automatically called with FALSE

1332:    Level: developer

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

1336: .seealso:  SNESGetNumberFunctionEvals(), SNESGetNumberLinearSolveIterations(), SNESGetNPC()
1337: @*/
1338: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1339: {
1343:   snes->counters_reset = reset;
1344:   return(0);
1345: }


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

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

1355:    Input Parameters:
1356: +  snes - the SNES context
1357: -  ksp - the KSP context

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

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

1366:    Level: developer

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

1370: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1371: @*/
1372: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1373: {

1380:   PetscObjectReference((PetscObject)ksp);
1381:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1382:   snes->ksp = ksp;
1383:   return(0);
1384: }

1386: /* -----------------------------------------------------------*/
1389: /*@
1390:    SNESCreate - Creates a nonlinear solver context.

1392:    Collective on MPI_Comm

1394:    Input Parameters:
1395: .  comm - MPI communicator

1397:    Output Parameter:
1398: .  outsnes - the new SNES context

1400:    Options Database Keys:
1401: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1402:                and no preconditioning matrix
1403: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1404:                products, and a user-provided preconditioning matrix
1405:                as set by SNESSetJacobian()
1406: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1408:    Level: beginner

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

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

1414: @*/
1415: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1416: {
1418:   SNES           snes;
1419:   SNESKSPEW      *kctx;

1423:   *outsnes = NULL;
1424:   SNESInitializePackage();

1426:   PetscHeaderCreate(snes,_p_SNES,struct _SNESOps,SNES_CLASSID,"SNES","Nonlinear solver","SNES",comm,SNESDestroy,SNESView);

1428:   snes->ops->converged    = SNESConvergedDefault;
1429:   snes->usesksp           = PETSC_TRUE;
1430:   snes->tolerancesset     = PETSC_FALSE;
1431:   snes->max_its           = 50;
1432:   snes->max_funcs         = 10000;
1433:   snes->norm              = 0.0;
1434:   snes->normschedule      = SNES_NORM_ALWAYS;
1435:   snes->functype          = SNES_FUNCTION_DEFAULT;
1436: #if defined(PETSC_USE_REAL_SINGLE)
1437:   snes->rtol              = 1.e-5;
1438: #else
1439:   snes->rtol              = 1.e-8;
1440: #endif
1441:   snes->ttol              = 0.0;
1442: #if defined(PETSC_USE_REAL_SINGLE)
1443:   snes->abstol            = 1.e-25;
1444: #else
1445:   snes->abstol            = 1.e-50;
1446: #endif
1447:   snes->stol              = 1.e-8;
1448: #if defined(PETSC_USE_REAL_SINGLE)
1449:   snes->deltatol          = 1.e-6;
1450: #else
1451:   snes->deltatol          = 1.e-12;
1452: #endif
1453:   snes->nfuncs            = 0;
1454:   snes->numFailures       = 0;
1455:   snes->maxFailures       = 1;
1456:   snes->linear_its        = 0;
1457:   snes->lagjacobian       = 1;
1458:   snes->jac_iter          = 0;
1459:   snes->lagjac_persist    = PETSC_FALSE;
1460:   snes->lagpreconditioner = 1;
1461:   snes->pre_iter          = 0;
1462:   snes->lagpre_persist    = PETSC_FALSE;
1463:   snes->numbermonitors    = 0;
1464:   snes->data              = 0;
1465:   snes->setupcalled       = PETSC_FALSE;
1466:   snes->ksp_ewconv        = PETSC_FALSE;
1467:   snes->nwork             = 0;
1468:   snes->work              = 0;
1469:   snes->nvwork            = 0;
1470:   snes->vwork             = 0;
1471:   snes->conv_hist_len     = 0;
1472:   snes->conv_hist_max     = 0;
1473:   snes->conv_hist         = NULL;
1474:   snes->conv_hist_its     = NULL;
1475:   snes->conv_hist_reset   = PETSC_TRUE;
1476:   snes->counters_reset    = PETSC_TRUE;
1477:   snes->vec_func_init_set = PETSC_FALSE;
1478:   snes->reason            = SNES_CONVERGED_ITERATING;
1479:   snes->pcside            = PC_RIGHT;

1481:   snes->mf          = PETSC_FALSE;
1482:   snes->mf_operator = PETSC_FALSE;
1483:   snes->mf_version  = 1;

1485:   snes->numLinearSolveFailures = 0;
1486:   snes->maxLinearSolveFailures = 1;

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

1491:   snes->kspconvctx  = (void*)kctx;
1492:   kctx->version     = 2;
1493:   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1494:                              this was too large for some test cases */
1495:   kctx->rtol_last   = 0.0;
1496:   kctx->rtol_max    = .9;
1497:   kctx->gamma       = 1.0;
1498:   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
1499:   kctx->alpha2      = kctx->alpha;
1500:   kctx->threshold   = .1;
1501:   kctx->lresid_last = 0.0;
1502:   kctx->norm_last   = 0.0;

1504:   *outsnes = snes;
1505:   return(0);
1506: }

1508: /*MC
1509:     SNESFunction - functional form used to convey the nonlinear function to be solved by SNES

1511:      Synopsis:
1512:      #include <petscsnes.h>
1513:      SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1515:      Input Parameters:
1516: +     snes - the SNES context
1517: .     x    - state at which to evaluate residual
1518: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1520:      Output Parameter:
1521: .     f  - vector to put residual (function value)

1523:    Level: intermediate

1525: .seealso:   SNESSetFunction(), SNESGetFunction()
1526: M*/

1530: /*@C
1531:    SNESSetFunction - Sets the function evaluation routine and function
1532:    vector for use by the SNES routines in solving systems of nonlinear
1533:    equations.

1535:    Logically Collective on SNES

1537:    Input Parameters:
1538: +  snes - the SNES context
1539: .  r - vector to store function value
1540: .  f - function evaluation routine; see SNESFunction for calling sequence details
1541: -  ctx - [optional] user-defined context for private data for the
1542:          function evaluation routine (may be NULL)

1544:    Notes:
1545:    The Newton-like methods typically solve linear systems of the form
1546: $      f'(x) x = -f(x),
1547:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1549:    Level: beginner

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

1553: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1554: @*/
1555: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1556: {
1558:   DM             dm;

1562:   if (r) {
1565:     PetscObjectReference((PetscObject)r);
1566:     VecDestroy(&snes->vec_func);

1568:     snes->vec_func = r;
1569:   }
1570:   SNESGetDM(snes,&dm);
1571:   DMSNESSetFunction(dm,f,ctx);
1572:   return(0);
1573: }


1578: /*@C
1579:    SNESSetInitialFunction - Sets the function vector to be used as the
1580:    function norm at the initialization of the method.  In some
1581:    instances, the user has precomputed the function before calling
1582:    SNESSolve.  This function allows one to avoid a redundant call
1583:    to SNESComputeFunction in that case.

1585:    Logically Collective on SNES

1587:    Input Parameters:
1588: +  snes - the SNES context
1589: -  f - vector to store function value

1591:    Notes:
1592:    This should not be modified during the solution procedure.

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

1596:    Level: developer

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

1600: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1601: @*/
1602: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1603: {
1605:   Vec            vec_func;

1611:   if (snes->pcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1612:     snes->vec_func_init_set = PETSC_FALSE;
1613:     return(0);
1614:   }
1615:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1616:   VecCopy(f, vec_func);

1618:   snes->vec_func_init_set = PETSC_TRUE;
1619:   return(0);
1620: }

1624: /*@
1625:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1626:    of the SNES method.

1628:    Logically Collective on SNES

1630:    Input Parameters:
1631: +  snes - the SNES context
1632: -  normschedule - the frequency of norm computation

1634:    Options Database Key:
1635: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1646:    Level: developer

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

1650: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1651: @*/
1652: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1653: {
1656:   snes->normschedule = normschedule;
1657:   return(0);
1658: }


1663: /*@
1664:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1665:    of the SNES method.

1667:    Logically Collective on SNES

1669:    Input Parameters:
1670: +  snes - the SNES context
1671: -  normschedule - the type of the norm used

1673:    Level: advanced

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

1677: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1678: @*/
1679: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1680: {
1683:   *normschedule = snes->normschedule;
1684:   return(0);
1685: }


1690: /*@C
1691:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1692:    of the SNES method.

1694:    Logically Collective on SNES

1696:    Input Parameters:
1697: +  snes - the SNES context
1698: -  normschedule - the frequency of norm computation

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

1709:    Level: developer

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

1713: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1714: @*/
1715: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1716: {
1719:   snes->functype = type;
1720:   return(0);
1721: }


1726: /*@C
1727:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1728:    of the SNES method.

1730:    Logically Collective on SNES

1732:    Input Parameters:
1733: +  snes - the SNES context
1734: -  normschedule - the type of the norm used

1736:    Level: advanced

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

1740: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1741: @*/
1742: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
1743: {
1746:   *type = snes->functype;
1747:   return(0);
1748: }

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

1753:      Synopsis:
1754:      #include <petscsnes.h>
1755: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1757: +  X   - solution vector
1758: .  B   - RHS vector
1759: -  ctx - optional user-defined Gauss-Seidel context

1761:    Level: intermediate

1763: .seealso:   SNESSetNGS(), SNESGetNGS()
1764: M*/

1768: /*@C
1769:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1770:    use with composed nonlinear solvers.

1772:    Input Parameters:
1773: +  snes   - the SNES context
1774: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
1775: -  ctx    - [optional] user-defined context for private data for the
1776:             smoother evaluation routine (may be NULL)

1778:    Notes:
1779:    The NGS routines are used by the composed nonlinear solver to generate
1780:     a problem appropriate update to the solution, particularly FAS.

1782:    Level: intermediate

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

1786: .seealso: SNESGetFunction(), SNESComputeNGS()
1787: @*/
1788: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1789: {
1791:   DM             dm;

1795:   SNESGetDM(snes,&dm);
1796:   DMSNESSetNGS(dm,f,ctx);
1797:   return(0);
1798: }

1802: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1803: {
1805:   DM             dm;
1806:   DMSNES         sdm;

1809:   SNESGetDM(snes,&dm);
1810:   DMGetDMSNES(dm,&sdm);
1811:   /*  A(x)*x - b(x) */
1812:   if (sdm->ops->computepfunction) {
1813:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
1814:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");

1816:   if (sdm->ops->computepjacobian) {
1817:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
1818:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard matrix.");
1819:   VecScale(f,-1.0);
1820:   MatMultAdd(snes->jacobian,x,f,f);
1821:   return(0);
1822: }

1826: PETSC_EXTERN PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
1827: {
1829:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
1830:   return(0);
1831: }

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

1838:    Logically Collective on SNES

1840:    Input Parameters:
1841: +  snes - the SNES context
1842: .  r - vector to store function value
1843: .  b - function evaluation routine
1844: .  Amat - matrix with which A(x) x - b(x) is to be computed
1845: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
1846: .  J  - function to compute matrix value
1847: -  ctx - [optional] user-defined context for private data for the
1848:          function evaluation routine (may be NULL)

1850:    Notes:
1851:     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
1852:     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.

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

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

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

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

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

1868:    Level: intermediate

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

1872: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard()
1873: @*/
1874: 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)
1875: {
1877:   DM             dm;

1881:   SNESGetDM(snes, &dm);
1882:   DMSNESSetPicard(dm,b,J,ctx);
1883:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
1884:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
1885:   return(0);
1886: }

1890: /*@C
1891:    SNESGetPicard - Returns the context for the Picard iteration

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

1895:    Input Parameter:
1896: .  snes - the SNES context

1898:    Output Parameter:
1899: +  r - the function (or NULL)
1900: .  f - the function (or NULL); see SNESFunction for calling sequence details
1901: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
1902: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
1903: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
1904: -  ctx - the function context (or NULL)

1906:    Level: advanced

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

1910: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
1911: @*/
1912: 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)
1913: {
1915:   DM             dm;

1919:   SNESGetFunction(snes,r,NULL,NULL);
1920:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
1921:   SNESGetDM(snes,&dm);
1922:   DMSNESGetPicard(dm,f,J,ctx);
1923:   return(0);
1924: }

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

1931:    Logically Collective on SNES

1933:    Input Parameters:
1934: +  snes - the SNES context
1935: .  func - function evaluation routine
1936: -  ctx - [optional] user-defined context for private data for the
1937:          function evaluation routine (may be NULL)

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

1942: .  f - function vector
1943: -  ctx - optional user-defined function context

1945:    Level: intermediate

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

1949: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
1950: @*/
1951: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
1952: {
1955:   if (func) snes->ops->computeinitialguess = func;
1956:   if (ctx)  snes->initialguessP            = ctx;
1957:   return(0);
1958: }

1960: /* --------------------------------------------------------------- */
1963: /*@C
1964:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
1965:    it assumes a zero right hand side.

1967:    Logically Collective on SNES

1969:    Input Parameter:
1970: .  snes - the SNES context

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

1975:    Level: intermediate

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

1979: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
1980: @*/
1981: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
1982: {
1986:   *rhs = snes->vec_rhs;
1987:   return(0);
1988: }

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

1995:    Collective on SNES

1997:    Input Parameters:
1998: +  snes - the SNES context
1999: -  x - input vector

2001:    Output Parameter:
2002: .  y - function vector, as set by SNESSetFunction()

2004:    Notes:
2005:    SNESComputeFunction() is typically used within nonlinear solvers
2006:    implementations, so most users would not generally call this routine
2007:    themselves.

2009:    Level: developer

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

2013: .seealso: SNESSetFunction(), SNESGetFunction()
2014: @*/
2015: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2016: {
2018:   DM             dm;
2019:   DMSNES         sdm;

2027:   VecValidValues(x,2,PETSC_TRUE);

2029:   SNESGetDM(snes,&dm);
2030:   DMGetDMSNES(dm,&sdm);
2031:   if (sdm->ops->computefunction) {
2032:     PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2033:     PetscStackPush("SNES user function");
2034:     (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);
2035:     PetscStackPop;
2036:     PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2037:   } else if (snes->vec_rhs) {
2038:     MatMult(snes->jacobian, x, y);
2039:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2040:   if (snes->vec_rhs) {
2041:     VecAXPY(y,-1.0,snes->vec_rhs);
2042:   }
2043:   snes->nfuncs++;
2044:   VecValidValues(y,3,PETSC_FALSE);
2045:   return(0);
2046: }

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

2053:    Collective on SNES

2055:    Input Parameters:
2056: +  snes - the SNES context
2057: .  x - input vector
2058: -  b - rhs vector

2060:    Output Parameter:
2061: .  x - new solution vector

2063:    Notes:
2064:    SNESComputeNGS() is typically used within composed nonlinear solver
2065:    implementations, so most users would not generally call this routine
2066:    themselves.

2068:    Level: developer

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

2072: .seealso: SNESSetNGS(), SNESComputeFunction()
2073: @*/
2074: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2075: {
2077:   DM             dm;
2078:   DMSNES         sdm;

2086:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2087:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2088:   SNESGetDM(snes,&dm);
2089:   DMGetDMSNES(dm,&sdm);
2090:   if (sdm->ops->computegs) {
2091:     PetscStackPush("SNES user NGS");
2092:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2093:     PetscStackPop;
2094:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2095:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2096:   VecValidValues(x,3,PETSC_FALSE);
2097:   return(0);
2098: }

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

2105:    Collective on SNES and Mat

2107:    Input Parameters:
2108: +  snes - the SNES context
2109: -  x - input vector

2111:    Output Parameters:
2112: +  A - Jacobian matrix
2113: -  B - optional preconditioning matrix

2115:   Options Database Keys:
2116: +    -snes_lag_preconditioner <lag>
2117: .    -snes_lag_jacobian <lag>
2118: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2119: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2120: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2121: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2122: .    -snes_compare_coloring - Compute the finite differece Jacobian using coloring and display norms of difference
2123: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2124: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2125: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2126: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2127: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2128: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2131:    Notes:
2132:    Most users should not need to explicitly call this routine, as it
2133:    is used internally within the nonlinear solvers.

2135:    Level: developer

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

2139: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2140: @*/
2141: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2142: {
2144:   PetscBool      flag;
2145:   DM             dm;
2146:   DMSNES         sdm;
2147:   KSP            ksp;

2153:   VecValidValues(X,2,PETSC_TRUE);
2154:   SNESGetDM(snes,&dm);
2155:   DMGetDMSNES(dm,&sdm);

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

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

2161:   if (snes->lagjacobian == -2) {
2162:     snes->lagjacobian = -1;

2164:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2165:   } else if (snes->lagjacobian == -1) {
2166:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2167:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2168:     if (flag) {
2169:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2170:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2171:     }
2172:     return(0);
2173:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2174:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2175:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2176:     if (flag) {
2177:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2178:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2179:     }
2180:     return(0);
2181:   }
2182:   if (snes->pc && snes->pcside == PC_LEFT) {
2183:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2184:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2185:       return(0);
2186:   }

2188:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);

2190:   PetscStackPush("SNES user Jacobian function");
2191:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2192:   PetscStackPop;

2194:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2196:   /* the next line ensures that snes->ksp exists */
2197:   SNESGetKSP(snes,&ksp);
2198:   if (snes->lagpreconditioner == -2) {
2199:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2200:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2201:     snes->lagpreconditioner = -1;
2202:   } else if (snes->lagpreconditioner == -1) {
2203:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2204:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2205:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2206:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2207:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2208:   } else {
2209:     PetscInfo(snes,"Rebuilding preconditioner\n");
2210:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2211:   }

2213:   /* make sure user returned a correct Jacobian and preconditioner */
2216:   {
2217:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2218:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_explicit",&flag,NULL);
2219:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",&flag_draw,NULL);
2220:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",&flag_contour,NULL);
2221:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_operator",&flag_operator,NULL);
2222:     if (flag || flag_draw || flag_contour) {
2223:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2224:       PetscViewer  vdraw,vstdout;
2225:       PetscBool    flg;
2226:       if (flag_operator) {
2227:         MatComputeExplicitOperator(A,&Bexp_mine);
2228:         Bexp = Bexp_mine;
2229:       } else {
2230:         /* See if the preconditioning matrix can be viewed and added directly */
2231:         PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2232:         if (flg) Bexp = B;
2233:         else {
2234:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2235:           MatComputeExplicitOperator(B,&Bexp_mine);
2236:           Bexp = Bexp_mine;
2237:         }
2238:       }
2239:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2240:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2241:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2242:       if (flag_draw || flag_contour) {
2243:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2244:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2245:       } else vdraw = NULL;
2246:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2247:       if (flag) {MatView(Bexp,vstdout);}
2248:       if (vdraw) {MatView(Bexp,vdraw);}
2249:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2250:       if (flag) {MatView(FDexp,vstdout);}
2251:       if (vdraw) {MatView(FDexp,vdraw);}
2252:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2253:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2254:       if (flag) {MatView(FDexp,vstdout);}
2255:       if (vdraw) {              /* Always use contour for the difference */
2256:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2257:         MatView(FDexp,vdraw);
2258:         PetscViewerPopFormat(vdraw);
2259:       }
2260:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2261:       PetscViewerDestroy(&vdraw);
2262:       MatDestroy(&Bexp_mine);
2263:       MatDestroy(&FDexp);
2264:     }
2265:   }
2266:   {
2267:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2268:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2269:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_coloring",&flag,NULL);
2270:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_coloring_display",&flag_display,NULL);
2271:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",&flag_draw,NULL);
2272:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",&flag_contour,NULL);
2273:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",&flag_threshold,NULL);
2274:     PetscOptionsGetReal(((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2275:     PetscOptionsGetReal(((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2276:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2277:       Mat            Bfd;
2278:       PetscViewer    vdraw,vstdout;
2279:       MatColoring    coloring;
2280:       ISColoring     iscoloring;
2281:       MatFDColoring  matfdcoloring;
2282:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2283:       void           *funcctx;
2284:       PetscReal      norm1,norm2,normmax;

2286:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2287:       MatColoringCreate(Bfd,&coloring);
2288:       MatColoringSetType(coloring,MATCOLORINGSL);
2289:       MatColoringSetFromOptions(coloring);
2290:       MatColoringApply(coloring,&iscoloring);
2291:       MatColoringDestroy(&coloring);
2292:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2293:       MatFDColoringSetFromOptions(matfdcoloring);
2294:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2295:       ISColoringDestroy(&iscoloring);

2297:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2298:       SNESGetFunction(snes,NULL,&func,&funcctx);
2299:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2300:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2301:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2302:       MatFDColoringSetFromOptions(matfdcoloring);
2303:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2304:       MatFDColoringDestroy(&matfdcoloring);

2306:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2307:       if (flag_draw || flag_contour) {
2308:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2309:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2310:       } else vdraw = NULL;
2311:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2312:       if (flag_display) {MatView(B,vstdout);}
2313:       if (vdraw) {MatView(B,vdraw);}
2314:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2315:       if (flag_display) {MatView(Bfd,vstdout);}
2316:       if (vdraw) {MatView(Bfd,vdraw);}
2317:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2318:       MatNorm(Bfd,NORM_1,&norm1);
2319:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2320:       MatNorm(Bfd,NORM_MAX,&normmax);
2321:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2322:       if (flag_display) {MatView(Bfd,vstdout);}
2323:       if (vdraw) {              /* Always use contour for the difference */
2324:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2325:         MatView(Bfd,vdraw);
2326:         PetscViewerPopFormat(vdraw);
2327:       }
2328:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2330:       if (flag_threshold) {
2331:         PetscInt bs,rstart,rend,i;
2332:         MatGetBlockSize(B,&bs);
2333:         MatGetOwnershipRange(B,&rstart,&rend);
2334:         for (i=rstart; i<rend; i++) {
2335:           const PetscScalar *ba,*ca;
2336:           const PetscInt    *bj,*cj;
2337:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2338:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2339:           MatGetRow(B,i,&bn,&bj,&ba);
2340:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2341:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2342:           for (j=0; j<bn; j++) {
2343:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2344:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2345:               maxentrycol = bj[j];
2346:               maxentry    = PetscRealPart(ba[j]);
2347:             }
2348:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2349:               maxdiffcol = bj[j];
2350:               maxdiff    = PetscRealPart(ca[j]);
2351:             }
2352:             if (rdiff > maxrdiff) {
2353:               maxrdiffcol = bj[j];
2354:               maxrdiff    = rdiff;
2355:             }
2356:           }
2357:           if (maxrdiff > 1) {
2358:             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);
2359:             for (j=0; j<bn; j++) {
2360:               PetscReal rdiff;
2361:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2362:               if (rdiff > 1) {
2363:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2364:               }
2365:             }
2366:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2367:           }
2368:           MatRestoreRow(B,i,&bn,&bj,&ba);
2369:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2370:         }
2371:       }
2372:       PetscViewerDestroy(&vdraw);
2373:       MatDestroy(&Bfd);
2374:     }
2375:   }
2376:   return(0);
2377: }

2379: /*MC
2380:     SNESJacobianFunction - function used to convey the nonlinear Jacobian of the function to be solved by SNES

2382:      Synopsis:
2383:      #include <petscsnes.h>
2384: $     SNESJacobianFunction(SNES snes,Vec x,Mat Amat,Mat Pmat,void *ctx);

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

2391:    Level: intermediate

2393: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2394: M*/

2398: /*@C
2399:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2400:    location to store the matrix.

2402:    Logically Collective on SNES and Mat

2404:    Input Parameters:
2405: +  snes - the SNES context
2406: .  Amat - the matrix that defines the (approximate) Jacobian
2407: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2408: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value)
2409: -  ctx - [optional] user-defined context for private data for the
2410:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2412:    Notes:
2413:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2414:    each matrix.

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

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

2422:    Level: beginner

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

2426: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J, SNESSetPicard()
2427: @*/
2428: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2429: {
2431:   DM             dm;

2439:   SNESGetDM(snes,&dm);
2440:   DMSNESSetJacobian(dm,J,ctx);
2441:   if (Amat) {
2442:     PetscObjectReference((PetscObject)Amat);
2443:     MatDestroy(&snes->jacobian);

2445:     snes->jacobian = Amat;
2446:   }
2447:   if (Pmat) {
2448:     PetscObjectReference((PetscObject)Pmat);
2449:     MatDestroy(&snes->jacobian_pre);

2451:     snes->jacobian_pre = Pmat;
2452:   }
2453:   return(0);
2454: }

2458: /*@C
2459:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2460:    provided context for evaluating the Jacobian.

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

2464:    Input Parameter:
2465: .  snes - the nonlinear solver context

2467:    Output Parameters:
2468: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2469: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2470: .  J - location to put Jacobian function (or NULL)
2471: -  ctx - location to stash Jacobian ctx (or NULL)

2473:    Level: advanced

2475: .seealso: SNESSetJacobian(), SNESComputeJacobian()
2476: @*/
2477: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2478: {
2480:   DM             dm;
2481:   DMSNES         sdm;

2485:   if (Amat) *Amat = snes->jacobian;
2486:   if (Pmat) *Pmat = snes->jacobian_pre;
2487:   SNESGetDM(snes,&dm);
2488:   DMGetDMSNES(dm,&sdm);
2489:   if (J) *J = sdm->ops->computejacobian;
2490:   if (ctx) *ctx = sdm->jacobianctx;
2491:   return(0);
2492: }

2496: /*@
2497:    SNESSetUp - Sets up the internal data structures for the later use
2498:    of a nonlinear solver.

2500:    Collective on SNES

2502:    Input Parameters:
2503: .  snes - the SNES context

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

2512:    Level: advanced

2514: .keywords: SNES, nonlinear, setup

2516: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2517: @*/
2518: PetscErrorCode  SNESSetUp(SNES snes)
2519: {
2521:   DM             dm;
2522:   DMSNES         sdm;
2523:   SNESLineSearch linesearch, pclinesearch;
2524:   void           *lsprectx,*lspostctx;
2525:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2526:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2527:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2528:   Vec            f,fpc;
2529:   void           *funcctx;
2530:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2531:   void           *jacctx,*appctx;
2532:   Mat            j,jpre;

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

2538:   if (!((PetscObject)snes)->type_name) {
2539:     SNESSetType(snes,SNESNEWTONLS);
2540:   }

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

2544:   SNESGetDM(snes,&dm);
2545:   DMGetDMSNES(dm,&sdm);
2546:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2547:   if (!sdm->ops->computejacobian) {
2548:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2549:   }
2550:   if (!snes->vec_func) {
2551:     DMCreateGlobalVector(dm,&snes->vec_func);
2552:   }

2554:   if (!snes->ksp) {
2555:     SNESGetKSP(snes, &snes->ksp);
2556:   }

2558:   if (!snes->linesearch) {
2559:     SNESGetLineSearch(snes, &snes->linesearch);
2560:   }
2561:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2563:   if (snes->pc && (snes->pcside == PC_LEFT)) {
2564:     snes->mf          = PETSC_TRUE;
2565:     snes->mf_operator = PETSC_FALSE;
2566:   }

2568:   if (snes->pc) {
2569:     /* copy the DM over */
2570:     SNESGetDM(snes,&dm);
2571:     SNESSetDM(snes->pc,dm);

2573:     SNESGetFunction(snes,&f,&func,&funcctx);
2574:     VecDuplicate(f,&fpc);
2575:     SNESSetFunction(snes->pc,fpc,func,funcctx);
2576:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2577:     SNESSetJacobian(snes->pc,j,jpre,jac,jacctx);
2578:     SNESGetApplicationContext(snes,&appctx);
2579:     SNESSetApplicationContext(snes->pc,appctx);
2580:     VecDestroy(&fpc);

2582:     /* copy the function pointers over */
2583:     PetscObjectCopyFortranFunctionPointers((PetscObject)snes,(PetscObject)snes->pc);

2585:     /* default to 1 iteration */
2586:     SNESSetTolerances(snes->pc,0.0,0.0,0.0,1,snes->pc->max_funcs);
2587:     if (snes->pcside==PC_RIGHT) {
2588:       SNESSetNormSchedule(snes->pc,SNES_NORM_FINAL_ONLY);
2589:     } else {
2590:       SNESSetNormSchedule(snes->pc,SNES_NORM_NONE);
2591:     }
2592:     SNESSetFromOptions(snes->pc);

2594:     /* copy the line search context over */
2595:     SNESGetLineSearch(snes,&linesearch);
2596:     SNESGetLineSearch(snes->pc,&pclinesearch);
2597:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2598:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2599:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2600:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2601:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2602:   }
2603:   if (snes->mf) {
2604:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2605:   }
2606:   if (snes->ops->usercompute && !snes->user) {
2607:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2608:   }

2610:   snes->jac_iter = 0;
2611:   snes->pre_iter = 0;

2613:   if (snes->ops->setup) {
2614:     (*snes->ops->setup)(snes);
2615:   }

2617:   if (snes->pc && (snes->pcside == PC_LEFT)) {
2618:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2619:       SNESGetLineSearch(snes,&linesearch);
2620:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2621:     }
2622:   }

2624:   snes->setupcalled = PETSC_TRUE;
2625:   return(0);
2626: }

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

2633:    Collective on SNES

2635:    Input Parameter:
2636: .  snes - iterative context obtained from SNESCreate()

2638:    Level: intermediate

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

2642: .keywords: SNES, destroy

2644: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
2645: @*/
2646: PetscErrorCode  SNESReset(SNES snes)
2647: {

2652:   if (snes->ops->userdestroy && snes->user) {
2653:     (*snes->ops->userdestroy)((void**)&snes->user);
2654:     snes->user = NULL;
2655:   }
2656:   if (snes->pc) {
2657:     SNESReset(snes->pc);
2658:   }

2660:   if (snes->ops->reset) {
2661:     (*snes->ops->reset)(snes);
2662:   }
2663:   if (snes->ksp) {
2664:     KSPReset(snes->ksp);
2665:   }

2667:   if (snes->linesearch) {
2668:     SNESLineSearchReset(snes->linesearch);
2669:   }

2671:   VecDestroy(&snes->vec_rhs);
2672:   VecDestroy(&snes->vec_sol);
2673:   VecDestroy(&snes->vec_sol_update);
2674:   VecDestroy(&snes->vec_func);
2675:   MatDestroy(&snes->jacobian);
2676:   MatDestroy(&snes->jacobian_pre);
2677:   VecDestroyVecs(snes->nwork,&snes->work);
2678:   VecDestroyVecs(snes->nvwork,&snes->vwork);

2680:   snes->nwork       = snes->nvwork = 0;
2681:   snes->setupcalled = PETSC_FALSE;
2682:   return(0);
2683: }

2687: /*@
2688:    SNESDestroy - Destroys the nonlinear solver context that was created
2689:    with SNESCreate().

2691:    Collective on SNES

2693:    Input Parameter:
2694: .  snes - the SNES context

2696:    Level: beginner

2698: .keywords: SNES, nonlinear, destroy

2700: .seealso: SNESCreate(), SNESSolve()
2701: @*/
2702: PetscErrorCode  SNESDestroy(SNES *snes)
2703: {

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

2711:   SNESReset((*snes));
2712:   SNESDestroy(&(*snes)->pc);

2714:   /* if memory was published with SAWs then destroy it */
2715:   PetscObjectSAWsViewOff((PetscObject)*snes);
2716:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

2718:   DMDestroy(&(*snes)->dm);
2719:   KSPDestroy(&(*snes)->ksp);
2720:   SNESLineSearchDestroy(&(*snes)->linesearch);

2722:   PetscFree((*snes)->kspconvctx);
2723:   if ((*snes)->ops->convergeddestroy) {
2724:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
2725:   }
2726:   if ((*snes)->conv_malloc) {
2727:     PetscFree((*snes)->conv_hist);
2728:     PetscFree((*snes)->conv_hist_its);
2729:   }
2730:   SNESMonitorCancel((*snes));
2731:   PetscHeaderDestroy(snes);
2732:   return(0);
2733: }

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

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

2742:    Logically Collective on SNES

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

2749:    Options Database Keys:
2750: .    -snes_lag_preconditioner <lag>

2752:    Notes:
2753:    The default is 1
2754:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
2755:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

2757:    Level: intermediate

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

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

2763: @*/
2764: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
2765: {
2768:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
2769:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
2771:   snes->lagpreconditioner = lag;
2772:   return(0);
2773: }

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

2780:    Logically Collective on SNES

2782:    Input Parameters:
2783: +  snes - the SNES context
2784: -  steps - the number of refinements to do, defaults to 0

2786:    Options Database Keys:
2787: .    -snes_grid_sequence <steps>

2789:    Level: intermediate

2791:    Notes:
2792:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2798: @*/
2799: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
2800: {
2804:   snes->gridsequence = steps;
2805:   return(0);
2806: }

2810: /*@
2811:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

2813:    Not Collective

2815:    Input Parameter:
2816: .  snes - the SNES context

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

2822:    Options Database Keys:
2823: .    -snes_lag_preconditioner <lag>

2825:    Notes:
2826:    The default is 1
2827:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

2829:    Level: intermediate

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

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

2835: @*/
2836: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
2837: {
2840:   *lag = snes->lagpreconditioner;
2841:   return(0);
2842: }

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

2850:    Logically Collective on SNES

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

2857:    Options Database Keys:
2858: .    -snes_lag_jacobian <lag>

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

2866:    Level: intermediate

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

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

2872: @*/
2873: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
2874: {
2877:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
2878:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
2880:   snes->lagjacobian = lag;
2881:   return(0);
2882: }

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

2889:    Not Collective

2891:    Input Parameter:
2892: .  snes - the SNES context

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

2898:    Options Database Keys:
2899: .    -snes_lag_jacobian <lag>

2901:    Notes:
2902:    The default is 1
2903:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

2905:    Level: intermediate

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

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

2911: @*/
2912: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
2913: {
2916:   *lag = snes->lagjacobian;
2917:   return(0);
2918: }

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

2925:    Logically collective on SNES

2927:    Input Parameter:
2928: +  snes - the SNES context
2929: -   flg - jacobian lagging persists if true

2931:    Options Database Keys:
2932: .    -snes_lag_jacobian_persists <flg>

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

2938:    Level: developer

2940: .keywords: SNES, nonlinear, lag

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

2944: @*/
2945: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
2946: {
2950:   snes->lagjac_persist = flg;
2951:   return(0);
2952: }

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

2959:    Logically Collective on SNES

2961:    Input Parameter:
2962: +  snes - the SNES context
2963: -   flg - preconditioner lagging persists if true

2965:    Options Database Keys:
2966: .    -snes_lag_jacobian_persists <flg>

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

2972:    Level: developer

2974: .keywords: SNES, nonlinear, lag

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

2978: @*/
2979: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
2980: {
2984:   snes->lagpre_persist = flg;
2985:   return(0);
2986: }

2990: /*@
2991:    SNESSetTolerances - Sets various parameters used in convergence tests.

2993:    Logically Collective on SNES

2995:    Input Parameters:
2996: +  snes - the SNES context
2997: .  abstol - absolute convergence tolerance
2998: .  rtol - relative convergence tolerance
2999: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3000: .  maxit - maximum number of iterations
3001: -  maxf - maximum number of function evaluations

3003:    Options Database Keys:
3004: +    -snes_atol <abstol> - Sets abstol
3005: .    -snes_rtol <rtol> - Sets rtol
3006: .    -snes_stol <stol> - Sets stol
3007: .    -snes_max_it <maxit> - Sets maxit
3008: -    -snes_max_funcs <maxf> - Sets maxf

3010:    Notes:
3011:    The default maximum number of iterations is 50.
3012:    The default maximum number of function evaluations is 1000.

3014:    Level: intermediate

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

3018: .seealso: SNESSetTrustRegionTolerance()
3019: @*/
3020: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3021: {

3030:   if (abstol != PETSC_DEFAULT) {
3031:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3032:     snes->abstol = abstol;
3033:   }
3034:   if (rtol != PETSC_DEFAULT) {
3035:     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);
3036:     snes->rtol = rtol;
3037:   }
3038:   if (stol != PETSC_DEFAULT) {
3039:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3040:     snes->stol = stol;
3041:   }
3042:   if (maxit != PETSC_DEFAULT) {
3043:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3044:     snes->max_its = maxit;
3045:   }
3046:   if (maxf != PETSC_DEFAULT) {
3047:     if (maxf < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be non-negative",maxf);
3048:     snes->max_funcs = maxf;
3049:   }
3050:   snes->tolerancesset = PETSC_TRUE;
3051:   return(0);
3052: }

3056: /*@
3057:    SNESGetTolerances - Gets various parameters used in convergence tests.

3059:    Not Collective

3061:    Input Parameters:
3062: +  snes - the SNES context
3063: .  atol - absolute convergence tolerance
3064: .  rtol - relative convergence tolerance
3065: .  stol -  convergence tolerance in terms of the norm
3066:            of the change in the solution between steps
3067: .  maxit - maximum number of iterations
3068: -  maxf - maximum number of function evaluations

3070:    Notes:
3071:    The user can specify NULL for any parameter that is not needed.

3073:    Level: intermediate

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

3077: .seealso: SNESSetTolerances()
3078: @*/
3079: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3080: {
3083:   if (atol)  *atol  = snes->abstol;
3084:   if (rtol)  *rtol  = snes->rtol;
3085:   if (stol)  *stol  = snes->stol;
3086:   if (maxit) *maxit = snes->max_its;
3087:   if (maxf)  *maxf  = snes->max_funcs;
3088:   return(0);
3089: }

3093: /*@
3094:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3096:    Logically Collective on SNES

3098:    Input Parameters:
3099: +  snes - the SNES context
3100: -  tol - tolerance

3102:    Options Database Key:
3103: .  -snes_trtol <tol> - Sets tol

3105:    Level: intermediate

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

3109: .seealso: SNESSetTolerances()
3110: @*/
3111: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3112: {
3116:   snes->deltatol = tol;
3117:   return(0);
3118: }

3120: /*
3121:    Duplicate the lg monitors for SNES from KSP; for some reason with
3122:    dynamic libraries things don't work under Sun4 if we just use
3123:    macros instead of functions
3124: */
3127: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,PetscObject *objs)
3128: {

3133:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,objs);
3134:   return(0);
3135: }

3139: PetscErrorCode  SNESMonitorLGCreate(const char host[],const char label[],int x,int y,int m,int n,PetscObject **draw)
3140: {

3144:   KSPMonitorLGResidualNormCreate(host,label,x,y,m,n,draw);
3145:   return(0);
3146: }

3150: PetscErrorCode  SNESMonitorLGDestroy(PetscObject **objs)
3151: {

3155:   KSPMonitorLGResidualNormDestroy(objs);
3156:   return(0);
3157: }

3159: extern PetscErrorCode  SNESMonitorRange_Private(SNES,PetscInt,PetscReal*);
3162: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3163: {
3164:   PetscDrawLG      lg;
3165:   PetscErrorCode   ierr;
3166:   PetscReal        x,y,per;
3167:   PetscViewer      v = (PetscViewer)monctx;
3168:   static PetscReal prev; /* should be in the context */
3169:   PetscDraw        draw;

3172:   PetscViewerDrawGetDrawLG(v,0,&lg);
3173:   if (!n) {PetscDrawLGReset(lg);}
3174:   PetscDrawLGGetDraw(lg,&draw);
3175:   PetscDrawSetTitle(draw,"Residual norm");
3176:   x    = (PetscReal)n;
3177:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3178:   else y = -15.0;
3179:   PetscDrawLGAddPoint(lg,&x,&y);
3180:   if (n < 20 || !(n % 5)) {
3181:     PetscDrawLGDraw(lg);
3182:   }

3184:   PetscViewerDrawGetDrawLG(v,1,&lg);
3185:   if (!n) {PetscDrawLGReset(lg);}
3186:   PetscDrawLGGetDraw(lg,&draw);
3187:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3188:    SNESMonitorRange_Private(snes,n,&per);
3189:   x    = (PetscReal)n;
3190:   y    = 100.0*per;
3191:   PetscDrawLGAddPoint(lg,&x,&y);
3192:   if (n < 20 || !(n % 5)) {
3193:     PetscDrawLGDraw(lg);
3194:   }

3196:   PetscViewerDrawGetDrawLG(v,2,&lg);
3197:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3198:   PetscDrawLGGetDraw(lg,&draw);
3199:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3200:   x    = (PetscReal)n;
3201:   y    = (prev - rnorm)/prev;
3202:   PetscDrawLGAddPoint(lg,&x,&y);
3203:   if (n < 20 || !(n % 5)) {
3204:     PetscDrawLGDraw(lg);
3205:   }

3207:   PetscViewerDrawGetDrawLG(v,3,&lg);
3208:   if (!n) {PetscDrawLGReset(lg);}
3209:   PetscDrawLGGetDraw(lg,&draw);
3210:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3211:   x    = (PetscReal)n;
3212:   y    = (prev - rnorm)/(prev*per);
3213:   if (n > 2) { /*skip initial crazy value */
3214:     PetscDrawLGAddPoint(lg,&x,&y);
3215:   }
3216:   if (n < 20 || !(n % 5)) {
3217:     PetscDrawLGDraw(lg);
3218:   }
3219:   prev = rnorm;
3220:   return(0);
3221: }

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

3228:    Collective on SNES

3230:    Input Parameters:
3231: +  snes - nonlinear solver context obtained from SNESCreate()
3232: .  iter - iteration number
3233: -  rnorm - relative norm of the residual

3235:    Notes:
3236:    This routine is called by the SNES implementations.
3237:    It does not typically need to be called by the user.

3239:    Level: developer

3241: .seealso: SNESMonitorSet()
3242: @*/
3243: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3244: {
3246:   PetscInt       i,n = snes->numbermonitors;

3249:   for (i=0; i<n; i++) {
3250:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3251:   }
3252:   return(0);
3253: }

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

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

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

3264: +    snes - the SNES context
3265: .    its - iteration number
3266: .    norm - 2-norm function value (may be estimated)
3267: -    mctx - [optional] monitoring context

3269:    Level: advanced

3271: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3272: M*/

3276: /*@C
3277:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3278:    iteration of the nonlinear solver to display the iteration's
3279:    progress.

3281:    Logically Collective on SNES

3283:    Input Parameters:
3284: +  snes - the SNES context
3285: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3286: .  mctx - [optional] user-defined context for private data for the
3287:           monitor routine (use NULL if no context is desired)
3288: -  monitordestroy - [optional] routine that frees monitor context
3289:           (may be NULL)

3291:    Options Database Keys:
3292: +    -snes_monitor        - sets SNESMonitorDefault()
3293: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3294:                             uses SNESMonitorLGCreate()
3295: -    -snes_monitor_cancel - cancels all monitors that have
3296:                             been hardwired into a code by
3297:                             calls to SNESMonitorSet(), but
3298:                             does not cancel those set via
3299:                             the options database.

3301:    Notes:
3302:    Several different monitoring routines may be set by calling
3303:    SNESMonitorSet() multiple times; all will be called in the
3304:    order in which they were set.

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

3308:    Level: intermediate

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

3312: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3313: @*/
3314: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3315: {
3316:   PetscInt       i;

3321:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3322:   for (i=0; i<snes->numbermonitors;i++) {
3323:     if (f == snes->monitor[i] && monitordestroy == snes->monitordestroy[i] && mctx == snes->monitorcontext[i]) {
3324:       if (monitordestroy) {
3325:         (*monitordestroy)(&mctx);
3326:       }
3327:       return(0);
3328:     }
3329:   }
3330:   snes->monitor[snes->numbermonitors]          = f;
3331:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3332:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3333:   return(0);
3334: }

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

3341:    Logically Collective on SNES

3343:    Input Parameters:
3344: .  snes - the SNES context

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

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

3354:    Level: intermediate

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

3358: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3359: @*/
3360: PetscErrorCode  SNESMonitorCancel(SNES snes)
3361: {
3363:   PetscInt       i;

3367:   for (i=0; i<snes->numbermonitors; i++) {
3368:     if (snes->monitordestroy[i]) {
3369:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3370:     }
3371:   }
3372:   snes->numbermonitors = 0;
3373:   return(0);
3374: }

3376: /*MC
3377:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3383: +    snes - the SNES context
3384: .    it - current iteration (0 is the first and is before any Newton step)
3385: .    cctx - [optional] convergence context
3386: .    reason - reason for convergence/divergence
3387: .    xnorm - 2-norm of current iterate
3388: .    gnorm - 2-norm of current step
3389: -    f - 2-norm of function

3391:    Level: intermediate

3393: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3394: M*/

3398: /*@C
3399:    SNESSetConvergenceTest - Sets the function that is to be used
3400:    to test for convergence of the nonlinear iterative solution.

3402:    Logically Collective on SNES

3404:    Input Parameters:
3405: +  snes - the SNES context
3406: .  SNESConvergenceTestFunction - routine to test for convergence
3407: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3408: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3410:    Level: advanced

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

3414: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3415: @*/
3416: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3417: {

3422:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3423:   if (snes->ops->convergeddestroy) {
3424:     (*snes->ops->convergeddestroy)(snes->cnvP);
3425:   }
3426:   snes->ops->converged        = SNESConvergenceTestFunction;
3427:   snes->ops->convergeddestroy = destroy;
3428:   snes->cnvP                  = cctx;
3429:   return(0);
3430: }

3434: /*@
3435:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3437:    Not Collective

3439:    Input Parameter:
3440: .  snes - the SNES context

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

3446:    Level: intermediate

3448:    Notes: Can only be called after the call the SNESSolve() is complete.

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

3452: .seealso: SNESSetConvergenceTest(), SNESConvergedReason
3453: @*/
3454: PetscErrorCode  SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3455: {
3459:   *reason = snes->reason;
3460:   return(0);
3461: }

3465: /*@
3466:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3468:    Logically Collective on SNES

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

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

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

3486:    Level: intermediate

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

3490: .seealso: SNESGetConvergenceHistory()

3492: @*/
3493: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3494: {

3501:   if (!a) {
3502:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3503:     PetscCalloc1(na,&a);
3504:     PetscCalloc1(na,&its);

3506:     snes->conv_malloc = PETSC_TRUE;
3507:   }
3508:   snes->conv_hist       = a;
3509:   snes->conv_hist_its   = its;
3510:   snes->conv_hist_max   = na;
3511:   snes->conv_hist_len   = 0;
3512:   snes->conv_hist_reset = reset;
3513:   return(0);
3514: }

3516: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3517: #include <engine.h>   /* MATLAB include file */
3518: #include <mex.h>      /* MATLAB include file */

3522: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3523: {
3524:   mxArray   *mat;
3525:   PetscInt  i;
3526:   PetscReal *ar;

3529:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3530:   ar  = (PetscReal*) mxGetData(mat);
3531:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3532:   PetscFunctionReturn(mat);
3533: }
3534: #endif

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

3541:    Not Collective

3543:    Input Parameter:
3544: .  snes - iterative context obtained from SNESCreate()

3546:    Output Parameters:
3547: .  a   - array to hold history
3548: .  its - integer array holds the number of linear iterations (or
3549:          negative if not converged) for each solve.
3550: -  na  - size of a and its

3552:    Notes:
3553:     The calling sequence for this routine in Fortran is
3554: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

3560:    Level: intermediate

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

3564: .seealso: SNESSetConvergencHistory()

3566: @*/
3567: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
3568: {
3571:   if (a)   *a   = snes->conv_hist;
3572:   if (its) *its = snes->conv_hist_its;
3573:   if (na)  *na  = snes->conv_hist_len;
3574:   return(0);
3575: }

3579: /*@C
3580:   SNESSetUpdate - Sets the general-purpose update function called
3581:   at the beginning of every iteration of the nonlinear solve. Specifically
3582:   it is called just before the Jacobian is "evaluated".

3584:   Logically Collective on SNES

3586:   Input Parameters:
3587: . snes - The nonlinear solver context
3588: . func - The function

3590:   Calling sequence of func:
3591: . func (SNES snes, PetscInt step);

3593: . step - The current step of the iteration

3595:   Level: advanced

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

3600: .keywords: SNES, update

3602: .seealso SNESSetJacobian(), SNESSolve()
3603: @*/
3604: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
3605: {
3608:   snes->ops->update = func;
3609:   return(0);
3610: }

3614: /*
3615:    SNESScaleStep_Private - Scales a step so that its length is less than the
3616:    positive parameter delta.

3618:     Input Parameters:
3619: +   snes - the SNES context
3620: .   y - approximate solution of linear system
3621: .   fnorm - 2-norm of current function
3622: -   delta - trust region size

3624:     Output Parameters:
3625: +   gpnorm - predicted function norm at the new point, assuming local
3626:     linearization.  The value is zero if the step lies within the trust
3627:     region, and exceeds zero otherwise.
3628: -   ynorm - 2-norm of the step

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

3634: .keywords: SNES, nonlinear, scale, step
3635: */
3636: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
3637: {
3638:   PetscReal      nrm;
3639:   PetscScalar    cnorm;


3647:   VecNorm(y,NORM_2,&nrm);
3648:   if (nrm > *delta) {
3649:     nrm     = *delta/nrm;
3650:     *gpnorm = (1.0 - nrm)*(*fnorm);
3651:     cnorm   = nrm;
3652:     VecScale(y,cnorm);
3653:     *ynorm  = *delta;
3654:   } else {
3655:     *gpnorm = 0.0;
3656:     *ynorm  = nrm;
3657:   }
3658:   return(0);
3659: }

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

3666:    Collective on SNES

3668:    Parameter:
3669: +  snes - iterative context obtained from SNESCreate()
3670: -  viewer - the viewer to display the reason


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

3676:    Level: beginner

3678: .keywords: SNES, solve, linear system

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

3682: @*/
3683: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
3684: {
3686:   PetscBool      isAscii;

3689:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
3690:   if (isAscii) {
3691:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
3692:     if (snes->reason > 0) {
3693:       if (((PetscObject) snes)->prefix) {
3694:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3695:       } else {
3696:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3697:       }
3698:     } else {
3699:       if (((PetscObject) snes)->prefix) {
3700:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3701:       } else {
3702:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3703:       }
3704:     }
3705:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
3706:   }
3707:   return(0);
3708: }

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

3715:   Collective on SNES

3717:   Input Parameters:
3718: . snes   - the SNES object

3720:   Level: intermediate

3722: @*/
3723: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
3724: {
3725:   PetscErrorCode    ierr;
3726:   PetscViewer       viewer;
3727:   PetscBool         flg;
3728:   static PetscBool  incall = PETSC_FALSE;
3729:   PetscViewerFormat format;

3732:   if (incall) return(0);
3733:   incall = PETSC_TRUE;
3734:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
3735:   if (flg) {
3736:     PetscViewerPushFormat(viewer,format);
3737:     SNESReasonView(snes,viewer);
3738:     PetscViewerPopFormat(viewer);
3739:     PetscViewerDestroy(&viewer);
3740:   }
3741:   incall = PETSC_FALSE;
3742:   return(0);
3743: }

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

3751:    Collective on SNES

3753:    Input Parameters:
3754: +  snes - the SNES context
3755: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
3756: -  x - the solution vector.

3758:    Notes:
3759:    The user should initialize the vector,x, with the initial guess
3760:    for the nonlinear solve prior to calling SNESSolve.  In particular,
3761:    to employ an initial guess of zero, the user should explicitly set
3762:    this vector to zero by calling VecSet().

3764:    Level: beginner

3766: .keywords: SNES, nonlinear, solve

3768: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
3769: @*/
3770: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
3771: {
3772:   PetscErrorCode    ierr;
3773:   PetscBool         flg;
3774:   PetscInt          grid;
3775:   Vec               xcreated = NULL;
3776:   DM                dm;


3785:   if (!x) {
3786:     SNESGetDM(snes,&dm);
3787:     DMCreateGlobalVector(dm,&xcreated);
3788:     x    = xcreated;
3789:   }
3790:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

3795:     /* set solution vector */
3796:     if (!grid) {PetscObjectReference((PetscObject)x);}
3797:     VecDestroy(&snes->vec_sol);
3798:     snes->vec_sol = x;
3799:     SNESGetDM(snes,&dm);

3801:     /* set affine vector if provided */
3802:     if (b) { PetscObjectReference((PetscObject)b); }
3803:     VecDestroy(&snes->vec_rhs);
3804:     snes->vec_rhs = b;

3806:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
3807:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
3808:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
3809:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
3810:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
3811:     }
3812:     DMShellSetGlobalVector(dm,snes->vec_sol);
3813:     SNESSetUp(snes);

3815:     if (!grid) {
3816:       if (snes->ops->computeinitialguess) {
3817:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
3818:       }
3819:     }

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

3824:     PetscLogEventBegin(SNES_Solve,snes,0,0,0);
3825:     (*snes->ops->solve)(snes);
3826:     PetscLogEventEnd(SNES_Solve,snes,0,0,0);
3827:     if (snes->domainerror) {
3828:       snes->reason      = SNES_DIVERGED_FUNCTION_DOMAIN;
3829:       snes->domainerror = PETSC_FALSE;
3830:     }
3831:     if (!snes->reason) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason");

3833:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
3834:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

3836:     flg  = PETSC_FALSE;
3837:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-snes_test_local_min",&flg,NULL);
3838:     if (flg && !PetscPreLoadingOn) { SNESTestLocalMin(snes); }
3839:     SNESReasonViewFromOptions(snes);

3841:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
3842:     if (grid <  snes->gridsequence) {
3843:       DM  fine;
3844:       Vec xnew;
3845:       Mat interp;

3847:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
3848:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
3849:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
3850:       DMCreateGlobalVector(fine,&xnew);
3851:       MatInterpolate(interp,x,xnew);
3852:       DMInterpolate(snes->dm,interp,fine);
3853:       MatDestroy(&interp);
3854:       x    = xnew;

3856:       SNESReset(snes);
3857:       SNESSetDM(snes,fine);
3858:       DMDestroy(&fine);
3859:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
3860:     }
3861:   }
3862:   SNESViewFromOptions(snes,NULL,"-snes_view");
3863:   VecViewFromOptions(snes->vec_sol,((PetscObject)snes)->prefix,"-snes_view_solution");

3865:   VecDestroy(&xcreated);
3866:   PetscObjectSAWsBlock((PetscObject)snes);
3867:   return(0);
3868: }

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

3874: /*@C
3875:    SNESSetType - Sets the method for the nonlinear solver.

3877:    Collective on SNES

3879:    Input Parameters:
3880: +  snes - the SNES context
3881: -  type - a known method

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

3887:    Notes:
3888:    See "petsc/include/petscsnes.h" for available methods (for instance)
3889: +    SNESNEWTONLS - Newton's method with line search
3890:      (systems of nonlinear equations)
3891: .    SNESNEWTONTR - Newton's method with trust region
3892:      (systems of nonlinear equations)

3894:   Normally, it is best to use the SNESSetFromOptions() command and then
3895:   set the SNES solver type from the options database rather than by using
3896:   this routine.  Using the options database provides the user with
3897:   maximum flexibility in evaluating the many nonlinear solvers.
3898:   The SNESSetType() routine is provided for those situations where it
3899:   is necessary to set the nonlinear solver independently of the command
3900:   line or options database.  This might be the case, for example, when
3901:   the choice of solver changes during the execution of the program,
3902:   and the user's application is taking responsibility for choosing the
3903:   appropriate method.

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

3908:   Level: intermediate

3910: .keywords: SNES, set, type

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

3914: @*/
3915: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
3916: {
3917:   PetscErrorCode ierr,(*r)(SNES);
3918:   PetscBool      match;


3924:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
3925:   if (match) return(0);

3927:    PetscFunctionListFind(SNESList,type,&r);
3928:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
3929:   /* Destroy the previous private SNES context */
3930:   if (snes->ops->destroy) {
3931:     (*(snes)->ops->destroy)(snes);
3932:     snes->ops->destroy = NULL;
3933:   }
3934:   /* Reinitialize function pointers in SNESOps structure */
3935:   snes->ops->setup          = 0;
3936:   snes->ops->solve          = 0;
3937:   snes->ops->view           = 0;
3938:   snes->ops->setfromoptions = 0;
3939:   snes->ops->destroy        = 0;
3940:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
3941:   snes->setupcalled = PETSC_FALSE;

3943:   PetscObjectChangeTypeName((PetscObject)snes,type);
3944:   (*r)(snes);
3945:   return(0);
3946: }

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

3953:    Not Collective

3955:    Input Parameter:
3956: .  snes - nonlinear solver context

3958:    Output Parameter:
3959: .  type - SNES method (a character string)

3961:    Level: intermediate

3963: .keywords: SNES, nonlinear, get, type, name
3964: @*/
3965: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
3966: {
3970:   *type = ((PetscObject)snes)->type_name;
3971:   return(0);
3972: }

3976: /*@
3977:    SNESGetSolution - Returns the vector where the approximate solution is
3978:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

3982:    Input Parameter:
3983: .  snes - the SNES context

3985:    Output Parameter:
3986: .  x - the solution

3988:    Level: intermediate

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

3992: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
3993: @*/
3994: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
3995: {
3999:   *x = snes->vec_sol;
4000:   return(0);
4001: }

4005: /*@
4006:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4007:    stored.

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

4011:    Input Parameter:
4012: .  snes - the SNES context

4014:    Output Parameter:
4015: .  x - the solution update

4017:    Level: advanced

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

4021: .seealso: SNESGetSolution(), SNESGetFunction()
4022: @*/
4023: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4024: {
4028:   *x = snes->vec_sol_update;
4029:   return(0);
4030: }

4034: /*@C
4035:    SNESGetFunction - Returns the vector where the function is stored.

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

4039:    Input Parameter:
4040: .  snes - the SNES context

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

4047:    Level: advanced

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

4051: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4052: @*/
4053: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4054: {
4056:   DM             dm;

4060:   if (r) {
4061:     if (!snes->vec_func) {
4062:       if (snes->vec_rhs) {
4063:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4064:       } else if (snes->vec_sol) {
4065:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4066:       } else if (snes->dm) {
4067:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4068:       }
4069:     }
4070:     *r = snes->vec_func;
4071:   }
4072:   SNESGetDM(snes,&dm);
4073:   DMSNESGetFunction(dm,f,ctx);
4074:   return(0);
4075: }

4077: /*@C
4078:    SNESGetNGS - Returns the NGS function and context.

4080:    Input Parameter:
4081: .  snes - the SNES context

4083:    Output Parameter:
4084: +  f - the function (or NULL) see SNESNGSFunction for details
4085: -  ctx    - the function context (or NULL)

4087:    Level: advanced

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

4091: .seealso: SNESSetNGS(), SNESGetFunction()
4092: @*/

4096: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4097: {
4099:   DM             dm;

4103:   SNESGetDM(snes,&dm);
4104:   DMSNESGetNGS(dm,f,ctx);
4105:   return(0);
4106: }

4110: /*@C
4111:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4112:    SNES options in the database.

4114:    Logically Collective on SNES

4116:    Input Parameter:
4117: +  snes - the SNES context
4118: -  prefix - the prefix to prepend to all option names

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

4124:    Level: advanced

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

4128: .seealso: SNESSetFromOptions()
4129: @*/
4130: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4131: {

4136:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4137:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4138:   if (snes->linesearch) {
4139:     SNESGetLineSearch(snes,&snes->linesearch);
4140:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4141:   }
4142:   KSPSetOptionsPrefix(snes->ksp,prefix);
4143:   return(0);
4144: }

4148: /*@C
4149:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4150:    SNES options in the database.

4152:    Logically Collective on SNES

4154:    Input Parameters:
4155: +  snes - the SNES context
4156: -  prefix - the prefix to prepend to all option names

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

4162:    Level: advanced

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

4166: .seealso: SNESGetOptionsPrefix()
4167: @*/
4168: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4169: {

4174:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4175:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4176:   if (snes->linesearch) {
4177:     SNESGetLineSearch(snes,&snes->linesearch);
4178:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4179:   }
4180:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4181:   return(0);
4182: }

4186: /*@C
4187:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4188:    SNES options in the database.

4190:    Not Collective

4192:    Input Parameter:
4193: .  snes - the SNES context

4195:    Output Parameter:
4196: .  prefix - pointer to the prefix string used

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

4201:    Level: advanced

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

4205: .seealso: SNESAppendOptionsPrefix()
4206: @*/
4207: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4208: {

4213:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4214:   return(0);
4215: }


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

4223:    Not collective

4225:    Input Parameters:
4226: +  name_solver - name of a new user-defined solver
4227: -  routine_create - routine to create method context

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

4232:    Sample usage:
4233: .vb
4234:    SNESRegister("my_solver",MySolverCreate);
4235: .ve

4237:    Then, your solver can be chosen with the procedural interface via
4238: $     SNESSetType(snes,"my_solver")
4239:    or at runtime via the option
4240: $     -snes_type my_solver

4242:    Level: advanced

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

4246: .keywords: SNES, nonlinear, register

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

4250:   Level: advanced
4251: @*/
4252: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4253: {

4257:   PetscFunctionListAdd(&SNESList,sname,function);
4258:   return(0);
4259: }

4263: PetscErrorCode  SNESTestLocalMin(SNES snes)
4264: {
4266:   PetscInt       N,i,j;
4267:   Vec            u,uh,fh;
4268:   PetscScalar    value;
4269:   PetscReal      norm;

4272:   SNESGetSolution(snes,&u);
4273:   VecDuplicate(u,&uh);
4274:   VecDuplicate(u,&fh);

4276:   /* currently only works for sequential */
4277:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4278:   VecGetSize(u,&N);
4279:   for (i=0; i<N; i++) {
4280:     VecCopy(u,uh);
4281:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4282:     for (j=-10; j<11; j++) {
4283:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4284:       VecSetValue(uh,i,value,ADD_VALUES);
4285:       SNESComputeFunction(snes,uh,fh);
4286:       VecNorm(fh,NORM_2,&norm);
4287:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4288:       value = -value;
4289:       VecSetValue(uh,i,value,ADD_VALUES);
4290:     }
4291:   }
4292:   VecDestroy(&uh);
4293:   VecDestroy(&fh);
4294:   return(0);
4295: }

4299: /*@
4300:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4301:    computing relative tolerance for linear solvers within an inexact
4302:    Newton method.

4304:    Logically Collective on SNES

4306:    Input Parameters:
4307: +  snes - SNES context
4308: -  flag - PETSC_TRUE or PETSC_FALSE

4310:     Options Database:
4311: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4312: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4313: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4314: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4315: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4316: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4317: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4318: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4320:    Notes:
4321:    Currently, the default is to use a constant relative tolerance for
4322:    the inner linear solvers.  Alternatively, one can use the
4323:    Eisenstat-Walker method, where the relative convergence tolerance
4324:    is reset at each Newton iteration according progress of the nonlinear
4325:    solver.

4327:    Level: advanced

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

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

4335: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4336: @*/
4337: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4338: {
4342:   snes->ksp_ewconv = flag;
4343:   return(0);
4344: }

4348: /*@
4349:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4350:    for computing relative tolerance for linear solvers within an
4351:    inexact Newton method.

4353:    Not Collective

4355:    Input Parameter:
4356: .  snes - SNES context

4358:    Output Parameter:
4359: .  flag - PETSC_TRUE or PETSC_FALSE

4361:    Notes:
4362:    Currently, the default is to use a constant relative tolerance for
4363:    the inner linear solvers.  Alternatively, one can use the
4364:    Eisenstat-Walker method, where the relative convergence tolerance
4365:    is reset at each Newton iteration according progress of the nonlinear
4366:    solver.

4368:    Level: advanced

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

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

4376: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4377: @*/
4378: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4379: {
4383:   *flag = snes->ksp_ewconv;
4384:   return(0);
4385: }

4389: /*@
4390:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4391:    convergence criteria for the linear solvers within an inexact
4392:    Newton method.

4394:    Logically Collective on SNES

4396:    Input Parameters:
4397: +    snes - SNES context
4398: .    version - version 1, 2 (default is 2) or 3
4399: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4400: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4401: .    gamma - multiplicative factor for version 2 rtol computation
4402:              (0 <= gamma2 <= 1)
4403: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4404: .    alpha2 - power for safeguard
4405: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4407:    Note:
4408:    Version 3 was contributed by Luis Chacon, June 2006.

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

4412:    Level: advanced

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

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

4421: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4422: @*/
4423: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4424: {
4425:   SNESKSPEW *kctx;

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

4439:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4440:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4441:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4442:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4443:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4444:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4445:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4447:   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);
4448:   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);
4449:   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);
4450:   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);
4451:   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);
4452:   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);
4453:   return(0);
4454: }

4458: /*@
4459:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4460:    convergence criteria for the linear solvers within an inexact
4461:    Newton method.

4463:    Not Collective

4465:    Input Parameters:
4466:      snes - SNES context

4468:    Output Parameters:
4469: +    version - version 1, 2 (default is 2) or 3
4470: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4471: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4472: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
4473: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4474: .    alpha2 - power for safeguard
4475: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4477:    Level: advanced

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

4481: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
4482: @*/
4483: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
4484: {
4485:   SNESKSPEW *kctx;

4489:   kctx = (SNESKSPEW*)snes->kspconvctx;
4490:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
4491:   if (version)   *version   = kctx->version;
4492:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
4493:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
4494:   if (gamma)     *gamma     = kctx->gamma;
4495:   if (alpha)     *alpha     = kctx->alpha;
4496:   if (alpha2)    *alpha2    = kctx->alpha2;
4497:   if (threshold) *threshold = kctx->threshold;
4498:   return(0);
4499: }

4503:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4504: {
4506:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4507:   PetscReal      rtol  = PETSC_DEFAULT,stol;

4510:   if (!snes->ksp_ewconv) return(0);
4511:   if (!snes->iter) {
4512:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
4513:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
4514:   }
4515:   else {
4516:     if (kctx->version == 1) {
4517:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
4518:       if (rtol < 0.0) rtol = -rtol;
4519:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
4520:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4521:     } else if (kctx->version == 2) {
4522:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4523:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
4524:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4525:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
4526:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4527:       /* safeguard: avoid sharp decrease of rtol */
4528:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
4529:       stol = PetscMax(rtol,stol);
4530:       rtol = PetscMin(kctx->rtol_0,stol);
4531:       /* safeguard: avoid oversolving */
4532:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
4533:       stol = PetscMax(rtol,stol);
4534:       rtol = PetscMin(kctx->rtol_0,stol);
4535:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
4536:   }
4537:   /* safeguard: avoid rtol greater than one */
4538:   rtol = PetscMin(rtol,kctx->rtol_max);
4539:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
4540:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
4541:   return(0);
4542: }

4546: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4547: {
4549:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4550:   PCSide         pcside;
4551:   Vec            lres;

4554:   if (!snes->ksp_ewconv) return(0);
4555:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
4556:   kctx->norm_last = snes->norm;
4557:   if (kctx->version == 1) {
4558:     PC        pc;
4559:     PetscBool isNone;

4561:     KSPGetPC(ksp, &pc);
4562:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
4563:     KSPGetPCSide(ksp,&pcside);
4564:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
4565:       /* KSP residual is true linear residual */
4566:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
4567:     } else {
4568:       /* KSP residual is preconditioned residual */
4569:       /* compute true linear residual norm */
4570:       VecDuplicate(b,&lres);
4571:       MatMult(snes->jacobian,x,lres);
4572:       VecAYPX(lres,-1.0,b);
4573:       VecNorm(lres,NORM_2,&kctx->lresid_last);
4574:       VecDestroy(&lres);
4575:     }
4576:   }
4577:   return(0);
4578: }

4582: /*@
4583:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

4587:    Input Parameter:
4588: .  snes - the SNES context

4590:    Output Parameter:
4591: .  ksp - the KSP context

4593:    Notes:
4594:    The user can then directly manipulate the KSP context to set various
4595:    options, etc.  Likewise, the user can then extract and manipulate the
4596:    PC contexts as well.

4598:    Level: beginner

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

4602: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
4603: @*/
4604: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
4605: {


4612:   if (!snes->ksp) {
4613:     PetscBool monitor = PETSC_FALSE;

4615:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
4616:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
4617:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

4622:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
4623:     if (monitor) {
4624:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
4625:     }
4626:     monitor = PETSC_FALSE;
4627:     PetscOptionsGetBool(((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
4628:     if (monitor) {
4629:       PetscObject *objs;
4630:       KSPMonitorSNESLGResidualNormCreate(0,0,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
4631:       objs[0] = (PetscObject) snes;
4632:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
4633:     }
4634:   }
4635:   *ksp = snes->ksp;
4636:   return(0);
4637: }


4640: #include <petsc-private/dmimpl.h>
4643: /*@
4644:    SNESSetDM - Sets the DM that may be used by some preconditioners

4646:    Logically Collective on SNES

4648:    Input Parameters:
4649: +  snes - the preconditioner context
4650: -  dm - the dm

4652:    Level: intermediate

4654: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
4655: @*/
4656: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
4657: {
4659:   KSP            ksp;
4660:   DMSNES         sdm;

4664:   if (dm) {PetscObjectReference((PetscObject)dm);}
4665:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
4666:     if (snes->dm->dmsnes && snes->dmAuto && !dm->dmsnes) {
4667:       DMCopyDMSNES(snes->dm,dm);
4668:       DMGetDMSNES(snes->dm,&sdm);
4669:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
4670:     }
4671:     DMDestroy(&snes->dm);
4672:   }
4673:   snes->dm     = dm;
4674:   snes->dmAuto = PETSC_FALSE;

4676:   SNESGetKSP(snes,&ksp);
4677:   KSPSetDM(ksp,dm);
4678:   KSPSetDMActive(ksp,PETSC_FALSE);
4679:   if (snes->pc) {
4680:     SNESSetDM(snes->pc, snes->dm);
4681:     SNESSetNPCSide(snes,snes->pcside);
4682:   }
4683:   return(0);
4684: }

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

4691:    Not Collective but DM obtained is parallel on SNES

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

4696:    Output Parameter:
4697: .  dm - the dm

4699:    Level: intermediate

4701: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
4702: @*/
4703: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
4704: {

4709:   if (!snes->dm) {
4710:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
4711:     snes->dmAuto = PETSC_TRUE;
4712:   }
4713:   *dm = snes->dm;
4714:   return(0);
4715: }

4719: /*@
4720:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

4722:   Collective on SNES

4724:   Input Parameters:
4725: + snes - iterative context obtained from SNESCreate()
4726: - pc   - the preconditioner object

4728:   Notes:
4729:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
4730:   to configure it using the API).

4732:   Level: developer

4734: .keywords: SNES, set, precondition
4735: .seealso: SNESGetNPC(), SNESHasNPC()
4736: @*/
4737: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
4738: {

4745:   PetscObjectReference((PetscObject) pc);
4746:   SNESDestroy(&snes->pc);
4747:   snes->pc = pc;
4748:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->pc);
4749:   return(0);
4750: }

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

4757:   Not Collective

4759:   Input Parameter:
4760: . snes - iterative context obtained from SNESCreate()

4762:   Output Parameter:
4763: . pc - preconditioner context

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

4767:   Level: developer

4769: .keywords: SNES, get, preconditioner
4770: .seealso: SNESSetNPC(), SNESHasNPC()
4771: @*/
4772: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
4773: {
4775:   const char     *optionsprefix;

4780:   if (!snes->pc) {
4781:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->pc);
4782:     PetscObjectIncrementTabLevel((PetscObject)snes->pc,(PetscObject)snes,1);
4783:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->pc);
4784:     SNESGetOptionsPrefix(snes,&optionsprefix);
4785:     SNESSetOptionsPrefix(snes->pc,optionsprefix);
4786:     SNESAppendOptionsPrefix(snes->pc,"npc_");
4787:     SNESSetCountersReset(snes->pc,PETSC_FALSE);
4788:   }
4789:   *pc = snes->pc;
4790:   return(0);
4791: }

4795: /*@
4796:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

4798:   Not Collective

4800:   Input Parameter:
4801: . snes - iterative context obtained from SNESCreate()

4803:   Output Parameter:
4804: . has_npc - whether the SNES has an NPC or not

4806:   Level: developer

4808: .keywords: SNES, has, preconditioner
4809: .seealso: SNESSetNPC(), SNESGetNPC()
4810: @*/
4811: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
4812: {
4815:   *has_npc = (PetscBool) (snes->pc != NULL);
4816:   return(0);
4817: }

4821: /*@
4822:     SNESSetNPCSide - Sets the preconditioning side.

4824:     Logically Collective on SNES

4826:     Input Parameter:
4827: .   snes - iterative context obtained from SNESCreate()

4829:     Output Parameter:
4830: .   side - the preconditioning side, where side is one of
4831: .vb
4832:       PC_LEFT - left preconditioning (default)
4833:       PC_RIGHT - right preconditioning
4834: .ve

4836:     Options Database Keys:
4837: .   -snes_pc_side <right,left>

4839:     Level: intermediate

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

4843: .seealso: SNESGetNPCSide(), KSPSetPCSide()
4844: @*/
4845: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
4846: {
4850:   snes->pcside = side;
4851:   return(0);
4852: }

4856: /*@
4857:     SNESGetNPCSide - Gets the preconditioning side.

4859:     Not Collective

4861:     Input Parameter:
4862: .   snes - iterative context obtained from SNESCreate()

4864:     Output Parameter:
4865: .   side - the preconditioning side, where side is one of
4866: .vb
4867:       PC_LEFT - left preconditioning (default)
4868:       PC_RIGHT - right preconditioning
4869: .ve

4871:     Level: intermediate

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

4875: .seealso: SNESSetNPCSide(), KSPGetPCSide()
4876: @*/
4877: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
4878: {
4882:   *side = snes->pcside;
4883:   return(0);
4884: }

4888: /*@
4889:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

4891:   Collective on SNES

4893:   Input Parameters:
4894: + snes - iterative context obtained from SNESCreate()
4895: - linesearch   - the linesearch object

4897:   Notes:
4898:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
4899:   to configure it using the API).

4901:   Level: developer

4903: .keywords: SNES, set, linesearch
4904: .seealso: SNESGetLineSearch()
4905: @*/
4906: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
4907: {

4914:   PetscObjectReference((PetscObject) linesearch);
4915:   SNESLineSearchDestroy(&snes->linesearch);

4917:   snes->linesearch = linesearch;

4919:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
4920:   return(0);
4921: }

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

4929:   Not Collective

4931:   Input Parameter:
4932: . snes - iterative context obtained from SNESCreate()

4934:   Output Parameter:
4935: . linesearch - linesearch context

4937:   Level: beginner

4939: .keywords: SNES, get, linesearch
4940: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
4941: @*/
4942: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
4943: {
4945:   const char     *optionsprefix;

4950:   if (!snes->linesearch) {
4951:     SNESGetOptionsPrefix(snes, &optionsprefix);
4952:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
4953:     SNESLineSearchSetSNES(snes->linesearch, snes);
4954:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
4955:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
4956:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
4957:   }
4958:   *linesearch = snes->linesearch;
4959:   return(0);
4960: }

4962: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4963: #include <mex.h>

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

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

4972:    Collective on SNES

4974:    Input Parameters:
4975: +  snes - the SNES context
4976: -  x - input vector

4978:    Output Parameter:
4979: .  y - function vector, as set by SNESSetFunction()

4981:    Notes:
4982:    SNESComputeFunction() is typically used within nonlinear solvers
4983:    implementations, so most users would not generally call this routine
4984:    themselves.

4986:    Level: developer

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

4990: .seealso: SNESSetFunction(), SNESGetFunction()
4991: */
4992: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
4993: {
4994:   PetscErrorCode    ierr;
4995:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
4996:   int               nlhs  = 1,nrhs = 5;
4997:   mxArray           *plhs[1],*prhs[5];
4998:   long long int     lx = 0,ly = 0,ls = 0;


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

5009:   PetscMemcpy(&ls,&snes,sizeof(snes));
5010:   PetscMemcpy(&lx,&x,sizeof(x));
5011:   PetscMemcpy(&ly,&y,sizeof(x));
5012:   prhs[0] = mxCreateDoubleScalar((double)ls);
5013:   prhs[1] = mxCreateDoubleScalar((double)lx);
5014:   prhs[2] = mxCreateDoubleScalar((double)ly);
5015:   prhs[3] = mxCreateString(sctx->funcname);
5016:   prhs[4] = sctx->ctx;
5017:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");
5018:   mxGetScalar(plhs[0]);
5019:   mxDestroyArray(prhs[0]);
5020:   mxDestroyArray(prhs[1]);
5021:   mxDestroyArray(prhs[2]);
5022:   mxDestroyArray(prhs[3]);
5023:   mxDestroyArray(plhs[0]);
5024:   return(0);
5025: }

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

5034:    Logically Collective on SNES

5036:    Input Parameters:
5037: +  snes - the SNES context
5038: .  r - vector to store function value
5039: -  f - function evaluation routine

5041:    Notes:
5042:    The Newton-like methods typically solve linear systems of the form
5043: $      f'(x) x = -f(x),
5044:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5046:    Level: beginner

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

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

5052: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5053: */
5054: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5055: {
5056:   PetscErrorCode    ierr;
5057:   SNESMatlabContext *sctx;

5060:   /* currently sctx is memory bleed */
5061:   PetscNew(&sctx);
5062:   PetscStrallocpy(f,&sctx->funcname);
5063:   /*
5064:      This should work, but it doesn't
5065:   sctx->ctx = ctx;
5066:   mexMakeArrayPersistent(sctx->ctx);
5067:   */
5068:   sctx->ctx = mxDuplicateArray(ctx);
5069:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5070:   return(0);
5071: }

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

5078:    Collective on SNES

5080:    Input Parameters:
5081: +  snes - the SNES context
5082: .  x - input vector
5083: .  A, B - the matrices
5084: -  ctx - user context

5086:    Level: developer

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

5090: .seealso: SNESSetFunction(), SNESGetFunction()
5091: @*/
5092: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5093: {
5094:   PetscErrorCode    ierr;
5095:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5096:   int               nlhs  = 2,nrhs = 6;
5097:   mxArray           *plhs[2],*prhs[6];
5098:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


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

5106:   PetscMemcpy(&ls,&snes,sizeof(snes));
5107:   PetscMemcpy(&lx,&x,sizeof(x));
5108:   PetscMemcpy(&lA,A,sizeof(x));
5109:   PetscMemcpy(&lB,B,sizeof(x));
5110:   prhs[0] = mxCreateDoubleScalar((double)ls);
5111:   prhs[1] = mxCreateDoubleScalar((double)lx);
5112:   prhs[2] = mxCreateDoubleScalar((double)lA);
5113:   prhs[3] = mxCreateDoubleScalar((double)lB);
5114:   prhs[4] = mxCreateString(sctx->funcname);
5115:   prhs[5] = sctx->ctx;
5116:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5117:   mxGetScalar(plhs[0]);
5118:   mxDestroyArray(prhs[0]);
5119:   mxDestroyArray(prhs[1]);
5120:   mxDestroyArray(prhs[2]);
5121:   mxDestroyArray(prhs[3]);
5122:   mxDestroyArray(prhs[4]);
5123:   mxDestroyArray(plhs[0]);
5124:   mxDestroyArray(plhs[1]);
5125:   return(0);
5126: }

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

5135:    Logically Collective on SNES

5137:    Input Parameters:
5138: +  snes - the SNES context
5139: .  A,B - Jacobian matrices
5140: .  J - function evaluation routine
5141: -  ctx - user context

5143:    Level: developer

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

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

5149: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5150: */
5151: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5152: {
5153:   PetscErrorCode    ierr;
5154:   SNESMatlabContext *sctx;

5157:   /* currently sctx is memory bleed */
5158:   PetscNew(&sctx);
5159:   PetscStrallocpy(J,&sctx->funcname);
5160:   /*
5161:      This should work, but it doesn't
5162:   sctx->ctx = ctx;
5163:   mexMakeArrayPersistent(sctx->ctx);
5164:   */
5165:   sctx->ctx = mxDuplicateArray(ctx);
5166:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5167:   return(0);
5168: }

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

5175:    Collective on SNES

5177: .seealso: SNESSetFunction(), SNESGetFunction()
5178: @*/
5179: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5180: {
5181:   PetscErrorCode    ierr;
5182:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5183:   int               nlhs  = 1,nrhs = 6;
5184:   mxArray           *plhs[1],*prhs[6];
5185:   long long int     lx = 0,ls = 0;
5186:   Vec               x  = snes->vec_sol;


5191:   PetscMemcpy(&ls,&snes,sizeof(snes));
5192:   PetscMemcpy(&lx,&x,sizeof(x));
5193:   prhs[0] = mxCreateDoubleScalar((double)ls);
5194:   prhs[1] = mxCreateDoubleScalar((double)it);
5195:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5196:   prhs[3] = mxCreateDoubleScalar((double)lx);
5197:   prhs[4] = mxCreateString(sctx->funcname);
5198:   prhs[5] = sctx->ctx;
5199:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5200:   mxGetScalar(plhs[0]);
5201:   mxDestroyArray(prhs[0]);
5202:   mxDestroyArray(prhs[1]);
5203:   mxDestroyArray(prhs[2]);
5204:   mxDestroyArray(prhs[3]);
5205:   mxDestroyArray(prhs[4]);
5206:   mxDestroyArray(plhs[0]);
5207:   return(0);
5208: }

5212: /*
5213:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5215:    Level: developer

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

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

5221: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5222: */
5223: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5224: {
5225:   PetscErrorCode    ierr;
5226:   SNESMatlabContext *sctx;

5229:   /* currently sctx is memory bleed */
5230:   PetscNew(&sctx);
5231:   PetscStrallocpy(f,&sctx->funcname);
5232:   /*
5233:      This should work, but it doesn't
5234:   sctx->ctx = ctx;
5235:   mexMakeArrayPersistent(sctx->ctx);
5236:   */
5237:   sctx->ctx = mxDuplicateArray(ctx);
5238:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5239:   return(0);
5240: }

5242: #endif