Actual source code: snes.c

petsc-master 2016-08-26
Report Typos and Errors
 2:  #include <petsc/private/snesimpl.h>
 3:  #include <petscdmshell.h>
 4:  #include <petscdraw.h>

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

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

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

 18:    Logically Collective on SNES

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

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

 27:    Level: intermediate

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

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

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

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

 51:    Not Collective

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

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

 59:    Level: intermediate

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

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

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

 79:    Logically Collective on SNES

 81:     Input Parameters:
 82: +   snes - the shell SNES
 83: -   flg - is the residual computed?

 85:    Level: advanced

 87: .seealso: SNESGetAlwaysComputesFinalResidual()
 88: @*/
 89: PetscErrorCode  SNESSetAlwaysComputesFinalResidual(SNES snes, PetscBool flg)
 90: {
 93:   snes->alwayscomputesfinalresidual = flg;
 94:   return(0);
 95: }

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

102:    Logically Collective on SNES

104:     Input Parameter:
105: .   snes - the shell SNES

107:     Output Parameter:
108: .   flg - is the residual computed?

110:    Level: advanced

112: .seealso: SNESSetAlwaysComputesFinalResidual()
113: @*/
114: PetscErrorCode  SNESGetAlwaysComputesFinalResidual(SNES snes, PetscBool *flg)
115: {
118:   *flg = snes->alwayscomputesfinalresidual;
119:   return(0);
120: }

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

128:    Logically Collective on SNES

130:    Input Parameters:
131: .  snes - the SNES context

133:    Level: advanced

135: .keywords: SNES, view

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

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

153:    Logically Collective on SNES

155:    Input Parameters:
156: .  snes - the SNES context

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

161:    Level: advanced

163: .keywords: SNES, view

165: .seealso: SNESSetFunctionDomainError(), SNESComputeFunction()
166: @*/
167: PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
168: {
172:   *domainerror = snes->domainerror;
173:   return(0);
174: }

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

181:   Collective on PetscViewer

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

188:    Level: intermediate

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

193:   Notes for advanced users:
194:   Most users should not need to know the details of the binary storage
195:   format, since SNESLoad() and TSView() completely hide these details.
196:   But for anyone who's interested, the standard binary matrix storage
197:   format is
198: .vb
199:      has not yet been determined
200: .ve

202: .seealso: PetscViewerBinaryOpen(), SNESView(), MatLoad(), VecLoad()
203: @*/
204: PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
205: {
207:   PetscBool      isbinary;
208:   PetscInt       classid;
209:   char           type[256];
210:   KSP            ksp;
211:   DM             dm;
212:   DMSNES         dmsnes;

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

220:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
221:   if (classid != SNES_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
222:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
223:   SNESSetType(snes, type);
224:   if (snes->ops->load) {
225:     (*snes->ops->load)(snes,viewer);
226:   }
227:   SNESGetDM(snes,&dm);
228:   DMGetDMSNES(dm,&dmsnes);
229:   DMSNESLoad(dmsnes,viewer);
230:   SNESGetKSP(snes,&ksp);
231:   KSPLoad(ksp,viewer);
232:   return(0);
233: }

235:  #include <petscdraw.h>
236: #if defined(PETSC_HAVE_SAWS)
237:  #include <petscviewersaws.h>
238: #endif
241: /*@C
242:    SNESView - Prints the SNES data structure.

244:    Collective on SNES

246:    Input Parameters:
247: +  SNES - the SNES context
248: -  viewer - visualization context

250:    Options Database Key:
251: .  -snes_view - Calls SNESView() at end of SNESSolve()

253:    Notes:
254:    The available visualization contexts include
255: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
256: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
257:          output where only the first processor opens
258:          the file.  All other processors send their
259:          data to the first processor to print.

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

264:    Level: beginner

266: .keywords: SNES, view

268: .seealso: PetscViewerASCIIOpen()
269: @*/
270: PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
271: {
272:   SNESKSPEW      *kctx;
274:   KSP            ksp;
275:   SNESLineSearch linesearch;
276:   PetscBool      iascii,isstring,isbinary,isdraw;
277:   DMSNES         dmsnes;
278: #if defined(PETSC_HAVE_SAWS)
279:   PetscBool      issaws;
280: #endif

284:   if (!viewer) {
285:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer);
286:   }

290:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
291:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
292:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
293:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
294: #if defined(PETSC_HAVE_SAWS)
295:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
296: #endif
297:   if (iascii) {
298:     SNESNormSchedule normschedule;

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

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

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

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

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

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

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

434:   Not Collective

436:   Input Parameter:
437: . snescheck - function that checks for options

439:   Level: developer

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

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

455: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
456: {
457:   Mat            J;
458:   KSP            ksp;
459:   PC             pc;
460:   PetscBool      match;
462:   MatNullSpace   nullsp;


467:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
468:     Mat A = snes->jacobian, B = snes->jacobian_pre;
469:     MatCreateVecs(A ? A : B, NULL,&snes->vec_func);
470:   }

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

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

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

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

522: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
523: {
524:   SNES           snes = (SNES)ctx;
526:   Vec            Xfine,Xfine_named = NULL,Xcoarse;

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

556: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
557: {

561:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
562:   return(0);
563: }

567: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
568:  * safely call SNESGetDM() in their residual evaluation routine. */
569: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
570: {
571:   SNES           snes = (SNES)ctx;
573:   Mat            Asave = A,Bsave = B;
574:   Vec            X,Xnamed = NULL;
575:   DM             dmsave;
576:   void           *ctxsave;
577:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);

580:   dmsave = snes->dm;
581:   KSPGetDM(ksp,&snes->dm);
582:   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
583:   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
584:     DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
585:     X    = Xnamed;
586:     SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave);
587:     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
588:     if (jac == SNESComputeJacobianDefaultColor) {
589:       SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,0);
590:     }
591:   }
592:   /* put the previous context back */

594:   SNESComputeJacobian(snes,X,A,B);
595:   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
596:     SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);
597:   }

599:   if (A != Asave || B != Bsave) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_SUP,"No support for changing matrices at this time");
600:   if (Xnamed) {
601:     DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
602:   }
603:   snes->dm = dmsave;
604:   return(0);
605: }

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

612:    Collective

614:    Input Arguments:
615: .  snes - snes to configure

617:    Level: developer

619: .seealso: SNESSetUp()
620: @*/
621: PetscErrorCode SNESSetUpMatrices(SNES snes)
622: {
624:   DM             dm;
625:   DMSNES         sdm;

628:   SNESGetDM(snes,&dm);
629:   DMGetDMSNES(dm,&sdm);
630:   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_PLIB,"DMSNES not properly configured");
631:   else if (!snes->jacobian && snes->mf) {
632:     Mat  J;
633:     void *functx;
634:     MatCreateSNESMF(snes,&J);
635:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
636:     MatSetFromOptions(J);
637:     SNESGetFunction(snes,NULL,NULL,&functx);
638:     SNESSetJacobian(snes,J,J,0,0);
639:     MatDestroy(&J);
640:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
641:     Mat J,B;
642:     MatCreateSNESMF(snes,&J);
643:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
644:     MatSetFromOptions(J);
645:     DMCreateMatrix(snes->dm,&B);
646:     /* sdm->computejacobian was already set to reach here */
647:     SNESSetJacobian(snes,J,B,NULL,NULL);
648:     MatDestroy(&J);
649:     MatDestroy(&B);
650:   } else if (!snes->jacobian_pre) {
651:     Mat J,B;
652:     J    = snes->jacobian;
653:     DMCreateMatrix(snes->dm,&B);
654:     SNESSetJacobian(snes,J ? J : B,B,NULL,NULL);
655:     MatDestroy(&B);
656:   }
657:   {
658:     KSP ksp;
659:     SNESGetKSP(snes,&ksp);
660:     KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);
661:     DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
662:   }
663:   return(0);
664: }

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

671:    Collective on SNES

673:    Input Parameters:
674: +  snes - SNES object you wish to monitor
675: .  name - the monitor type one is seeking
676: .  help - message indicating what monitoring is done
677: .  manual - manual page for the monitor
678: .  monitor - the monitor function
679: -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the SNES or PetscViewer objects

681:    Level: developer

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

699:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,name,&viewer,&format,&flg);
700:   if (flg) {
701:     PetscViewerAndFormat *vf;
702:     PetscViewerAndFormatCreate(viewer,format,&vf);
703:     PetscObjectDereference((PetscObject)viewer);
704:     if (monitorsetup) {
705:       (*monitorsetup)(snes,vf);
706:     }
707:     SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
708:   }
709:   return(0);
710: }

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

717:    Collective on SNES

719:    Input Parameter:
720: .  snes - the SNES context

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

750:     Options Database for Eisenstat-Walker method:
751: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
752: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
753: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
754: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
755: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
756: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
757: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
758: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

760:    Notes:
761:    To see all options, run your program with the -help option or consult
762:    Users-Manual: ch_snes

764:    Level: beginner

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

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

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

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

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

820:   PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg);
821:   if (flg) {
822:     SNESSetGridSequence(snes,grids);
823:   }

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

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

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

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

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

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

851:   flg  = PETSC_FALSE;
852:   PetscOptionsBool("-snes_check_jacobian","Check each Jacobian with a differenced one","SNESUpdateCheckJacobian",flg,&flg,&set);
853:   if (set && flg) {
854:     SNESSetUpdate(snes,SNESUpdateCheckJacobian);
855:   }

857:   flg  = PETSC_FALSE;
858:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
859:   if (set && flg) {SNESMonitorCancel(snes);}

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

865:   SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp);
866:   SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL);
867:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL);
868:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL);
869:   SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL);
870:   SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL);
871:   SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL);

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


877:   flg  = PETSC_FALSE;
878:   PetscOptionsBool("-snes_monitor_lg_residualnorm","Plot function norm at each iteration","SNESMonitorLGResidualNorm",flg,&flg,NULL);
879:   if (flg) {
880:     PetscDrawLG ctx;

882:     SNESMonitorLGCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
883:     SNESMonitorSet(snes,SNESMonitorLGResidualNorm,ctx,(PetscErrorCode (*)(void**))PetscDrawLGDestroy);
884:   }
885:   flg  = PETSC_FALSE;
886:   PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);
887:   if (flg) {
888:     PetscViewer ctx;

890:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
891:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
892:   }



896:   flg  = PETSC_FALSE;
897:   PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);
898:   if (flg) {
899:     void *functx;
900:     SNESGetFunction(snes,NULL,NULL,&functx);
901:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);
902:     PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");
903:   }

905:   flg  = PETSC_FALSE;
906:   PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);
907:   if (flg) {
908:     SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);
909:   }

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

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

934:   flg  = PETSC_FALSE;
935:   SNESGetNPCSide(snes,&pcside);
936:   PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);
937:   if (flg) {SNESSetNPCSide(snes,pcside);}

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

962:   for (i = 0; i < numberofsetfromoptions; i++) {
963:     (*othersetfromoptions[i])(snes);
964:   }

966:   if (snes->ops->setfromoptions) {
967:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
968:   }

970:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
971:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
972:   PetscOptionsEnd();

974:   if (!snes->linesearch) {
975:     SNESGetLineSearch(snes, &snes->linesearch);
976:   }
977:   SNESLineSearchSetFromOptions(snes->linesearch);

979:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
980:   KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
981:   KSPSetFromOptions(snes->ksp);

983:   /* if someone has set the SNES NPC type, create it. */
984:   SNESGetOptionsPrefix(snes, &optionsprefix);
985:   PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset);
986:   if (pcset && (!snes->pc)) {
987:     SNESGetNPC(snes, &snes->pc);
988:   }
989:   return(0);
990: }

994: /*@C
995:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
996:    the nonlinear solvers.

998:    Logically Collective on SNES

1000:    Input Parameters:
1001: +  snes - the SNES context
1002: .  compute - function to compute the context
1003: -  destroy - function to destroy the context

1005:    Level: intermediate

1007:    Notes:
1008:    This function is currently not available from Fortran.

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

1012: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1013: @*/
1014: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1015: {
1018:   snes->ops->usercompute = compute;
1019:   snes->ops->userdestroy = destroy;
1020:   return(0);
1021: }

1025: /*@
1026:    SNESSetApplicationContext - Sets the optional user-defined context for
1027:    the nonlinear solvers.

1029:    Logically Collective on SNES

1031:    Input Parameters:
1032: +  snes - the SNES context
1033: -  usrP - optional user context

1035:    Level: intermediate

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

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

1042: .seealso: SNESGetApplicationContext()
1043: @*/
1044: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1045: {
1047:   KSP            ksp;

1051:   SNESGetKSP(snes,&ksp);
1052:   KSPSetApplicationContext(ksp,usrP);
1053:   snes->user = usrP;
1054:   return(0);
1055: }

1059: /*@
1060:    SNESGetApplicationContext - Gets the user-defined context for the
1061:    nonlinear solvers.

1063:    Not Collective

1065:    Input Parameter:
1066: .  snes - SNES context

1068:    Output Parameter:
1069: .  usrP - user context

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

1074:    Level: intermediate

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

1078: .seealso: SNESSetApplicationContext()
1079: @*/
1080: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1081: {
1084:   *(void**)usrP = snes->user;
1085:   return(0);
1086: }

1090: /*@
1091:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1092:    at this time.

1094:    Not Collective

1096:    Input Parameter:
1097: .  snes - SNES context

1099:    Output Parameter:
1100: .  iter - iteration number

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

1105:    This is useful for using lagged Jacobians (where one does not recompute the
1106:    Jacobian at each SNES iteration). For example, the code
1107: .vb
1108:       SNESGetIterationNumber(snes,&it);
1109:       if (!(it % 2)) {
1110:         [compute Jacobian here]
1111:       }
1112: .ve
1113:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1114:    recomputed every second SNES iteration.

1116:    Level: intermediate

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

1120: .seealso:   SNESGetLinearSolveIterations()
1121: @*/
1122: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1123: {
1127:   *iter = snes->iter;
1128:   return(0);
1129: }

1133: /*@
1134:    SNESSetIterationNumber - Sets the current iteration number.

1136:    Not Collective

1138:    Input Parameter:
1139: .  snes - SNES context
1140: .  iter - iteration number

1142:    Level: developer

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

1146: .seealso:   SNESGetLinearSolveIterations()
1147: @*/
1148: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1149: {

1154:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1155:   snes->iter = iter;
1156:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1157:   return(0);
1158: }

1162: /*@
1163:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1164:    attempted by the nonlinear solver.

1166:    Not Collective

1168:    Input Parameter:
1169: .  snes - SNES context

1171:    Output Parameter:
1172: .  nfails - number of unsuccessful steps attempted

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

1177:    Level: intermediate

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

1181: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1182:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1183: @*/
1184: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1185: {
1189:   *nfails = snes->numFailures;
1190:   return(0);
1191: }

1195: /*@
1196:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1197:    attempted by the nonlinear solver before it gives up.

1199:    Not Collective

1201:    Input Parameters:
1202: +  snes     - SNES context
1203: -  maxFails - maximum of unsuccessful steps

1205:    Level: intermediate

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

1209: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1210:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1211: @*/
1212: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1213: {
1216:   snes->maxFailures = maxFails;
1217:   return(0);
1218: }

1222: /*@
1223:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1224:    attempted by the nonlinear solver before it gives up.

1226:    Not Collective

1228:    Input Parameter:
1229: .  snes     - SNES context

1231:    Output Parameter:
1232: .  maxFails - maximum of unsuccessful steps

1234:    Level: intermediate

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

1238: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1239:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1241: @*/
1242: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1243: {
1247:   *maxFails = snes->maxFailures;
1248:   return(0);
1249: }

1253: /*@
1254:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1255:      done by SNES.

1257:    Not Collective

1259:    Input Parameter:
1260: .  snes     - SNES context

1262:    Output Parameter:
1263: .  nfuncs - number of evaluations

1265:    Level: intermediate

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

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

1271: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1272: @*/
1273: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1274: {
1278:   *nfuncs = snes->nfuncs;
1279:   return(0);
1280: }

1284: /*@
1285:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1286:    linear solvers.

1288:    Not Collective

1290:    Input Parameter:
1291: .  snes - SNES context

1293:    Output Parameter:
1294: .  nfails - number of failed solves

1296:    Level: intermediate

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

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

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

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

1319: /*@
1320:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1321:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1323:    Logically Collective on SNES

1325:    Input Parameters:
1326: +  snes     - SNES context
1327: -  maxFails - maximum allowed linear solve failures

1329:    Level: intermediate

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

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

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

1338: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1339: @*/
1340: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1341: {
1345:   snes->maxLinearSolveFailures = maxFails;
1346:   return(0);
1347: }

1351: /*@
1352:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1353:      are allowed before SNES terminates

1355:    Not Collective

1357:    Input Parameter:
1358: .  snes     - SNES context

1360:    Output Parameter:
1361: .  maxFails - maximum of unsuccessful solves allowed

1363:    Level: intermediate

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

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

1369: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1370: @*/
1371: PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1372: {
1376:   *maxFails = snes->maxLinearSolveFailures;
1377:   return(0);
1378: }

1382: /*@
1383:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1384:    used by the nonlinear solver.

1386:    Not Collective

1388:    Input Parameter:
1389: .  snes - SNES context

1391:    Output Parameter:
1392: .  lits - number of linear iterations

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

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

1400:    Level: intermediate

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

1404: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1405: @*/
1406: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1407: {
1411:   *lits = snes->linear_its;
1412:   return(0);
1413: }

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

1421:    Logically Collective on SNES

1423:    Input Parameter:
1424: +  snes - SNES context
1425: -  reset - whether to reset the counters or not

1427:    Notes:
1428:    This defaults to PETSC_TRUE

1430:    Level: developer

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

1434: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1435: @*/
1436: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1437: {
1441:   snes->counters_reset = reset;
1442:   return(0);
1443: }


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

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

1453:    Input Parameters:
1454: +  snes - the SNES context
1455: -  ksp - the KSP context

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

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

1464:    Level: developer

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

1468: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1469: @*/
1470: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1471: {

1478:   PetscObjectReference((PetscObject)ksp);
1479:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1480:   snes->ksp = ksp;
1481:   return(0);
1482: }

1484: /* -----------------------------------------------------------*/
1487: /*@
1488:    SNESCreate - Creates a nonlinear solver context.

1490:    Collective on MPI_Comm

1492:    Input Parameters:
1493: .  comm - MPI communicator

1495:    Output Parameter:
1496: .  outsnes - the new SNES context

1498:    Options Database Keys:
1499: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1500:                and no preconditioning matrix
1501: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1502:                products, and a user-provided preconditioning matrix
1503:                as set by SNESSetJacobian()
1504: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1506:    Level: beginner

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

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

1512: @*/
1513: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1514: {
1516:   SNES           snes;
1517:   SNESKSPEW      *kctx;

1521:   *outsnes = NULL;
1522:   SNESInitializePackage();

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

1526:   snes->ops->converged    = SNESConvergedDefault;
1527:   snes->usesksp           = PETSC_TRUE;
1528:   snes->tolerancesset     = PETSC_FALSE;
1529:   snes->max_its           = 50;
1530:   snes->max_funcs         = 10000;
1531:   snes->norm              = 0.0;
1532:   snes->normschedule      = SNES_NORM_ALWAYS;
1533:   snes->functype          = SNES_FUNCTION_DEFAULT;
1534: #if defined(PETSC_USE_REAL_SINGLE)
1535:   snes->rtol              = 1.e-5;
1536: #else
1537:   snes->rtol              = 1.e-8;
1538: #endif
1539:   snes->ttol              = 0.0;
1540: #if defined(PETSC_USE_REAL_SINGLE)
1541:   snes->abstol            = 1.e-25;
1542: #else
1543:   snes->abstol            = 1.e-50;
1544: #endif
1545: #if defined(PETSC_USE_REAL_SINGLE)
1546:   snes->stol              = 1.e-5;
1547: #else
1548:   snes->stol              = 1.e-8;
1549: #endif
1550: #if defined(PETSC_USE_REAL_SINGLE)
1551:   snes->deltatol          = 1.e-6;
1552: #else
1553:   snes->deltatol          = 1.e-12;
1554: #endif
1555:   snes->divtol            = 1.e4;
1556:   snes->rnorm0            = 0;
1557:   snes->nfuncs            = 0;
1558:   snes->numFailures       = 0;
1559:   snes->maxFailures       = 1;
1560:   snes->linear_its        = 0;
1561:   snes->lagjacobian       = 1;
1562:   snes->jac_iter          = 0;
1563:   snes->lagjac_persist    = PETSC_FALSE;
1564:   snes->lagpreconditioner = 1;
1565:   snes->pre_iter          = 0;
1566:   snes->lagpre_persist    = PETSC_FALSE;
1567:   snes->numbermonitors    = 0;
1568:   snes->data              = 0;
1569:   snes->setupcalled       = PETSC_FALSE;
1570:   snes->ksp_ewconv        = PETSC_FALSE;
1571:   snes->nwork             = 0;
1572:   snes->work              = 0;
1573:   snes->nvwork            = 0;
1574:   snes->vwork             = 0;
1575:   snes->conv_hist_len     = 0;
1576:   snes->conv_hist_max     = 0;
1577:   snes->conv_hist         = NULL;
1578:   snes->conv_hist_its     = NULL;
1579:   snes->conv_hist_reset   = PETSC_TRUE;
1580:   snes->counters_reset    = PETSC_TRUE;
1581:   snes->vec_func_init_set = PETSC_FALSE;
1582:   snes->reason            = SNES_CONVERGED_ITERATING;
1583:   snes->pcside            = PC_RIGHT;

1585:   snes->mf          = PETSC_FALSE;
1586:   snes->mf_operator = PETSC_FALSE;
1587:   snes->mf_version  = 1;

1589:   snes->numLinearSolveFailures = 0;
1590:   snes->maxLinearSolveFailures = 1;

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

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

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

1600:   snes->kspconvctx  = (void*)kctx;
1601:   kctx->version     = 2;
1602:   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1603:                              this was too large for some test cases */
1604:   kctx->rtol_last   = 0.0;
1605:   kctx->rtol_max    = .9;
1606:   kctx->gamma       = 1.0;
1607:   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
1608:   kctx->alpha2      = kctx->alpha;
1609:   kctx->threshold   = .1;
1610:   kctx->lresid_last = 0.0;
1611:   kctx->norm_last   = 0.0;

1613:   *outsnes = snes;
1614:   return(0);
1615: }

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

1620:      Synopsis:
1621:      #include "petscsnes.h"
1622:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1624:      Input Parameters:
1625: +     snes - the SNES context
1626: .     x    - state at which to evaluate residual
1627: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1629:      Output Parameter:
1630: .     f  - vector to put residual (function value)

1632:    Level: intermediate

1634: .seealso:   SNESSetFunction(), SNESGetFunction()
1635: M*/

1639: /*@C
1640:    SNESSetFunction - Sets the function evaluation routine and function
1641:    vector for use by the SNES routines in solving systems of nonlinear
1642:    equations.

1644:    Logically Collective on SNES

1646:    Input Parameters:
1647: +  snes - the SNES context
1648: .  r - vector to store function value
1649: .  f - function evaluation routine; see SNESFunction for calling sequence details
1650: -  ctx - [optional] user-defined context for private data for the
1651:          function evaluation routine (may be NULL)

1653:    Notes:
1654:    The Newton-like methods typically solve linear systems of the form
1655: $      f'(x) x = -f(x),
1656:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1658:    Level: beginner

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

1662: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1663: @*/
1664: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1665: {
1667:   DM             dm;

1671:   if (r) {
1674:     PetscObjectReference((PetscObject)r);
1675:     VecDestroy(&snes->vec_func);

1677:     snes->vec_func = r;
1678:   }
1679:   SNESGetDM(snes,&dm);
1680:   DMSNESSetFunction(dm,f,ctx);
1681:   return(0);
1682: }


1687: /*@C
1688:    SNESSetInitialFunction - Sets the function vector to be used as the
1689:    function norm at the initialization of the method.  In some
1690:    instances, the user has precomputed the function before calling
1691:    SNESSolve.  This function allows one to avoid a redundant call
1692:    to SNESComputeFunction in that case.

1694:    Logically Collective on SNES

1696:    Input Parameters:
1697: +  snes - the SNES context
1698: -  f - vector to store function value

1700:    Notes:
1701:    This should not be modified during the solution procedure.

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

1705:    Level: developer

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

1709: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1710: @*/
1711: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1712: {
1714:   Vec            vec_func;

1720:   if (snes->pcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1721:     snes->vec_func_init_set = PETSC_FALSE;
1722:     return(0);
1723:   }
1724:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1725:   VecCopy(f, vec_func);

1727:   snes->vec_func_init_set = PETSC_TRUE;
1728:   return(0);
1729: }

1733: /*@
1734:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1735:    of the SNES method.

1737:    Logically Collective on SNES

1739:    Input Parameters:
1740: +  snes - the SNES context
1741: -  normschedule - the frequency of norm computation

1743:    Options Database Key:
1744: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1755:    Level: developer

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

1759: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1760: @*/
1761: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1762: {
1765:   snes->normschedule = normschedule;
1766:   return(0);
1767: }


1772: /*@
1773:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1774:    of the SNES method.

1776:    Logically Collective on SNES

1778:    Input Parameters:
1779: +  snes - the SNES context
1780: -  normschedule - the type of the norm used

1782:    Level: advanced

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

1786: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1787: @*/
1788: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1789: {
1792:   *normschedule = snes->normschedule;
1793:   return(0);
1794: }


1799: /*@
1800:   SNESSetFunctionNorm - Sets the last computed residual norm.

1802:   Logically Collective on SNES

1804:   Input Parameters:
1805: + snes - the SNES context

1807: - normschedule - the frequency of norm computation

1809:   Level: developer

1811: .keywords: SNES, nonlinear, set, function, norm, type
1812: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1813: @*/
1814: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1815: {
1818:   snes->norm = norm;
1819:   return(0);
1820: }

1824: /*@
1825:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1827:   Not Collective

1829:   Input Parameter:
1830: . snes - the SNES context

1832:   Output Parameter:
1833: . norm - the last computed residual norm

1835:   Level: developer

1837: .keywords: SNES, nonlinear, set, function, norm, type
1838: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1839: @*/
1840: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1841: {
1845:   *norm = snes->norm;
1846:   return(0);
1847: }

1851: /*@C
1852:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1853:    of the SNES method.

1855:    Logically Collective on SNES

1857:    Input Parameters:
1858: +  snes - the SNES context
1859: -  normschedule - the frequency of norm computation

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

1870:    Level: developer

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

1874: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1875: @*/
1876: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1877: {
1880:   snes->functype = type;
1881:   return(0);
1882: }


1887: /*@C
1888:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1889:    of the SNES method.

1891:    Logically Collective on SNES

1893:    Input Parameters:
1894: +  snes - the SNES context
1895: -  normschedule - the type of the norm used

1897:    Level: advanced

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

1901: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1902: @*/
1903: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
1904: {
1907:   *type = snes->functype;
1908:   return(0);
1909: }

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

1914:      Synopsis:
1915:      #include <petscsnes.h>
1916: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1918: +  X   - solution vector
1919: .  B   - RHS vector
1920: -  ctx - optional user-defined Gauss-Seidel context

1922:    Level: intermediate

1924: .seealso:   SNESSetNGS(), SNESGetNGS()
1925: M*/

1929: /*@C
1930:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1931:    use with composed nonlinear solvers.

1933:    Input Parameters:
1934: +  snes   - the SNES context
1935: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
1936: -  ctx    - [optional] user-defined context for private data for the
1937:             smoother evaluation routine (may be NULL)

1939:    Notes:
1940:    The NGS routines are used by the composed nonlinear solver to generate
1941:     a problem appropriate update to the solution, particularly FAS.

1943:    Level: intermediate

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

1947: .seealso: SNESGetFunction(), SNESComputeNGS()
1948: @*/
1949: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1950: {
1952:   DM             dm;

1956:   SNESGetDM(snes,&dm);
1957:   DMSNESSetNGS(dm,f,ctx);
1958:   return(0);
1959: }

1963: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1964: {
1966:   DM             dm;
1967:   DMSNES         sdm;

1970:   SNESGetDM(snes,&dm);
1971:   DMGetDMSNES(dm,&sdm);
1972:   /*  A(x)*x - b(x) */
1973:   if (sdm->ops->computepfunction) {
1974:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
1975:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");

1977:   if (sdm->ops->computepjacobian) {
1978:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
1979:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard matrix.");
1980:   VecScale(f,-1.0);
1981:   MatMultAdd(snes->jacobian,x,f,f);
1982:   return(0);
1983: }

1987: PETSC_EXTERN PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
1988: {
1990:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
1991:   return(0);
1992: }

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

1999:    Logically Collective on SNES

2001:    Input Parameters:
2002: +  snes - the SNES context
2003: .  r - vector to store function value
2004: .  b - function evaluation routine
2005: .  Amat - matrix with which A(x) x - b(x) is to be computed
2006: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2007: .  J  - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
2008: -  ctx - [optional] user-defined context for private data for the
2009:          function evaluation routine (may be NULL)

2011:    Notes:
2012:     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
2013:     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.

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

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

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

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

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

2029:    Level: intermediate

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

2033: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2034: @*/
2035: 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)
2036: {
2038:   DM             dm;

2042:   SNESGetDM(snes, &dm);
2043:   DMSNESSetPicard(dm,b,J,ctx);
2044:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2045:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2046:   return(0);
2047: }

2051: /*@C
2052:    SNESGetPicard - Returns the context for the Picard iteration

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

2056:    Input Parameter:
2057: .  snes - the SNES context

2059:    Output Parameter:
2060: +  r - the function (or NULL)
2061: .  f - the function (or NULL); see SNESFunction for calling sequence details
2062: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2063: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2064: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2065: -  ctx - the function context (or NULL)

2067:    Level: advanced

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

2071: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2072: @*/
2073: 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)
2074: {
2076:   DM             dm;

2080:   SNESGetFunction(snes,r,NULL,NULL);
2081:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2082:   SNESGetDM(snes,&dm);
2083:   DMSNESGetPicard(dm,f,J,ctx);
2084:   return(0);
2085: }

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

2092:    Logically Collective on SNES

2094:    Input Parameters:
2095: +  snes - the SNES context
2096: .  func - function evaluation routine
2097: -  ctx - [optional] user-defined context for private data for the
2098:          function evaluation routine (may be NULL)

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

2103: .  f - function vector
2104: -  ctx - optional user-defined function context

2106:    Level: intermediate

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

2110: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2111: @*/
2112: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2113: {
2116:   if (func) snes->ops->computeinitialguess = func;
2117:   if (ctx)  snes->initialguessP            = ctx;
2118:   return(0);
2119: }

2121: /* --------------------------------------------------------------- */
2124: /*@C
2125:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2126:    it assumes a zero right hand side.

2128:    Logically Collective on SNES

2130:    Input Parameter:
2131: .  snes - the SNES context

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

2136:    Level: intermediate

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

2140: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2141: @*/
2142: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2143: {
2147:   *rhs = snes->vec_rhs;
2148:   return(0);
2149: }

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

2156:    Collective on SNES

2158:    Input Parameters:
2159: +  snes - the SNES context
2160: -  x - input vector

2162:    Output Parameter:
2163: .  y - function vector, as set by SNESSetFunction()

2165:    Notes:
2166:    SNESComputeFunction() is typically used within nonlinear solvers
2167:    implementations, so most users would not generally call this routine
2168:    themselves.

2170:    Level: developer

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

2174: .seealso: SNESSetFunction(), SNESGetFunction()
2175: @*/
2176: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2177: {
2179:   DM             dm;
2180:   DMSNES         sdm;

2188:   VecValidValues(x,2,PETSC_TRUE);

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

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

2226:    Collective on SNES

2228:    Input Parameters:
2229: +  snes - the SNES context
2230: .  x - input vector
2231: -  b - rhs vector

2233:    Output Parameter:
2234: .  x - new solution vector

2236:    Notes:
2237:    SNESComputeNGS() is typically used within composed nonlinear solver
2238:    implementations, so most users would not generally call this routine
2239:    themselves.

2241:    Level: developer

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

2245: .seealso: SNESSetNGS(), SNESComputeFunction()
2246: @*/
2247: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2248: {
2250:   DM             dm;
2251:   DMSNES         sdm;

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

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

2279:    Collective on SNES and Mat

2281:    Input Parameters:
2282: +  snes - the SNES context
2283: -  x - input vector

2285:    Output Parameters:
2286: +  A - Jacobian matrix
2287: -  B - optional preconditioning matrix

2289:   Options Database Keys:
2290: +    -snes_lag_preconditioner <lag>
2291: .    -snes_lag_jacobian <lag>
2292: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2293: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2294: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2295: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2296: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2297: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2298: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2299: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2300: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2301: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2302: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2305:    Notes:
2306:    Most users should not need to explicitly call this routine, as it
2307:    is used internally within the nonlinear solvers.

2309:    Level: developer

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

2313: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2314: @*/
2315: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2316: {
2318:   PetscBool      flag;
2319:   DM             dm;
2320:   DMSNES         sdm;
2321:   KSP            ksp;

2327:   VecValidValues(X,2,PETSC_TRUE);
2328:   SNESGetDM(snes,&dm);
2329:   DMGetDMSNES(dm,&sdm);

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

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

2335:   if (snes->lagjacobian == -2) {
2336:     snes->lagjacobian = -1;

2338:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2339:   } else if (snes->lagjacobian == -1) {
2340:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2341:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2342:     if (flag) {
2343:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2344:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2345:     }
2346:     return(0);
2347:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2348:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2349:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2350:     if (flag) {
2351:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2352:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2353:     }
2354:     return(0);
2355:   }
2356:   if (snes->pc && snes->pcside == PC_LEFT) {
2357:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2358:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2359:       return(0);
2360:   }

2362:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2363:   VecLockPush(X);
2364:   PetscStackPush("SNES user Jacobian function");
2365:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2366:   PetscStackPop;
2367:   VecLockPop(X);
2368:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2370:   /* the next line ensures that snes->ksp exists */
2371:   SNESGetKSP(snes,&ksp);
2372:   if (snes->lagpreconditioner == -2) {
2373:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2374:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2375:     snes->lagpreconditioner = -1;
2376:   } else if (snes->lagpreconditioner == -1) {
2377:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2378:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2379:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2380:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2381:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2382:   } else {
2383:     PetscInfo(snes,"Rebuilding preconditioner\n");
2384:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2385:   }

2387:   /* make sure user returned a correct Jacobian and preconditioner */
2390:   {
2391:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2392:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2393:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2394:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2395:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2396:     if (flag || flag_draw || flag_contour) {
2397:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2398:       PetscViewer  vdraw,vstdout;
2399:       PetscBool    flg;
2400:       if (flag_operator) {
2401:         MatComputeExplicitOperator(A,&Bexp_mine);
2402:         Bexp = Bexp_mine;
2403:       } else {
2404:         /* See if the preconditioning matrix can be viewed and added directly */
2405:         PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2406:         if (flg) Bexp = B;
2407:         else {
2408:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2409:           MatComputeExplicitOperator(B,&Bexp_mine);
2410:           Bexp = Bexp_mine;
2411:         }
2412:       }
2413:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2414:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2415:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2416:       if (flag_draw || flag_contour) {
2417:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2418:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2419:       } else vdraw = NULL;
2420:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2421:       if (flag) {MatView(Bexp,vstdout);}
2422:       if (vdraw) {MatView(Bexp,vdraw);}
2423:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2424:       if (flag) {MatView(FDexp,vstdout);}
2425:       if (vdraw) {MatView(FDexp,vdraw);}
2426:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2427:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2428:       if (flag) {MatView(FDexp,vstdout);}
2429:       if (vdraw) {              /* Always use contour for the difference */
2430:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2431:         MatView(FDexp,vdraw);
2432:         PetscViewerPopFormat(vdraw);
2433:       }
2434:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2435:       PetscViewerDestroy(&vdraw);
2436:       MatDestroy(&Bexp_mine);
2437:       MatDestroy(&FDexp);
2438:     }
2439:   }
2440:   {
2441:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2442:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2443:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2444:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2445:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2446:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2447:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2448:     if (flag_threshold) {
2449:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2450:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2451:     }
2452:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2453:       Mat            Bfd;
2454:       PetscViewer    vdraw,vstdout;
2455:       MatColoring    coloring;
2456:       ISColoring     iscoloring;
2457:       MatFDColoring  matfdcoloring;
2458:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2459:       void           *funcctx;
2460:       PetscReal      norm1,norm2,normmax;

2462:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2463:       MatColoringCreate(Bfd,&coloring);
2464:       MatColoringSetType(coloring,MATCOLORINGSL);
2465:       MatColoringSetFromOptions(coloring);
2466:       MatColoringApply(coloring,&iscoloring);
2467:       MatColoringDestroy(&coloring);
2468:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2469:       MatFDColoringSetFromOptions(matfdcoloring);
2470:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2471:       ISColoringDestroy(&iscoloring);

2473:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2474:       SNESGetFunction(snes,NULL,&func,&funcctx);
2475:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2476:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2477:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2478:       MatFDColoringSetFromOptions(matfdcoloring);
2479:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2480:       MatFDColoringDestroy(&matfdcoloring);

2482:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2483:       if (flag_draw || flag_contour) {
2484:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2485:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2486:       } else vdraw = NULL;
2487:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2488:       if (flag_display) {MatView(B,vstdout);}
2489:       if (vdraw) {MatView(B,vdraw);}
2490:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2491:       if (flag_display) {MatView(Bfd,vstdout);}
2492:       if (vdraw) {MatView(Bfd,vdraw);}
2493:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2494:       MatNorm(Bfd,NORM_1,&norm1);
2495:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2496:       MatNorm(Bfd,NORM_MAX,&normmax);
2497:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2498:       if (flag_display) {MatView(Bfd,vstdout);}
2499:       if (vdraw) {              /* Always use contour for the difference */
2500:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2501:         MatView(Bfd,vdraw);
2502:         PetscViewerPopFormat(vdraw);
2503:       }
2504:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2506:       if (flag_threshold) {
2507:         PetscInt bs,rstart,rend,i;
2508:         MatGetBlockSize(B,&bs);
2509:         MatGetOwnershipRange(B,&rstart,&rend);
2510:         for (i=rstart; i<rend; i++) {
2511:           const PetscScalar *ba,*ca;
2512:           const PetscInt    *bj,*cj;
2513:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2514:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2515:           MatGetRow(B,i,&bn,&bj,&ba);
2516:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2517:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2518:           for (j=0; j<bn; j++) {
2519:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2520:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2521:               maxentrycol = bj[j];
2522:               maxentry    = PetscRealPart(ba[j]);
2523:             }
2524:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2525:               maxdiffcol = bj[j];
2526:               maxdiff    = PetscRealPart(ca[j]);
2527:             }
2528:             if (rdiff > maxrdiff) {
2529:               maxrdiffcol = bj[j];
2530:               maxrdiff    = rdiff;
2531:             }
2532:           }
2533:           if (maxrdiff > 1) {
2534:             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);
2535:             for (j=0; j<bn; j++) {
2536:               PetscReal rdiff;
2537:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2538:               if (rdiff > 1) {
2539:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2540:               }
2541:             }
2542:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2543:           }
2544:           MatRestoreRow(B,i,&bn,&bj,&ba);
2545:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2546:         }
2547:       }
2548:       PetscViewerDestroy(&vdraw);
2549:       MatDestroy(&Bfd);
2550:     }
2551:   }
2552:   return(0);
2553: }

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

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

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

2567:    Level: intermediate

2569: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2570: M*/

2574: /*@C
2575:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2576:    location to store the matrix.

2578:    Logically Collective on SNES and Mat

2580:    Input Parameters:
2581: +  snes - the SNES context
2582: .  Amat - the matrix that defines the (approximate) Jacobian
2583: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2584: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2585: -  ctx - [optional] user-defined context for private data for the
2586:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2588:    Notes:
2589:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2590:    each matrix.

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

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

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

2601:    Level: beginner

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

2605: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J, 
2606:           SNESSetPicard(), SNESJacobianFunction
2607: @*/
2608: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2609: {
2611:   DM             dm;

2619:   SNESGetDM(snes,&dm);
2620:   DMSNESSetJacobian(dm,J,ctx);
2621:   if (Amat) {
2622:     PetscObjectReference((PetscObject)Amat);
2623:     MatDestroy(&snes->jacobian);

2625:     snes->jacobian = Amat;
2626:   }
2627:   if (Pmat) {
2628:     PetscObjectReference((PetscObject)Pmat);
2629:     MatDestroy(&snes->jacobian_pre);

2631:     snes->jacobian_pre = Pmat;
2632:   }
2633:   return(0);
2634: }

2638: /*@C
2639:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2640:    provided context for evaluating the Jacobian.

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

2644:    Input Parameter:
2645: .  snes - the nonlinear solver context

2647:    Output Parameters:
2648: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2649: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2650: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2651: -  ctx - location to stash Jacobian ctx (or NULL)

2653:    Level: advanced

2655: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2656: @*/
2657: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2658: {
2660:   DM             dm;
2661:   DMSNES         sdm;

2665:   if (Amat) *Amat = snes->jacobian;
2666:   if (Pmat) *Pmat = snes->jacobian_pre;
2667:   SNESGetDM(snes,&dm);
2668:   DMGetDMSNES(dm,&sdm);
2669:   if (J) *J = sdm->ops->computejacobian;
2670:   if (ctx) *ctx = sdm->jacobianctx;
2671:   return(0);
2672: }

2676: /*@
2677:    SNESSetUp - Sets up the internal data structures for the later use
2678:    of a nonlinear solver.

2680:    Collective on SNES

2682:    Input Parameters:
2683: .  snes - the SNES context

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

2692:    Level: advanced

2694: .keywords: SNES, nonlinear, setup

2696: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2697: @*/
2698: PetscErrorCode  SNESSetUp(SNES snes)
2699: {
2701:   DM             dm;
2702:   DMSNES         sdm;
2703:   SNESLineSearch linesearch, pclinesearch;
2704:   void           *lsprectx,*lspostctx;
2705:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2706:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2707:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2708:   Vec            f,fpc;
2709:   void           *funcctx;
2710:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2711:   void           *jacctx,*appctx;
2712:   Mat            j,jpre;

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

2718:   if (!((PetscObject)snes)->type_name) {
2719:     SNESSetType(snes,SNESNEWTONLS);
2720:   }

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

2724:   SNESGetDM(snes,&dm);
2725:   DMGetDMSNES(dm,&sdm);
2726:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2727:   if (!sdm->ops->computejacobian) {
2728:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2729:   }
2730:   if (!snes->vec_func) {
2731:     DMCreateGlobalVector(dm,&snes->vec_func);
2732:   }

2734:   if (!snes->ksp) {
2735:     SNESGetKSP(snes, &snes->ksp);
2736:   }

2738:   if (!snes->linesearch) {
2739:     SNESGetLineSearch(snes, &snes->linesearch);
2740:   }
2741:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2743:   if (snes->pc && (snes->pcside == PC_LEFT)) {
2744:     snes->mf          = PETSC_TRUE;
2745:     snes->mf_operator = PETSC_FALSE;
2746:   }

2748:   if (snes->pc) {
2749:     /* copy the DM over */
2750:     SNESGetDM(snes,&dm);
2751:     SNESSetDM(snes->pc,dm);

2753:     SNESGetFunction(snes,&f,&func,&funcctx);
2754:     VecDuplicate(f,&fpc);
2755:     SNESSetFunction(snes->pc,fpc,func,funcctx);
2756:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2757:     SNESSetJacobian(snes->pc,j,jpre,jac,jacctx);
2758:     SNESGetApplicationContext(snes,&appctx);
2759:     SNESSetApplicationContext(snes->pc,appctx);
2760:     VecDestroy(&fpc);

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

2765:     /* default to 1 iteration */
2766:     SNESSetTolerances(snes->pc,0.0,0.0,0.0,1,snes->pc->max_funcs);
2767:     if (snes->pcside==PC_RIGHT) {
2768:       SNESSetNormSchedule(snes->pc,SNES_NORM_FINAL_ONLY);
2769:     } else {
2770:       SNESSetNormSchedule(snes->pc,SNES_NORM_NONE);
2771:     }
2772:     SNESSetFromOptions(snes->pc);

2774:     /* copy the line search context over */
2775:     SNESGetLineSearch(snes,&linesearch);
2776:     SNESGetLineSearch(snes->pc,&pclinesearch);
2777:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2778:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2779:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2780:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2781:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2782:   }
2783:   if (snes->mf) {
2784:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2785:   }
2786:   if (snes->ops->usercompute && !snes->user) {
2787:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2788:   }

2790:   snes->jac_iter = 0;
2791:   snes->pre_iter = 0;

2793:   if (snes->ops->setup) {
2794:     (*snes->ops->setup)(snes);
2795:   }

2797:   if (snes->pc && (snes->pcside == PC_LEFT)) {
2798:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2799:       SNESGetLineSearch(snes,&linesearch);
2800:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2801:     }
2802:   }

2804:   snes->setupcalled = PETSC_TRUE;
2805:   return(0);
2806: }

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

2813:    Collective on SNES

2815:    Input Parameter:
2816: .  snes - iterative context obtained from SNESCreate()

2818:    Level: intermediate

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

2822: .keywords: SNES, destroy

2824: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
2825: @*/
2826: PetscErrorCode  SNESReset(SNES snes)
2827: {

2832:   if (snes->ops->userdestroy && snes->user) {
2833:     (*snes->ops->userdestroy)((void**)&snes->user);
2834:     snes->user = NULL;
2835:   }
2836:   if (snes->pc) {
2837:     SNESReset(snes->pc);
2838:   }

2840:   if (snes->ops->reset) {
2841:     (*snes->ops->reset)(snes);
2842:   }
2843:   if (snes->ksp) {
2844:     KSPReset(snes->ksp);
2845:   }

2847:   if (snes->linesearch) {
2848:     SNESLineSearchReset(snes->linesearch);
2849:   }

2851:   VecDestroy(&snes->vec_rhs);
2852:   VecDestroy(&snes->vec_sol);
2853:   VecDestroy(&snes->vec_sol_update);
2854:   VecDestroy(&snes->vec_func);
2855:   MatDestroy(&snes->jacobian);
2856:   MatDestroy(&snes->jacobian_pre);
2857:   VecDestroyVecs(snes->nwork,&snes->work);
2858:   VecDestroyVecs(snes->nvwork,&snes->vwork);

2860:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

2862:   snes->nwork       = snes->nvwork = 0;
2863:   snes->setupcalled = PETSC_FALSE;
2864:   return(0);
2865: }

2869: /*@
2870:    SNESDestroy - Destroys the nonlinear solver context that was created
2871:    with SNESCreate().

2873:    Collective on SNES

2875:    Input Parameter:
2876: .  snes - the SNES context

2878:    Level: beginner

2880: .keywords: SNES, nonlinear, destroy

2882: .seealso: SNESCreate(), SNESSolve()
2883: @*/
2884: PetscErrorCode  SNESDestroy(SNES *snes)
2885: {

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

2893:   SNESReset((*snes));
2894:   SNESDestroy(&(*snes)->pc);

2896:   /* if memory was published with SAWs then destroy it */
2897:   PetscObjectSAWsViewOff((PetscObject)*snes);
2898:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

2900:   DMDestroy(&(*snes)->dm);
2901:   KSPDestroy(&(*snes)->ksp);
2902:   SNESLineSearchDestroy(&(*snes)->linesearch);

2904:   PetscFree((*snes)->kspconvctx);
2905:   if ((*snes)->ops->convergeddestroy) {
2906:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
2907:   }
2908:   if ((*snes)->conv_malloc) {
2909:     PetscFree((*snes)->conv_hist);
2910:     PetscFree((*snes)->conv_hist_its);
2911:   }
2912:   SNESMonitorCancel((*snes));
2913:   PetscHeaderDestroy(snes);
2914:   return(0);
2915: }

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

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

2924:    Logically Collective on SNES

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

2931:    Options Database Keys:
2932: .    -snes_lag_preconditioner <lag>

2934:    Notes:
2935:    The default is 1
2936:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
2937:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

2939:    Level: intermediate

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

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

2945: @*/
2946: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
2947: {
2950:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
2951:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
2953:   snes->lagpreconditioner = lag;
2954:   return(0);
2955: }

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

2962:    Logically Collective on SNES

2964:    Input Parameters:
2965: +  snes - the SNES context
2966: -  steps - the number of refinements to do, defaults to 0

2968:    Options Database Keys:
2969: .    -snes_grid_sequence <steps>

2971:    Level: intermediate

2973:    Notes:
2974:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2980: @*/
2981: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
2982: {
2986:   snes->gridsequence = steps;
2987:   return(0);
2988: }

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

2995:    Logically Collective on SNES

2997:    Input Parameter:
2998: .  snes - the SNES context

3000:    Output Parameter:
3001: .  steps - the number of refinements to do, defaults to 0

3003:    Options Database Keys:
3004: .    -snes_grid_sequence <steps>

3006:    Level: intermediate

3008:    Notes:
3009:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

3015: @*/
3016: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3017: {
3020:   *steps = snes->gridsequence;
3021:   return(0);
3022: }

3026: /*@
3027:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3029:    Not Collective

3031:    Input Parameter:
3032: .  snes - the SNES context

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

3038:    Options Database Keys:
3039: .    -snes_lag_preconditioner <lag>

3041:    Notes:
3042:    The default is 1
3043:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3045:    Level: intermediate

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

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

3051: @*/
3052: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3053: {
3056:   *lag = snes->lagpreconditioner;
3057:   return(0);
3058: }

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

3066:    Logically Collective on SNES

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

3073:    Options Database Keys:
3074: .    -snes_lag_jacobian <lag>

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

3082:    Level: intermediate

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

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

3088: @*/
3089: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3090: {
3093:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3094:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3096:   snes->lagjacobian = lag;
3097:   return(0);
3098: }

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

3105:    Not Collective

3107:    Input Parameter:
3108: .  snes - the SNES context

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

3114:    Options Database Keys:
3115: .    -snes_lag_jacobian <lag>

3117:    Notes:
3118:    The default is 1
3119:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3121:    Level: intermediate

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

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

3127: @*/
3128: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3129: {
3132:   *lag = snes->lagjacobian;
3133:   return(0);
3134: }

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

3141:    Logically collective on SNES

3143:    Input Parameter:
3144: +  snes - the SNES context
3145: -   flg - jacobian lagging persists if true

3147:    Options Database Keys:
3148: .    -snes_lag_jacobian_persists <flg>

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

3154:    Level: developer

3156: .keywords: SNES, nonlinear, lag

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

3160: @*/
3161: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3162: {
3166:   snes->lagjac_persist = flg;
3167:   return(0);
3168: }

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

3175:    Logically Collective on SNES

3177:    Input Parameter:
3178: +  snes - the SNES context
3179: -   flg - preconditioner lagging persists if true

3181:    Options Database Keys:
3182: .    -snes_lag_jacobian_persists <flg>

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

3188:    Level: developer

3190: .keywords: SNES, nonlinear, lag

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

3194: @*/
3195: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3196: {
3200:   snes->lagpre_persist = flg;
3201:   return(0);
3202: }

3206: /*@
3207:    SNESSetTolerances - Sets various parameters used in convergence tests.

3209:    Logically Collective on SNES

3211:    Input Parameters:
3212: +  snes - the SNES context
3213: .  abstol - absolute convergence tolerance
3214: .  rtol - relative convergence tolerance
3215: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3216: .  maxit - maximum number of iterations
3217: -  maxf - maximum number of function evaluations

3219:    Options Database Keys:
3220: +    -snes_atol <abstol> - Sets abstol
3221: .    -snes_rtol <rtol> - Sets rtol
3222: .    -snes_stol <stol> - Sets stol
3223: .    -snes_max_it <maxit> - Sets maxit
3224: -    -snes_max_funcs <maxf> - Sets maxf

3226:    Notes:
3227:    The default maximum number of iterations is 50.
3228:    The default maximum number of function evaluations is 1000.

3230:    Level: intermediate

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

3234: .seealso: SNESSetTrustRegionTolerance()
3235: @*/
3236: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3237: {

3246:   if (abstol != PETSC_DEFAULT) {
3247:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3248:     snes->abstol = abstol;
3249:   }
3250:   if (rtol != PETSC_DEFAULT) {
3251:     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);
3252:     snes->rtol = rtol;
3253:   }
3254:   if (stol != PETSC_DEFAULT) {
3255:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3256:     snes->stol = stol;
3257:   }
3258:   if (maxit != PETSC_DEFAULT) {
3259:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3260:     snes->max_its = maxit;
3261:   }
3262:   if (maxf != PETSC_DEFAULT) {
3263:     if (maxf < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be non-negative",maxf);
3264:     snes->max_funcs = maxf;
3265:   }
3266:   snes->tolerancesset = PETSC_TRUE;
3267:   return(0);
3268: }

3272: /*@
3273:    SNESGetTolerances - Gets various parameters used in convergence tests.

3275:    Not Collective

3277:    Input Parameters:
3278: +  snes - the SNES context
3279: .  atol - absolute convergence tolerance
3280: .  rtol - relative convergence tolerance
3281: .  stol -  convergence tolerance in terms of the norm
3282:            of the change in the solution between steps
3283: .  maxit - maximum number of iterations
3284: -  maxf - maximum number of function evaluations

3286:    Notes:
3287:    The user can specify NULL for any parameter that is not needed.

3289:    Level: intermediate

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

3293: .seealso: SNESSetTolerances()
3294: @*/
3295: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3296: {
3299:   if (atol)  *atol  = snes->abstol;
3300:   if (rtol)  *rtol  = snes->rtol;
3301:   if (stol)  *stol  = snes->stol;
3302:   if (maxit) *maxit = snes->max_its;
3303:   if (maxf)  *maxf  = snes->max_funcs;
3304:   return(0);
3305: }

3309: /*@
3310:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3312:    Logically Collective on SNES

3314:    Input Parameters:
3315: +  snes - the SNES context
3316: -  tol - tolerance

3318:    Options Database Key:
3319: .  -snes_trtol <tol> - Sets tol

3321:    Level: intermediate

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

3325: .seealso: SNESSetTolerances()
3326: @*/
3327: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3328: {
3332:   snes->deltatol = tol;
3333:   return(0);
3334: }

3336: /*
3337:    Duplicate the lg monitors for SNES from KSP; for some reason with
3338:    dynamic libraries things don't work under Sun4 if we just use
3339:    macros instead of functions
3340: */
3343: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3344: {

3349:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3350:   return(0);
3351: }

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

3360:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3361:   return(0);
3362: }

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

3368: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3369: {
3370:   PetscDrawLG      lg;
3371:   PetscErrorCode   ierr;
3372:   PetscReal        x,y,per;
3373:   PetscViewer      v = (PetscViewer)monctx;
3374:   static PetscReal prev; /* should be in the context */
3375:   PetscDraw        draw;

3379:   PetscViewerDrawGetDrawLG(v,0,&lg);
3380:   if (!n) {PetscDrawLGReset(lg);}
3381:   PetscDrawLGGetDraw(lg,&draw);
3382:   PetscDrawSetTitle(draw,"Residual norm");
3383:   x    = (PetscReal)n;
3384:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3385:   else y = -15.0;
3386:   PetscDrawLGAddPoint(lg,&x,&y);
3387:   if (n < 20 || !(n % 5) || snes->reason) {
3388:     PetscDrawLGDraw(lg);
3389:     PetscDrawLGSave(lg);
3390:   }

3392:   PetscViewerDrawGetDrawLG(v,1,&lg);
3393:   if (!n) {PetscDrawLGReset(lg);}
3394:   PetscDrawLGGetDraw(lg,&draw);
3395:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3396:    SNESMonitorRange_Private(snes,n,&per);
3397:   x    = (PetscReal)n;
3398:   y    = 100.0*per;
3399:   PetscDrawLGAddPoint(lg,&x,&y);
3400:   if (n < 20 || !(n % 5) || snes->reason) {
3401:     PetscDrawLGDraw(lg);
3402:     PetscDrawLGSave(lg);
3403:   }

3405:   PetscViewerDrawGetDrawLG(v,2,&lg);
3406:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3407:   PetscDrawLGGetDraw(lg,&draw);
3408:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3409:   x    = (PetscReal)n;
3410:   y    = (prev - rnorm)/prev;
3411:   PetscDrawLGAddPoint(lg,&x,&y);
3412:   if (n < 20 || !(n % 5) || snes->reason) {
3413:     PetscDrawLGDraw(lg);
3414:     PetscDrawLGSave(lg);
3415:   }

3417:   PetscViewerDrawGetDrawLG(v,3,&lg);
3418:   if (!n) {PetscDrawLGReset(lg);}
3419:   PetscDrawLGGetDraw(lg,&draw);
3420:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3421:   x    = (PetscReal)n;
3422:   y    = (prev - rnorm)/(prev*per);
3423:   if (n > 2) { /*skip initial crazy value */
3424:     PetscDrawLGAddPoint(lg,&x,&y);
3425:   }
3426:   if (n < 20 || !(n % 5) || snes->reason) {
3427:     PetscDrawLGDraw(lg);
3428:     PetscDrawLGSave(lg);
3429:   }
3430:   prev = rnorm;
3431:   return(0);
3432: }

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

3439:    Collective on SNES

3441:    Input Parameters:
3442: +  snes - nonlinear solver context obtained from SNESCreate()
3443: .  iter - iteration number
3444: -  rnorm - relative norm of the residual

3446:    Notes:
3447:    This routine is called by the SNES implementations.
3448:    It does not typically need to be called by the user.

3450:    Level: developer

3452: .seealso: SNESMonitorSet()
3453: @*/
3454: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3455: {
3457:   PetscInt       i,n = snes->numbermonitors;

3460:   VecLockPush(snes->vec_sol);
3461:   for (i=0; i<n; i++) {
3462:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3463:   }
3464:   VecLockPop(snes->vec_sol);
3465:   return(0);
3466: }

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

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

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

3477: +    snes - the SNES context
3478: .    its - iteration number
3479: .    norm - 2-norm function value (may be estimated)
3480: -    mctx - [optional] monitoring context

3482:    Level: advanced

3484: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3485: M*/

3489: /*@C
3490:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3491:    iteration of the nonlinear solver to display the iteration's
3492:    progress.

3494:    Logically Collective on SNES

3496:    Input Parameters:
3497: +  snes - the SNES context
3498: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3499: .  mctx - [optional] user-defined context for private data for the
3500:           monitor routine (use NULL if no context is desired)
3501: -  monitordestroy - [optional] routine that frees monitor context
3502:           (may be NULL)

3504:    Options Database Keys:
3505: +    -snes_monitor        - sets SNESMonitorDefault()
3506: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3507:                             uses SNESMonitorLGCreate()
3508: -    -snes_monitor_cancel - cancels all monitors that have
3509:                             been hardwired into a code by
3510:                             calls to SNESMonitorSet(), but
3511:                             does not cancel those set via
3512:                             the options database.

3514:    Notes:
3515:    Several different monitoring routines may be set by calling
3516:    SNESMonitorSet() multiple times; all will be called in the
3517:    order in which they were set.

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

3521:    Level: intermediate

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

3525: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3526: @*/
3527: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3528: {
3529:   PetscInt       i;
3531:   PetscBool      identical;

3535:   for (i=0; i<snes->numbermonitors;i++) {
3536:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3537:     if (identical) return(0);
3538:   }
3539:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3540:   snes->monitor[snes->numbermonitors]          = f;
3541:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3542:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3543:   return(0);
3544: }

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

3551:    Logically Collective on SNES

3553:    Input Parameters:
3554: .  snes - the SNES context

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

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

3564:    Level: intermediate

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

3568: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3569: @*/
3570: PetscErrorCode  SNESMonitorCancel(SNES snes)
3571: {
3573:   PetscInt       i;

3577:   for (i=0; i<snes->numbermonitors; i++) {
3578:     if (snes->monitordestroy[i]) {
3579:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3580:     }
3581:   }
3582:   snes->numbermonitors = 0;
3583:   return(0);
3584: }

3586: /*MC
3587:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3593: +    snes - the SNES context
3594: .    it - current iteration (0 is the first and is before any Newton step)
3595: .    cctx - [optional] convergence context
3596: .    reason - reason for convergence/divergence
3597: .    xnorm - 2-norm of current iterate
3598: .    gnorm - 2-norm of current step
3599: -    f - 2-norm of function

3601:    Level: intermediate

3603: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3604: M*/

3608: /*@C
3609:    SNESSetConvergenceTest - Sets the function that is to be used
3610:    to test for convergence of the nonlinear iterative solution.

3612:    Logically Collective on SNES

3614:    Input Parameters:
3615: +  snes - the SNES context
3616: .  SNESConvergenceTestFunction - routine to test for convergence
3617: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3618: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3620:    Level: advanced

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

3624: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3625: @*/
3626: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3627: {

3632:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3633:   if (snes->ops->convergeddestroy) {
3634:     (*snes->ops->convergeddestroy)(snes->cnvP);
3635:   }
3636:   snes->ops->converged        = SNESConvergenceTestFunction;
3637:   snes->ops->convergeddestroy = destroy;
3638:   snes->cnvP                  = cctx;
3639:   return(0);
3640: }

3644: /*@
3645:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3647:    Not Collective

3649:    Input Parameter:
3650: .  snes - the SNES context

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

3656:    Level: intermediate

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

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

3662: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
3663: @*/
3664: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3665: {
3669:   *reason = snes->reason;
3670:   return(0);
3671: }

3675: /*@
3676:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3678:    Not Collective

3680:    Input Parameters:
3681: +  snes - the SNES context
3682: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
3683:             manual pages for the individual convergence tests for complete lists

3685:    Level: intermediate

3687: .keywords: SNES, nonlinear, set, convergence, test
3688: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
3689: @*/
3690: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
3691: {
3694:   snes->reason = reason;
3695:   return(0);
3696: }

3700: /*@
3701:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3703:    Logically Collective on SNES

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

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

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

3721:    Level: intermediate

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

3725: .seealso: SNESGetConvergenceHistory()

3727: @*/
3728: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3729: {

3736:   if (!a) {
3737:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3738:     PetscCalloc1(na,&a);
3739:     PetscCalloc1(na,&its);

3741:     snes->conv_malloc = PETSC_TRUE;
3742:   }
3743:   snes->conv_hist       = a;
3744:   snes->conv_hist_its   = its;
3745:   snes->conv_hist_max   = na;
3746:   snes->conv_hist_len   = 0;
3747:   snes->conv_hist_reset = reset;
3748:   return(0);
3749: }

3751: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3752: #include <engine.h>   /* MATLAB include file */
3753: #include <mex.h>      /* MATLAB include file */

3757: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3758: {
3759:   mxArray   *mat;
3760:   PetscInt  i;
3761:   PetscReal *ar;

3764:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3765:   ar  = (PetscReal*) mxGetData(mat);
3766:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3767:   PetscFunctionReturn(mat);
3768: }
3769: #endif

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

3776:    Not Collective

3778:    Input Parameter:
3779: .  snes - iterative context obtained from SNESCreate()

3781:    Output Parameters:
3782: .  a   - array to hold history
3783: .  its - integer array holds the number of linear iterations (or
3784:          negative if not converged) for each solve.
3785: -  na  - size of a and its

3787:    Notes:
3788:     The calling sequence for this routine in Fortran is
3789: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

3795:    Level: intermediate

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

3799: .seealso: SNESSetConvergencHistory()

3801: @*/
3802: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
3803: {
3806:   if (a)   *a   = snes->conv_hist;
3807:   if (its) *its = snes->conv_hist_its;
3808:   if (na)  *na  = snes->conv_hist_len;
3809:   return(0);
3810: }

3814: /*@C
3815:   SNESSetUpdate - Sets the general-purpose update function called
3816:   at the beginning of every iteration of the nonlinear solve. Specifically
3817:   it is called just before the Jacobian is "evaluated".

3819:   Logically Collective on SNES

3821:   Input Parameters:
3822: . snes - The nonlinear solver context
3823: . func - The function

3825:   Calling sequence of func:
3826: . func (SNES snes, PetscInt step);

3828: . step - The current step of the iteration

3830:   Level: advanced

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

3835: .keywords: SNES, update

3837: .seealso SNESSetJacobian(), SNESSolve()
3838: @*/
3839: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
3840: {
3843:   snes->ops->update = func;
3844:   return(0);
3845: }

3849: /*
3850:    SNESScaleStep_Private - Scales a step so that its length is less than the
3851:    positive parameter delta.

3853:     Input Parameters:
3854: +   snes - the SNES context
3855: .   y - approximate solution of linear system
3856: .   fnorm - 2-norm of current function
3857: -   delta - trust region size

3859:     Output Parameters:
3860: +   gpnorm - predicted function norm at the new point, assuming local
3861:     linearization.  The value is zero if the step lies within the trust
3862:     region, and exceeds zero otherwise.
3863: -   ynorm - 2-norm of the step

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

3869: .keywords: SNES, nonlinear, scale, step
3870: */
3871: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
3872: {
3873:   PetscReal      nrm;
3874:   PetscScalar    cnorm;


3882:   VecNorm(y,NORM_2,&nrm);
3883:   if (nrm > *delta) {
3884:     nrm     = *delta/nrm;
3885:     *gpnorm = (1.0 - nrm)*(*fnorm);
3886:     cnorm   = nrm;
3887:     VecScale(y,cnorm);
3888:     *ynorm  = *delta;
3889:   } else {
3890:     *gpnorm = 0.0;
3891:     *ynorm  = nrm;
3892:   }
3893:   return(0);
3894: }

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

3901:    Collective on SNES

3903:    Parameter:
3904: +  snes - iterative context obtained from SNESCreate()
3905: -  viewer - the viewer to display the reason


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

3911:    Level: beginner

3913: .keywords: SNES, solve, linear system

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

3917: @*/
3918: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
3919: {
3921:   PetscBool      isAscii;

3924:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
3925:   if (isAscii) {
3926:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
3927:     if (snes->reason > 0) {
3928:       if (((PetscObject) snes)->prefix) {
3929:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3930:       } else {
3931:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3932:       }
3933:     } else {
3934:       if (((PetscObject) snes)->prefix) {
3935:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3936:       } else {
3937:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3938:       }
3939:     }
3940:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
3941:   }
3942:   return(0);
3943: }

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

3950:   Collective on SNES

3952:   Input Parameters:
3953: . snes   - the SNES object

3955:   Level: intermediate

3957: @*/
3958: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
3959: {
3960:   PetscErrorCode    ierr;
3961:   PetscViewer       viewer;
3962:   PetscBool         flg;
3963:   static PetscBool  incall = PETSC_FALSE;
3964:   PetscViewerFormat format;

3967:   if (incall) return(0);
3968:   incall = PETSC_TRUE;
3969:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
3970:   if (flg) {
3971:     PetscViewerPushFormat(viewer,format);
3972:     SNESReasonView(snes,viewer);
3973:     PetscViewerPopFormat(viewer);
3974:     PetscViewerDestroy(&viewer);
3975:   }
3976:   incall = PETSC_FALSE;
3977:   return(0);
3978: }

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

3986:    Collective on SNES

3988:    Input Parameters:
3989: +  snes - the SNES context
3990: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
3991: -  x - the solution vector.

3993:    Notes:
3994:    The user should initialize the vector,x, with the initial guess
3995:    for the nonlinear solve prior to calling SNESSolve.  In particular,
3996:    to employ an initial guess of zero, the user should explicitly set
3997:    this vector to zero by calling VecSet().

3999:    Level: beginner

4001: .keywords: SNES, nonlinear, solve

4003: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4004: @*/
4005: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4006: {
4007:   PetscErrorCode    ierr;
4008:   PetscBool         flg;
4009:   PetscInt          grid;
4010:   Vec               xcreated = NULL;
4011:   DM                dm;


4020:   if (!x) {
4021:     SNESGetDM(snes,&dm);
4022:     DMCreateGlobalVector(dm,&xcreated);
4023:     x    = xcreated;
4024:   }
4025:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4030:     /* set solution vector */
4031:     if (!grid) {PetscObjectReference((PetscObject)x);}
4032:     VecDestroy(&snes->vec_sol);
4033:     snes->vec_sol = x;
4034:     SNESGetDM(snes,&dm);

4036:     /* set affine vector if provided */
4037:     if (b) { PetscObjectReference((PetscObject)b); }
4038:     VecDestroy(&snes->vec_rhs);
4039:     snes->vec_rhs = b;

4041:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4042:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4043:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4044:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4045:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4046:     }
4047:     DMShellSetGlobalVector(dm,snes->vec_sol);
4048:     SNESSetUp(snes);

4050:     if (!grid) {
4051:       if (snes->ops->computeinitialguess) {
4052:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4053:       }
4054:     }

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

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

4065:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4066:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4072:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4073:     if (snes->reason < 0) break;
4074:     if (grid <  snes->gridsequence) {
4075:       DM  fine;
4076:       Vec xnew;
4077:       Mat interp;

4079:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4080:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4081:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4082:       DMCreateGlobalVector(fine,&xnew);
4083:       MatInterpolate(interp,x,xnew);
4084:       DMInterpolate(snes->dm,interp,fine);
4085:       MatDestroy(&interp);
4086:       x    = xnew;

4088:       SNESReset(snes);
4089:       SNESSetDM(snes,fine);
4090:       DMDestroy(&fine);
4091:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4092:     }
4093:   }
4094:   SNESViewFromOptions(snes,NULL,"-snes_view");
4095:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4097:   VecDestroy(&xcreated);
4098:   PetscObjectSAWsBlock((PetscObject)snes);
4099:   return(0);
4100: }

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

4106: /*@C
4107:    SNESSetType - Sets the method for the nonlinear solver.

4109:    Collective on SNES

4111:    Input Parameters:
4112: +  snes - the SNES context
4113: -  type - a known method

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

4119:    Notes:
4120:    See "petsc/include/petscsnes.h" for available methods (for instance)
4121: +    SNESNEWTONLS - Newton's method with line search
4122:      (systems of nonlinear equations)
4123: .    SNESNEWTONTR - Newton's method with trust region
4124:      (systems of nonlinear equations)

4126:   Normally, it is best to use the SNESSetFromOptions() command and then
4127:   set the SNES solver type from the options database rather than by using
4128:   this routine.  Using the options database provides the user with
4129:   maximum flexibility in evaluating the many nonlinear solvers.
4130:   The SNESSetType() routine is provided for those situations where it
4131:   is necessary to set the nonlinear solver independently of the command
4132:   line or options database.  This might be the case, for example, when
4133:   the choice of solver changes during the execution of the program,
4134:   and the user's application is taking responsibility for choosing the
4135:   appropriate method.

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

4140:   Level: intermediate

4142: .keywords: SNES, set, type

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

4146: @*/
4147: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4148: {
4149:   PetscErrorCode ierr,(*r)(SNES);
4150:   PetscBool      match;


4156:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4157:   if (match) return(0);

4159:    PetscFunctionListFind(SNESList,type,&r);
4160:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4161:   /* Destroy the previous private SNES context */
4162:   if (snes->ops->destroy) {
4163:     (*(snes)->ops->destroy)(snes);
4164:     snes->ops->destroy = NULL;
4165:   }
4166:   /* Reinitialize function pointers in SNESOps structure */
4167:   snes->ops->setup          = 0;
4168:   snes->ops->solve          = 0;
4169:   snes->ops->view           = 0;
4170:   snes->ops->setfromoptions = 0;
4171:   snes->ops->destroy        = 0;
4172:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4173:   snes->setupcalled = PETSC_FALSE;

4175:   PetscObjectChangeTypeName((PetscObject)snes,type);
4176:   (*r)(snes);
4177:   return(0);
4178: }

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

4185:    Not Collective

4187:    Input Parameter:
4188: .  snes - nonlinear solver context

4190:    Output Parameter:
4191: .  type - SNES method (a character string)

4193:    Level: intermediate

4195: .keywords: SNES, nonlinear, get, type, name
4196: @*/
4197: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4198: {
4202:   *type = ((PetscObject)snes)->type_name;
4203:   return(0);
4204: }

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

4211:   Logically Collective on SNES and Vec

4213:   Input Parameters:
4214: + snes - the SNES context obtained from SNESCreate()
4215: - u    - the solution vector

4217:   Level: beginner

4219: .keywords: SNES, set, solution
4220: @*/
4221: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4222: {
4223:   DM             dm;

4229:   PetscObjectReference((PetscObject) u);
4230:   VecDestroy(&snes->vec_sol);

4232:   snes->vec_sol = u;

4234:   SNESGetDM(snes, &dm);
4235:   DMShellSetGlobalVector(dm, u);
4236:   return(0);
4237: }

4241: /*@
4242:    SNESGetSolution - Returns the vector where the approximate solution is
4243:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4247:    Input Parameter:
4248: .  snes - the SNES context

4250:    Output Parameter:
4251: .  x - the solution

4253:    Level: intermediate

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

4257: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4258: @*/
4259: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4260: {
4264:   *x = snes->vec_sol;
4265:   return(0);
4266: }

4270: /*@
4271:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4272:    stored.

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

4276:    Input Parameter:
4277: .  snes - the SNES context

4279:    Output Parameter:
4280: .  x - the solution update

4282:    Level: advanced

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

4286: .seealso: SNESGetSolution(), SNESGetFunction()
4287: @*/
4288: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4289: {
4293:   *x = snes->vec_sol_update;
4294:   return(0);
4295: }

4299: /*@C
4300:    SNESGetFunction - Returns the vector where the function is stored.

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

4304:    Input Parameter:
4305: .  snes - the SNES context

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

4312:    Level: advanced

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

4316: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4317: @*/
4318: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4319: {
4321:   DM             dm;

4325:   if (r) {
4326:     if (!snes->vec_func) {
4327:       if (snes->vec_rhs) {
4328:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4329:       } else if (snes->vec_sol) {
4330:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4331:       } else if (snes->dm) {
4332:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4333:       }
4334:     }
4335:     *r = snes->vec_func;
4336:   }
4337:   SNESGetDM(snes,&dm);
4338:   DMSNESGetFunction(dm,f,ctx);
4339:   return(0);
4340: }

4342: /*@C
4343:    SNESGetNGS - Returns the NGS function and context.

4345:    Input Parameter:
4346: .  snes - the SNES context

4348:    Output Parameter:
4349: +  f - the function (or NULL) see SNESNGSFunction for details
4350: -  ctx    - the function context (or NULL)

4352:    Level: advanced

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

4356: .seealso: SNESSetNGS(), SNESGetFunction()
4357: @*/

4361: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4362: {
4364:   DM             dm;

4368:   SNESGetDM(snes,&dm);
4369:   DMSNESGetNGS(dm,f,ctx);
4370:   return(0);
4371: }

4375: /*@C
4376:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4377:    SNES options in the database.

4379:    Logically Collective on SNES

4381:    Input Parameter:
4382: +  snes - the SNES context
4383: -  prefix - the prefix to prepend to all option names

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

4389:    Level: advanced

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

4393: .seealso: SNESSetFromOptions()
4394: @*/
4395: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4396: {

4401:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4402:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4403:   if (snes->linesearch) {
4404:     SNESGetLineSearch(snes,&snes->linesearch);
4405:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4406:   }
4407:   KSPSetOptionsPrefix(snes->ksp,prefix);
4408:   return(0);
4409: }

4413: /*@C
4414:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4415:    SNES options in the database.

4417:    Logically Collective on SNES

4419:    Input Parameters:
4420: +  snes - the SNES context
4421: -  prefix - the prefix to prepend to all option names

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

4427:    Level: advanced

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

4431: .seealso: SNESGetOptionsPrefix()
4432: @*/
4433: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4434: {

4439:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4440:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4441:   if (snes->linesearch) {
4442:     SNESGetLineSearch(snes,&snes->linesearch);
4443:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4444:   }
4445:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4446:   return(0);
4447: }

4451: /*@C
4452:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4453:    SNES options in the database.

4455:    Not Collective

4457:    Input Parameter:
4458: .  snes - the SNES context

4460:    Output Parameter:
4461: .  prefix - pointer to the prefix string used

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

4466:    Level: advanced

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

4470: .seealso: SNESAppendOptionsPrefix()
4471: @*/
4472: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4473: {

4478:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4479:   return(0);
4480: }


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

4488:    Not collective

4490:    Input Parameters:
4491: +  name_solver - name of a new user-defined solver
4492: -  routine_create - routine to create method context

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

4497:    Sample usage:
4498: .vb
4499:    SNESRegister("my_solver",MySolverCreate);
4500: .ve

4502:    Then, your solver can be chosen with the procedural interface via
4503: $     SNESSetType(snes,"my_solver")
4504:    or at runtime via the option
4505: $     -snes_type my_solver

4507:    Level: advanced

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

4511: .keywords: SNES, nonlinear, register

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

4515:   Level: advanced
4516: @*/
4517: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4518: {

4522:   PetscFunctionListAdd(&SNESList,sname,function);
4523:   return(0);
4524: }

4528: PetscErrorCode  SNESTestLocalMin(SNES snes)
4529: {
4531:   PetscInt       N,i,j;
4532:   Vec            u,uh,fh;
4533:   PetscScalar    value;
4534:   PetscReal      norm;

4537:   SNESGetSolution(snes,&u);
4538:   VecDuplicate(u,&uh);
4539:   VecDuplicate(u,&fh);

4541:   /* currently only works for sequential */
4542:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4543:   VecGetSize(u,&N);
4544:   for (i=0; i<N; i++) {
4545:     VecCopy(u,uh);
4546:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4547:     for (j=-10; j<11; j++) {
4548:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4549:       VecSetValue(uh,i,value,ADD_VALUES);
4550:       SNESComputeFunction(snes,uh,fh);
4551:       VecNorm(fh,NORM_2,&norm);
4552:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4553:       value = -value;
4554:       VecSetValue(uh,i,value,ADD_VALUES);
4555:     }
4556:   }
4557:   VecDestroy(&uh);
4558:   VecDestroy(&fh);
4559:   return(0);
4560: }

4564: /*@
4565:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4566:    computing relative tolerance for linear solvers within an inexact
4567:    Newton method.

4569:    Logically Collective on SNES

4571:    Input Parameters:
4572: +  snes - SNES context
4573: -  flag - PETSC_TRUE or PETSC_FALSE

4575:     Options Database:
4576: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4577: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4578: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4579: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4580: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4581: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4582: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4583: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4585:    Notes:
4586:    Currently, the default is to use a constant relative tolerance for
4587:    the inner linear solvers.  Alternatively, one can use the
4588:    Eisenstat-Walker method, where the relative convergence tolerance
4589:    is reset at each Newton iteration according progress of the nonlinear
4590:    solver.

4592:    Level: advanced

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

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

4600: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4601: @*/
4602: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4603: {
4607:   snes->ksp_ewconv = flag;
4608:   return(0);
4609: }

4613: /*@
4614:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4615:    for computing relative tolerance for linear solvers within an
4616:    inexact Newton method.

4618:    Not Collective

4620:    Input Parameter:
4621: .  snes - SNES context

4623:    Output Parameter:
4624: .  flag - PETSC_TRUE or PETSC_FALSE

4626:    Notes:
4627:    Currently, the default is to use a constant relative tolerance for
4628:    the inner linear solvers.  Alternatively, one can use the
4629:    Eisenstat-Walker method, where the relative convergence tolerance
4630:    is reset at each Newton iteration according progress of the nonlinear
4631:    solver.

4633:    Level: advanced

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

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

4641: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4642: @*/
4643: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4644: {
4648:   *flag = snes->ksp_ewconv;
4649:   return(0);
4650: }

4654: /*@
4655:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4656:    convergence criteria for the linear solvers within an inexact
4657:    Newton method.

4659:    Logically Collective on SNES

4661:    Input Parameters:
4662: +    snes - SNES context
4663: .    version - version 1, 2 (default is 2) or 3
4664: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4665: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4666: .    gamma - multiplicative factor for version 2 rtol computation
4667:              (0 <= gamma2 <= 1)
4668: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4669: .    alpha2 - power for safeguard
4670: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4672:    Note:
4673:    Version 3 was contributed by Luis Chacon, June 2006.

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

4677:    Level: advanced

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

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

4686: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4687: @*/
4688: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4689: {
4690:   SNESKSPEW *kctx;

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

4704:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4705:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4706:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4707:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4708:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4709:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4710:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4712:   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);
4713:   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);
4714:   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);
4715:   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);
4716:   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);
4717:   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);
4718:   return(0);
4719: }

4723: /*@
4724:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4725:    convergence criteria for the linear solvers within an inexact
4726:    Newton method.

4728:    Not Collective

4730:    Input Parameters:
4731:      snes - SNES context

4733:    Output Parameters:
4734: +    version - version 1, 2 (default is 2) or 3
4735: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4736: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4737: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
4738: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4739: .    alpha2 - power for safeguard
4740: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4742:    Level: advanced

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

4746: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
4747: @*/
4748: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
4749: {
4750:   SNESKSPEW *kctx;

4754:   kctx = (SNESKSPEW*)snes->kspconvctx;
4755:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
4756:   if (version)   *version   = kctx->version;
4757:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
4758:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
4759:   if (gamma)     *gamma     = kctx->gamma;
4760:   if (alpha)     *alpha     = kctx->alpha;
4761:   if (alpha2)    *alpha2    = kctx->alpha2;
4762:   if (threshold) *threshold = kctx->threshold;
4763:   return(0);
4764: }

4768:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4769: {
4771:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4772:   PetscReal      rtol  = PETSC_DEFAULT,stol;

4775:   if (!snes->ksp_ewconv) return(0);
4776:   if (!snes->iter) {
4777:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
4778:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
4779:   }
4780:   else {
4781:     if (kctx->version == 1) {
4782:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
4783:       if (rtol < 0.0) rtol = -rtol;
4784:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
4785:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4786:     } else if (kctx->version == 2) {
4787:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4788:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
4789:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4790:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
4791:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4792:       /* safeguard: avoid sharp decrease of rtol */
4793:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
4794:       stol = PetscMax(rtol,stol);
4795:       rtol = PetscMin(kctx->rtol_0,stol);
4796:       /* safeguard: avoid oversolving */
4797:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
4798:       stol = PetscMax(rtol,stol);
4799:       rtol = PetscMin(kctx->rtol_0,stol);
4800:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
4801:   }
4802:   /* safeguard: avoid rtol greater than one */
4803:   rtol = PetscMin(rtol,kctx->rtol_max);
4804:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
4805:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
4806:   return(0);
4807: }

4811: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4812: {
4814:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4815:   PCSide         pcside;
4816:   Vec            lres;

4819:   if (!snes->ksp_ewconv) return(0);
4820:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
4821:   kctx->norm_last = snes->norm;
4822:   if (kctx->version == 1) {
4823:     PC        pc;
4824:     PetscBool isNone;

4826:     KSPGetPC(ksp, &pc);
4827:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
4828:     KSPGetPCSide(ksp,&pcside);
4829:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
4830:       /* KSP residual is true linear residual */
4831:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
4832:     } else {
4833:       /* KSP residual is preconditioned residual */
4834:       /* compute true linear residual norm */
4835:       VecDuplicate(b,&lres);
4836:       MatMult(snes->jacobian,x,lres);
4837:       VecAYPX(lres,-1.0,b);
4838:       VecNorm(lres,NORM_2,&kctx->lresid_last);
4839:       VecDestroy(&lres);
4840:     }
4841:   }
4842:   return(0);
4843: }

4847: /*@
4848:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

4852:    Input Parameter:
4853: .  snes - the SNES context

4855:    Output Parameter:
4856: .  ksp - the KSP context

4858:    Notes:
4859:    The user can then directly manipulate the KSP context to set various
4860:    options, etc.  Likewise, the user can then extract and manipulate the
4861:    PC contexts as well.

4863:    Level: beginner

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

4867: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
4868: @*/
4869: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
4870: {


4877:   if (!snes->ksp) {
4878:     PetscBool monitor = PETSC_FALSE;

4880:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
4881:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
4882:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

4887:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
4888:     if (monitor) {
4889:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
4890:     }
4891:     monitor = PETSC_FALSE;
4892:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
4893:     if (monitor) {
4894:       PetscObject *objs;
4895:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
4896:       objs[0] = (PetscObject) snes;
4897:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
4898:     }
4899:   }
4900:   *ksp = snes->ksp;
4901:   return(0);
4902: }


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

4911:    Logically Collective on SNES

4913:    Input Parameters:
4914: +  snes - the nonlinear solver context
4915: -  dm - the dm, cannot be NULL

4917:    Level: intermediate

4919: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
4920: @*/
4921: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
4922: {
4924:   KSP            ksp;
4925:   DMSNES         sdm;

4930:   PetscObjectReference((PetscObject)dm);
4931:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
4932:     if (snes->dm->dmsnes && !dm->dmsnes) {
4933:       DMCopyDMSNES(snes->dm,dm);
4934:       DMGetDMSNES(snes->dm,&sdm);
4935:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
4936:     }
4937:     DMDestroy(&snes->dm);
4938:   }
4939:   snes->dm     = dm;
4940:   snes->dmAuto = PETSC_FALSE;

4942:   SNESGetKSP(snes,&ksp);
4943:   KSPSetDM(ksp,dm);
4944:   KSPSetDMActive(ksp,PETSC_FALSE);
4945:   if (snes->pc) {
4946:     SNESSetDM(snes->pc, snes->dm);
4947:     SNESSetNPCSide(snes,snes->pcside);
4948:   }
4949:   return(0);
4950: }

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

4957:    Not Collective but DM obtained is parallel on SNES

4959:    Input Parameter:
4960: . snes - the preconditioner context

4962:    Output Parameter:
4963: .  dm - the dm

4965:    Level: intermediate

4967: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
4968: @*/
4969: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
4970: {

4975:   if (!snes->dm) {
4976:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
4977:     snes->dmAuto = PETSC_TRUE;
4978:   }
4979:   *dm = snes->dm;
4980:   return(0);
4981: }

4985: /*@
4986:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

4988:   Collective on SNES

4990:   Input Parameters:
4991: + snes - iterative context obtained from SNESCreate()
4992: - pc   - the preconditioner object

4994:   Notes:
4995:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
4996:   to configure it using the API).

4998:   Level: developer

5000: .keywords: SNES, set, precondition
5001: .seealso: SNESGetNPC(), SNESHasNPC()
5002: @*/
5003: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5004: {

5011:   PetscObjectReference((PetscObject) pc);
5012:   SNESDestroy(&snes->pc);
5013:   snes->pc = pc;
5014:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->pc);
5015:   return(0);
5016: }

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

5023:   Not Collective

5025:   Input Parameter:
5026: . snes - iterative context obtained from SNESCreate()

5028:   Output Parameter:
5029: . pc - preconditioner context

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

5033:   Level: developer

5035: .keywords: SNES, get, preconditioner
5036: .seealso: SNESSetNPC(), SNESHasNPC()
5037: @*/
5038: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5039: {
5041:   const char     *optionsprefix;

5046:   if (!snes->pc) {
5047:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->pc);
5048:     PetscObjectIncrementTabLevel((PetscObject)snes->pc,(PetscObject)snes,1);
5049:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->pc);
5050:     SNESGetOptionsPrefix(snes,&optionsprefix);
5051:     SNESSetOptionsPrefix(snes->pc,optionsprefix);
5052:     SNESAppendOptionsPrefix(snes->pc,"npc_");
5053:     SNESSetCountersReset(snes->pc,PETSC_FALSE);
5054:   }
5055:   *pc = snes->pc;
5056:   return(0);
5057: }

5061: /*@
5062:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5064:   Not Collective

5066:   Input Parameter:
5067: . snes - iterative context obtained from SNESCreate()

5069:   Output Parameter:
5070: . has_npc - whether the SNES has an NPC or not

5072:   Level: developer

5074: .keywords: SNES, has, preconditioner
5075: .seealso: SNESSetNPC(), SNESGetNPC()
5076: @*/
5077: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5078: {
5081:   *has_npc = (PetscBool) (snes->pc ? PETSC_TRUE : PETSC_FALSE);
5082:   return(0);
5083: }

5087: /*@
5088:     SNESSetNPCSide - Sets the preconditioning side.

5090:     Logically Collective on SNES

5092:     Input Parameter:
5093: .   snes - iterative context obtained from SNESCreate()

5095:     Output Parameter:
5096: .   side - the preconditioning side, where side is one of
5097: .vb
5098:       PC_LEFT - left preconditioning
5099:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5100: .ve

5102:     Options Database Keys:
5103: .   -snes_pc_side <right,left>

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

5107:     Level: intermediate

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

5111: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5112: @*/
5113: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5114: {
5118:   snes->pcside = side;
5119:   return(0);
5120: }

5124: /*@
5125:     SNESGetNPCSide - Gets the preconditioning side.

5127:     Not Collective

5129:     Input Parameter:
5130: .   snes - iterative context obtained from SNESCreate()

5132:     Output Parameter:
5133: .   side - the preconditioning side, where side is one of
5134: .vb
5135:       PC_LEFT - left preconditioning
5136:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5137: .ve

5139:     Level: intermediate

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

5143: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5144: @*/
5145: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5146: {
5150:   *side = snes->pcside;
5151:   return(0);
5152: }

5156: /*@
5157:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5159:   Collective on SNES

5161:   Input Parameters:
5162: + snes - iterative context obtained from SNESCreate()
5163: - linesearch   - the linesearch object

5165:   Notes:
5166:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5167:   to configure it using the API).

5169:   Level: developer

5171: .keywords: SNES, set, linesearch
5172: .seealso: SNESGetLineSearch()
5173: @*/
5174: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5175: {

5182:   PetscObjectReference((PetscObject) linesearch);
5183:   SNESLineSearchDestroy(&snes->linesearch);

5185:   snes->linesearch = linesearch;

5187:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5188:   return(0);
5189: }

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

5197:   Not Collective

5199:   Input Parameter:
5200: . snes - iterative context obtained from SNESCreate()

5202:   Output Parameter:
5203: . linesearch - linesearch context

5205:   Level: beginner

5207: .keywords: SNES, get, linesearch
5208: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5209: @*/
5210: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5211: {
5213:   const char     *optionsprefix;

5218:   if (!snes->linesearch) {
5219:     SNESGetOptionsPrefix(snes, &optionsprefix);
5220:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5221:     SNESLineSearchSetSNES(snes->linesearch, snes);
5222:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5223:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5224:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5225:   }
5226:   *linesearch = snes->linesearch;
5227:   return(0);
5228: }

5230: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5231: #include <mex.h>

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

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

5240:    Collective on SNES

5242:    Input Parameters:
5243: +  snes - the SNES context
5244: -  x - input vector

5246:    Output Parameter:
5247: .  y - function vector, as set by SNESSetFunction()

5249:    Notes:
5250:    SNESComputeFunction() is typically used within nonlinear solvers
5251:    implementations, so most users would not generally call this routine
5252:    themselves.

5254:    Level: developer

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

5258: .seealso: SNESSetFunction(), SNESGetFunction()
5259: */
5260: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5261: {
5262:   PetscErrorCode    ierr;
5263:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5264:   int               nlhs  = 1,nrhs = 5;
5265:   mxArray           *plhs[1],*prhs[5];
5266:   long long int     lx = 0,ly = 0,ls = 0;


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

5277:   PetscMemcpy(&ls,&snes,sizeof(snes));
5278:   PetscMemcpy(&lx,&x,sizeof(x));
5279:   PetscMemcpy(&ly,&y,sizeof(x));
5280:   prhs[0] = mxCreateDoubleScalar((double)ls);
5281:   prhs[1] = mxCreateDoubleScalar((double)lx);
5282:   prhs[2] = mxCreateDoubleScalar((double)ly);
5283:   prhs[3] = mxCreateString(sctx->funcname);
5284:   prhs[4] = sctx->ctx;
5285:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");
5286:   mxGetScalar(plhs[0]);
5287:   mxDestroyArray(prhs[0]);
5288:   mxDestroyArray(prhs[1]);
5289:   mxDestroyArray(prhs[2]);
5290:   mxDestroyArray(prhs[3]);
5291:   mxDestroyArray(plhs[0]);
5292:   return(0);
5293: }

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

5302:    Logically Collective on SNES

5304:    Input Parameters:
5305: +  snes - the SNES context
5306: .  r - vector to store function value
5307: -  f - function evaluation routine

5309:    Notes:
5310:    The Newton-like methods typically solve linear systems of the form
5311: $      f'(x) x = -f(x),
5312:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5314:    Level: beginner

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

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

5320: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5321: */
5322: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5323: {
5324:   PetscErrorCode    ierr;
5325:   SNESMatlabContext *sctx;

5328:   /* currently sctx is memory bleed */
5329:   PetscNew(&sctx);
5330:   PetscStrallocpy(f,&sctx->funcname);
5331:   /*
5332:      This should work, but it doesn't
5333:   sctx->ctx = ctx;
5334:   mexMakeArrayPersistent(sctx->ctx);
5335:   */
5336:   sctx->ctx = mxDuplicateArray(ctx);
5337:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5338:   return(0);
5339: }

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

5346:    Collective on SNES

5348:    Input Parameters:
5349: +  snes - the SNES context
5350: .  x - input vector
5351: .  A, B - the matrices
5352: -  ctx - user context

5354:    Level: developer

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

5358: .seealso: SNESSetFunction(), SNESGetFunction()
5359: @*/
5360: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5361: {
5362:   PetscErrorCode    ierr;
5363:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5364:   int               nlhs  = 2,nrhs = 6;
5365:   mxArray           *plhs[2],*prhs[6];
5366:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


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

5374:   PetscMemcpy(&ls,&snes,sizeof(snes));
5375:   PetscMemcpy(&lx,&x,sizeof(x));
5376:   PetscMemcpy(&lA,A,sizeof(x));
5377:   PetscMemcpy(&lB,B,sizeof(x));
5378:   prhs[0] = mxCreateDoubleScalar((double)ls);
5379:   prhs[1] = mxCreateDoubleScalar((double)lx);
5380:   prhs[2] = mxCreateDoubleScalar((double)lA);
5381:   prhs[3] = mxCreateDoubleScalar((double)lB);
5382:   prhs[4] = mxCreateString(sctx->funcname);
5383:   prhs[5] = sctx->ctx;
5384:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5385:   mxGetScalar(plhs[0]);
5386:   mxDestroyArray(prhs[0]);
5387:   mxDestroyArray(prhs[1]);
5388:   mxDestroyArray(prhs[2]);
5389:   mxDestroyArray(prhs[3]);
5390:   mxDestroyArray(prhs[4]);
5391:   mxDestroyArray(plhs[0]);
5392:   mxDestroyArray(plhs[1]);
5393:   return(0);
5394: }

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

5403:    Logically Collective on SNES

5405:    Input Parameters:
5406: +  snes - the SNES context
5407: .  A,B - Jacobian matrices
5408: .  J - function evaluation routine
5409: -  ctx - user context

5411:    Level: developer

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

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

5417: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5418: */
5419: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5420: {
5421:   PetscErrorCode    ierr;
5422:   SNESMatlabContext *sctx;

5425:   /* currently sctx is memory bleed */
5426:   PetscNew(&sctx);
5427:   PetscStrallocpy(J,&sctx->funcname);
5428:   /*
5429:      This should work, but it doesn't
5430:   sctx->ctx = ctx;
5431:   mexMakeArrayPersistent(sctx->ctx);
5432:   */
5433:   sctx->ctx = mxDuplicateArray(ctx);
5434:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5435:   return(0);
5436: }

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

5443:    Collective on SNES

5445: .seealso: SNESSetFunction(), SNESGetFunction()
5446: @*/
5447: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5448: {
5449:   PetscErrorCode    ierr;
5450:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5451:   int               nlhs  = 1,nrhs = 6;
5452:   mxArray           *plhs[1],*prhs[6];
5453:   long long int     lx = 0,ls = 0;
5454:   Vec               x  = snes->vec_sol;


5459:   PetscMemcpy(&ls,&snes,sizeof(snes));
5460:   PetscMemcpy(&lx,&x,sizeof(x));
5461:   prhs[0] = mxCreateDoubleScalar((double)ls);
5462:   prhs[1] = mxCreateDoubleScalar((double)it);
5463:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5464:   prhs[3] = mxCreateDoubleScalar((double)lx);
5465:   prhs[4] = mxCreateString(sctx->funcname);
5466:   prhs[5] = sctx->ctx;
5467:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5468:   mxGetScalar(plhs[0]);
5469:   mxDestroyArray(prhs[0]);
5470:   mxDestroyArray(prhs[1]);
5471:   mxDestroyArray(prhs[2]);
5472:   mxDestroyArray(prhs[3]);
5473:   mxDestroyArray(prhs[4]);
5474:   mxDestroyArray(plhs[0]);
5475:   return(0);
5476: }

5480: /*
5481:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5483:    Level: developer

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

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

5489: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5490: */
5491: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5492: {
5493:   PetscErrorCode    ierr;
5494:   SNESMatlabContext *sctx;

5497:   /* currently sctx is memory bleed */
5498:   PetscNew(&sctx);
5499:   PetscStrallocpy(f,&sctx->funcname);
5500:   /*
5501:      This should work, but it doesn't
5502:   sctx->ctx = ctx;
5503:   mexMakeArrayPersistent(sctx->ctx);
5504:   */
5505:   sctx->ctx = mxDuplicateArray(ctx);
5506:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5507:   return(0);
5508: }

5510: #endif