Actual source code: snes.c

petsc-3.10.2 2018-10-09
Report Typos and Errors
  1:  #include <petsc/private/snesimpl.h>
  2:  #include <petscdmshell.h>
  3:  #include <petscdraw.h>
  4:  #include <petscds.h>
  5:  #include <petscdmadaptor.h>
  6:  #include <petscconvest.h>

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

 11: /* Logging support */
 12: PetscClassId  SNES_CLASSID, DMSNES_CLASSID;
 13: PetscLogEvent SNES_Solve, SNES_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: }

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

 49:    Not Collective

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

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

 57:    Level: intermediate

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

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

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

 75:    Logically Collective on SNES

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

 81:    Level: advanced

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

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

 96:    Logically Collective on SNES

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

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

104:    Level: advanced

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

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

120:    Logically Collective on SNES

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

125:    Level: advanced

127: .keywords: SNES, view

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

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

143:    Logically Collective on SNES

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

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

151:    Level: advanced

153: .keywords: SNES, view

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

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

169:   Collective on PetscViewer

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

176:    Level: intermediate

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

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

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

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

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

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

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

231:    Collective on SNES

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

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

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

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

251:    Level: beginner

253: .keywords: SNES, view

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

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

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

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

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

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

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

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

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

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

431:   Not Collective

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

436:   Level: developer

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

599:    Collective

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

604:    Level: developer

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

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

645:     J    = snes->jacobian;
646:     DMGetDS(dm, &prob);
647:     if (prob) {PetscDSHasJacobianPreconditioner(prob, &hasPrec);}
648:     if (J)            {PetscObjectReference((PetscObject) J);}
649:     else if (hasPrec) {DMCreateMatrix(snes->dm, &J);}
650:     DMCreateMatrix(snes->dm, &B);
651:     PetscDSGetNumFields(prob, &Nf);
652:     DMGetNullSpaceConstructor(snes->dm, Nf, &nspconstr);
653:     if (nspconstr) (*nspconstr)(snes->dm, -1, &nullspace);
654:     MatSetNullSpace(B, nullspace);
655:     MatNullSpaceDestroy(&nullspace);
656:     SNESSetJacobian(snes, J ? J : B, B, NULL, NULL);
657:     MatDestroy(&J);
658:     MatDestroy(&B);
659:   }
660:   {
661:     KSP ksp;
662:     SNESGetKSP(snes,&ksp);
663:     KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);
664:     DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
665:   }
666:   return(0);
667: }

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

672:    Collective on SNES

674:    Input Parameters:
675: +  snes - SNES object you wish to monitor
676: .  name - the monitor type one is seeking
677: .  help - message indicating what monitoring is done
678: .  manual - manual page for the monitor
679: .  monitor - the monitor function
680: -  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

682:    Level: developer

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

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

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

716:    Collective on SNES

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

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

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

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

765:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

854:   flg  = PETSC_FALSE;
855:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
856:   if (set && flg) {SNESMonitorCancel(snes);}

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

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

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


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

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

887:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
888:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
889:   }



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

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

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

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

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

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

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

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

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

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

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

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

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

998:    Collective on SNES

1000:    Input Parameter:
1001: .  snes - the SNES context

1003:    Level: beginner

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

1007: .seealso: SNESSetFromOptions(), SNESSetOptionsPrefix()
1008: @*/
1009: PetscErrorCode SNESResetFromOptions(SNES snes)
1010: {

1014:   if (snes->setfromoptionscalled) {SNESSetFromOptions(snes);}
1015:   return(0);
1016: }

1018: /*@C
1019:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
1020:    the nonlinear solvers.

1022:    Logically Collective on SNES

1024:    Input Parameters:
1025: +  snes - the SNES context
1026: .  compute - function to compute the context
1027: -  destroy - function to destroy the context

1029:    Level: intermediate

1031:    Notes:
1032:    This function is currently not available from Fortran.

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

1036: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1037: @*/
1038: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1039: {
1042:   snes->ops->usercompute = compute;
1043:   snes->ops->userdestroy = destroy;
1044:   return(0);
1045: }

1047: /*@
1048:    SNESSetApplicationContext - Sets the optional user-defined context for
1049:    the nonlinear solvers.

1051:    Logically Collective on SNES

1053:    Input Parameters:
1054: +  snes - the SNES context
1055: -  usrP - optional user context

1057:    Level: intermediate

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

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

1065: .seealso: SNESGetApplicationContext()
1066: @*/
1067: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1068: {
1070:   KSP            ksp;

1074:   SNESGetKSP(snes,&ksp);
1075:   KSPSetApplicationContext(ksp,usrP);
1076:   snes->user = usrP;
1077:   return(0);
1078: }

1080: /*@
1081:    SNESGetApplicationContext - Gets the user-defined context for the
1082:    nonlinear solvers.

1084:    Not Collective

1086:    Input Parameter:
1087: .  snes - SNES context

1089:    Output Parameter:
1090: .  usrP - user context

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

1096:    Level: intermediate

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

1100: .seealso: SNESSetApplicationContext()
1101: @*/
1102: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1103: {
1106:   *(void**)usrP = snes->user;
1107:   return(0);
1108: }

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

1114:    Collective on SNES

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

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

1125:    Level: intermediate

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

1129: .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF()
1130: @*/
1131: PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1132: {
1137:   if (mf && !mf_operator) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"If using mf must also use mf_operator");
1138:   snes->mf          = mf;
1139:   snes->mf_operator = mf_operator;
1140:   return(0);
1141: }

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

1147:    Collective on SNES

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

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

1156:    Options Database:
1157: + -snes_mf - use matrix free for both the mat and pmat operator
1158: - -snes_mf_operator - use matrix free only for the mat operator

1160:    Level: intermediate

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

1164: .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
1165: @*/
1166: PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1167: {
1170:   if (mf)          *mf          = snes->mf;
1171:   if (mf_operator) *mf_operator = snes->mf_operator;
1172:   return(0);
1173: }

1175: /*@
1176:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1177:    at this time.

1179:    Not Collective

1181:    Input Parameter:
1182: .  snes - SNES context

1184:    Output Parameter:
1185: .  iter - iteration number

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

1190:    This is useful for using lagged Jacobians (where one does not recompute the
1191:    Jacobian at each SNES iteration). For example, the code
1192: .vb
1193:       SNESGetIterationNumber(snes,&it);
1194:       if (!(it % 2)) {
1195:         [compute Jacobian here]
1196:       }
1197: .ve
1198:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1199:    recomputed every second SNES iteration.

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

1203:    Level: intermediate

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

1207: .seealso:   SNESGetLinearSolveIterations()
1208: @*/
1209: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1210: {
1214:   *iter = snes->iter;
1215:   return(0);
1216: }

1218: /*@
1219:    SNESSetIterationNumber - Sets the current iteration number.

1221:    Not Collective

1223:    Input Parameter:
1224: .  snes - SNES context
1225: .  iter - iteration number

1227:    Level: developer

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

1231: .seealso:   SNESGetLinearSolveIterations()
1232: @*/
1233: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1234: {

1239:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1240:   snes->iter = iter;
1241:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1242:   return(0);
1243: }

1245: /*@
1246:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1247:    attempted by the nonlinear solver.

1249:    Not Collective

1251:    Input Parameter:
1252: .  snes - SNES context

1254:    Output Parameter:
1255: .  nfails - number of unsuccessful steps attempted

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

1260:    Level: intermediate

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

1264: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1265:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1266: @*/
1267: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1268: {
1272:   *nfails = snes->numFailures;
1273:   return(0);
1274: }

1276: /*@
1277:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1278:    attempted by the nonlinear solver before it gives up.

1280:    Not Collective

1282:    Input Parameters:
1283: +  snes     - SNES context
1284: -  maxFails - maximum of unsuccessful steps

1286:    Level: intermediate

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

1290: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1291:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1292: @*/
1293: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1294: {
1297:   snes->maxFailures = maxFails;
1298:   return(0);
1299: }

1301: /*@
1302:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1303:    attempted by the nonlinear solver before it gives up.

1305:    Not Collective

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

1310:    Output Parameter:
1311: .  maxFails - maximum of unsuccessful steps

1313:    Level: intermediate

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

1317: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1318:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1320: @*/
1321: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1322: {
1326:   *maxFails = snes->maxFailures;
1327:   return(0);
1328: }

1330: /*@
1331:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1332:      done by SNES.

1334:    Not Collective

1336:    Input Parameter:
1337: .  snes     - SNES context

1339:    Output Parameter:
1340: .  nfuncs - number of evaluations

1342:    Level: intermediate

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

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

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

1360: /*@
1361:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1362:    linear solvers.

1364:    Not Collective

1366:    Input Parameter:
1367: .  snes - SNES context

1369:    Output Parameter:
1370: .  nfails - number of failed solves

1372:    Level: intermediate

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

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

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

1382: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1383: @*/
1384: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1385: {
1389:   *nfails = snes->numLinearSolveFailures;
1390:   return(0);
1391: }

1393: /*@
1394:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1395:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1397:    Logically Collective on SNES

1399:    Input Parameters:
1400: +  snes     - SNES context
1401: -  maxFails - maximum allowed linear solve failures

1403:    Level: intermediate

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

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

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

1413: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1414: @*/
1415: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1416: {
1420:   snes->maxLinearSolveFailures = maxFails;
1421:   return(0);
1422: }

1424: /*@
1425:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1426:      are allowed before SNES terminates

1428:    Not Collective

1430:    Input Parameter:
1431: .  snes     - SNES context

1433:    Output Parameter:
1434: .  maxFails - maximum of unsuccessful solves allowed

1436:    Level: intermediate

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

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

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

1454: /*@
1455:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1456:    used by the nonlinear solver.

1458:    Not Collective

1460:    Input Parameter:
1461: .  snes - SNES context

1463:    Output Parameter:
1464: .  lits - number of linear iterations

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

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

1472:    Level: intermediate

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

1476: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1477: @*/
1478: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1479: {
1483:   *lits = snes->linear_its;
1484:   return(0);
1485: }

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

1491:    Logically Collective on SNES

1493:    Input Parameter:
1494: +  snes - SNES context
1495: -  reset - whether to reset the counters or not

1497:    Notes:
1498:    This defaults to PETSC_TRUE

1500:    Level: developer

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

1504: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1505: @*/
1506: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1507: {
1511:   snes->counters_reset = reset;
1512:   return(0);
1513: }


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

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

1521:    Input Parameters:
1522: +  snes - the SNES context
1523: -  ksp - the KSP context

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

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

1532:    Level: developer

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

1536: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1537: @*/
1538: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1539: {

1546:   PetscObjectReference((PetscObject)ksp);
1547:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1548:   snes->ksp = ksp;
1549:   return(0);
1550: }

1552: /* -----------------------------------------------------------*/
1553: /*@
1554:    SNESCreate - Creates a nonlinear solver context.

1556:    Collective on MPI_Comm

1558:    Input Parameters:
1559: .  comm - MPI communicator

1561:    Output Parameter:
1562: .  outsnes - the new SNES context

1564:    Options Database Keys:
1565: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1566:                and no preconditioning matrix
1567: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1568:                products, and a user-provided preconditioning matrix
1569:                as set by SNESSetJacobian()
1570: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1572:    Level: beginner

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

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

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

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

1588: @*/
1589: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1590: {
1592:   SNES           snes;
1593:   SNESKSPEW      *kctx;

1597:   *outsnes = NULL;
1598:   SNESInitializePackage();

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

1602:   snes->ops->converged    = SNESConvergedDefault;
1603:   snes->usesksp           = PETSC_TRUE;
1604:   snes->tolerancesset     = PETSC_FALSE;
1605:   snes->max_its           = 50;
1606:   snes->max_funcs         = 10000;
1607:   snes->norm              = 0.0;
1608:   snes->normschedule      = SNES_NORM_ALWAYS;
1609:   snes->functype          = SNES_FUNCTION_DEFAULT;
1610: #if defined(PETSC_USE_REAL_SINGLE)
1611:   snes->rtol              = 1.e-5;
1612: #else
1613:   snes->rtol              = 1.e-8;
1614: #endif
1615:   snes->ttol              = 0.0;
1616: #if defined(PETSC_USE_REAL_SINGLE)
1617:   snes->abstol            = 1.e-25;
1618: #else
1619:   snes->abstol            = 1.e-50;
1620: #endif
1621: #if defined(PETSC_USE_REAL_SINGLE)
1622:   snes->stol              = 1.e-5;
1623: #else
1624:   snes->stol              = 1.e-8;
1625: #endif
1626: #if defined(PETSC_USE_REAL_SINGLE)
1627:   snes->deltatol          = 1.e-6;
1628: #else
1629:   snes->deltatol          = 1.e-12;
1630: #endif
1631:   snes->divtol            = 1.e4;
1632:   snes->rnorm0            = 0;
1633:   snes->nfuncs            = 0;
1634:   snes->numFailures       = 0;
1635:   snes->maxFailures       = 1;
1636:   snes->linear_its        = 0;
1637:   snes->lagjacobian       = 1;
1638:   snes->jac_iter          = 0;
1639:   snes->lagjac_persist    = PETSC_FALSE;
1640:   snes->lagpreconditioner = 1;
1641:   snes->pre_iter          = 0;
1642:   snes->lagpre_persist    = PETSC_FALSE;
1643:   snes->numbermonitors    = 0;
1644:   snes->data              = 0;
1645:   snes->setupcalled       = PETSC_FALSE;
1646:   snes->ksp_ewconv        = PETSC_FALSE;
1647:   snes->nwork             = 0;
1648:   snes->work              = 0;
1649:   snes->nvwork            = 0;
1650:   snes->vwork             = 0;
1651:   snes->conv_hist_len     = 0;
1652:   snes->conv_hist_max     = 0;
1653:   snes->conv_hist         = NULL;
1654:   snes->conv_hist_its     = NULL;
1655:   snes->conv_hist_reset   = PETSC_TRUE;
1656:   snes->counters_reset    = PETSC_TRUE;
1657:   snes->vec_func_init_set = PETSC_FALSE;
1658:   snes->reason            = SNES_CONVERGED_ITERATING;
1659:   snes->npcside           = PC_RIGHT;
1660:   snes->setfromoptionscalled = 0;

1662:   snes->mf          = PETSC_FALSE;
1663:   snes->mf_operator = PETSC_FALSE;
1664:   snes->mf_version  = 1;

1666:   snes->numLinearSolveFailures = 0;
1667:   snes->maxLinearSolveFailures = 1;

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

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

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

1677:   snes->kspconvctx  = (void*)kctx;
1678:   kctx->version     = 2;
1679:   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1680:                              this was too large for some test cases */
1681:   kctx->rtol_last   = 0.0;
1682:   kctx->rtol_max    = .9;
1683:   kctx->gamma       = 1.0;
1684:   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
1685:   kctx->alpha2      = kctx->alpha;
1686:   kctx->threshold   = .1;
1687:   kctx->lresid_last = 0.0;
1688:   kctx->norm_last   = 0.0;

1690:   *outsnes = snes;
1691:   return(0);
1692: }

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

1697:      Synopsis:
1698:      #include "petscsnes.h"
1699:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1701:      Input Parameters:
1702: +     snes - the SNES context
1703: .     x    - state at which to evaluate residual
1704: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1706:      Output Parameter:
1707: .     f  - vector to put residual (function value)

1709:    Level: intermediate

1711: .seealso:   SNESSetFunction(), SNESGetFunction()
1712: M*/

1714: /*@C
1715:    SNESSetFunction - Sets the function evaluation routine and function
1716:    vector for use by the SNES routines in solving systems of nonlinear
1717:    equations.

1719:    Logically Collective on SNES

1721:    Input Parameters:
1722: +  snes - the SNES context
1723: .  r - vector to store function value
1724: .  f - function evaluation routine; see SNESFunction for calling sequence details
1725: -  ctx - [optional] user-defined context for private data for the
1726:          function evaluation routine (may be NULL)

1728:    Notes:
1729:    The Newton-like methods typically solve linear systems of the form
1730: $      f'(x) x = -f(x),
1731:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1733:    Level: beginner

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

1737: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1738: @*/
1739: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1740: {
1742:   DM             dm;

1746:   if (r) {
1749:     PetscObjectReference((PetscObject)r);
1750:     VecDestroy(&snes->vec_func);

1752:     snes->vec_func = r;
1753:   }
1754:   SNESGetDM(snes,&dm);
1755:   DMSNESSetFunction(dm,f,ctx);
1756:   return(0);
1757: }


1760: /*@C
1761:    SNESSetInitialFunction - Sets the function vector to be used as the
1762:    function norm at the initialization of the method.  In some
1763:    instances, the user has precomputed the function before calling
1764:    SNESSolve.  This function allows one to avoid a redundant call
1765:    to SNESComputeFunction in that case.

1767:    Logically Collective on SNES

1769:    Input Parameters:
1770: +  snes - the SNES context
1771: -  f - vector to store function value

1773:    Notes:
1774:    This should not be modified during the solution procedure.

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

1778:    Level: developer

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

1782: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1783: @*/
1784: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1785: {
1787:   Vec            vec_func;

1793:   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1794:     snes->vec_func_init_set = PETSC_FALSE;
1795:     return(0);
1796:   }
1797:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1798:   VecCopy(f, vec_func);

1800:   snes->vec_func_init_set = PETSC_TRUE;
1801:   return(0);
1802: }

1804: /*@
1805:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1806:    of the SNES method.

1808:    Logically Collective on SNES

1810:    Input Parameters:
1811: +  snes - the SNES context
1812: -  normschedule - the frequency of norm computation

1814:    Options Database Key:
1815: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1826:    Level: developer

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

1830: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1831: @*/
1832: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1833: {
1836:   snes->normschedule = normschedule;
1837:   return(0);
1838: }


1841: /*@
1842:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1843:    of the SNES method.

1845:    Logically Collective on SNES

1847:    Input Parameters:
1848: +  snes - the SNES context
1849: -  normschedule - the type of the norm used

1851:    Level: advanced

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

1855: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1856: @*/
1857: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1858: {
1861:   *normschedule = snes->normschedule;
1862:   return(0);
1863: }


1866: /*@
1867:   SNESSetFunctionNorm - Sets the last computed residual norm.

1869:   Logically Collective on SNES

1871:   Input Parameters:
1872: + snes - the SNES context

1874: - normschedule - the frequency of norm computation

1876:   Level: developer

1878: .keywords: SNES, nonlinear, set, function, norm, type
1879: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1880: @*/
1881: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1882: {
1885:   snes->norm = norm;
1886:   return(0);
1887: }

1889: /*@
1890:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1892:   Not Collective

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

1897:   Output Parameter:
1898: . norm - the last computed residual norm

1900:   Level: developer

1902: .keywords: SNES, nonlinear, set, function, norm, type
1903: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1904: @*/
1905: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1906: {
1910:   *norm = snes->norm;
1911:   return(0);
1912: }

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

1918:    Logically Collective on SNES

1920:    Input Parameters:
1921: +  snes - the SNES context
1922: -  normschedule - the frequency of norm computation

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

1933:    Level: developer

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

1937: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1938: @*/
1939: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1940: {
1943:   snes->functype = type;
1944:   return(0);
1945: }


1948: /*@C
1949:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1950:    of the SNES method.

1952:    Logically Collective on SNES

1954:    Input Parameters:
1955: +  snes - the SNES context
1956: -  normschedule - the type of the norm used

1958:    Level: advanced

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

1962: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1963: @*/
1964: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
1965: {
1968:   *type = snes->functype;
1969:   return(0);
1970: }

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

1975:      Synopsis:
1976:      #include <petscsnes.h>
1977: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1979: +  X   - solution vector
1980: .  B   - RHS vector
1981: -  ctx - optional user-defined Gauss-Seidel context

1983:    Level: intermediate

1985: .seealso:   SNESSetNGS(), SNESGetNGS()
1986: M*/

1988: /*@C
1989:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1990:    use with composed nonlinear solvers.

1992:    Input Parameters:
1993: +  snes   - the SNES context
1994: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
1995: -  ctx    - [optional] user-defined context for private data for the
1996:             smoother evaluation routine (may be NULL)

1998:    Notes:
1999:    The NGS routines are used by the composed nonlinear solver to generate
2000:     a problem appropriate update to the solution, particularly FAS.

2002:    Level: intermediate

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

2006: .seealso: SNESGetFunction(), SNESComputeNGS()
2007: @*/
2008: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
2009: {
2011:   DM             dm;

2015:   SNESGetDM(snes,&dm);
2016:   DMSNESSetNGS(dm,f,ctx);
2017:   return(0);
2018: }

2020: PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
2021: {
2023:   DM             dm;
2024:   DMSNES         sdm;

2027:   SNESGetDM(snes,&dm);
2028:   DMGetDMSNES(dm,&sdm);
2029:   if (!sdm->ops->computepfunction) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");
2030:   if (!sdm->ops->computepjacobian) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard Jacobian.");
2031:   /*  A(x)*x - b(x) */
2032:   PetscStackPush("SNES Picard user function");
2033:   (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
2034:   PetscStackPop;
2035:   PetscStackPush("SNES Picard user Jacobian");
2036:   (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
2037:   PetscStackPop;
2038:   VecScale(f,-1.0);
2039:   MatMultAdd(snes->jacobian,x,f,f);
2040:   return(0);
2041: }

2043: PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
2044: {
2046:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2047:   return(0);
2048: }

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

2053:    Logically Collective on SNES

2055:    Input Parameters:
2056: +  snes - the SNES context
2057: .  r - vector to store function value
2058: .  b - function evaluation routine
2059: .  Amat - matrix with which A(x) x - b(x) is to be computed
2060: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
2061: .  J  - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
2062: -  ctx - [optional] user-defined context for private data for the
2063:          function evaluation routine (may be NULL)

2065:    Notes:
2066:     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
2067:     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.

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

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

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

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

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

2083:    Level: intermediate

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

2087: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2088: @*/
2089: 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)
2090: {
2092:   DM             dm;

2096:   SNESGetDM(snes, &dm);
2097:   DMSNESSetPicard(dm,b,J,ctx);
2098:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2099:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2100:   return(0);
2101: }

2103: /*@C
2104:    SNESGetPicard - Returns the context for the Picard iteration

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

2108:    Input Parameter:
2109: .  snes - the SNES context

2111:    Output Parameter:
2112: +  r - the function (or NULL)
2113: .  f - the function (or NULL); see SNESFunction for calling sequence details
2114: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2115: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2116: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2117: -  ctx - the function context (or NULL)

2119:    Level: advanced

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

2123: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2124: @*/
2125: 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)
2126: {
2128:   DM             dm;

2132:   SNESGetFunction(snes,r,NULL,NULL);
2133:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2134:   SNESGetDM(snes,&dm);
2135:   DMSNESGetPicard(dm,f,J,ctx);
2136:   return(0);
2137: }

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

2142:    Logically Collective on SNES

2144:    Input Parameters:
2145: +  snes - the SNES context
2146: .  func - function evaluation routine
2147: -  ctx - [optional] user-defined context for private data for the
2148:          function evaluation routine (may be NULL)

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

2153: .  f - function vector
2154: -  ctx - optional user-defined function context

2156:    Level: intermediate

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

2160: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2161: @*/
2162: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2163: {
2166:   if (func) snes->ops->computeinitialguess = func;
2167:   if (ctx)  snes->initialguessP            = ctx;
2168:   return(0);
2169: }

2171: /* --------------------------------------------------------------- */
2172: /*@C
2173:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2174:    it assumes a zero right hand side.

2176:    Logically Collective on SNES

2178:    Input Parameter:
2179: .  snes - the SNES context

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

2184:    Level: intermediate

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

2188: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2189: @*/
2190: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2191: {
2195:   *rhs = snes->vec_rhs;
2196:   return(0);
2197: }

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

2202:    Collective on SNES

2204:    Input Parameters:
2205: +  snes - the SNES context
2206: -  x - input vector

2208:    Output Parameter:
2209: .  y - function vector, as set by SNESSetFunction()

2211:    Notes:
2212:    SNESComputeFunction() is typically used within nonlinear solvers
2213:    implementations, so most users would not generally call this routine
2214:    themselves.

2216:    Level: developer

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

2220: .seealso: SNESSetFunction(), SNESGetFunction()
2221: @*/
2222: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2223: {
2225:   DM             dm;
2226:   DMSNES         sdm;

2234:   VecValidValues(x,2,PETSC_TRUE);

2236:   SNESGetDM(snes,&dm);
2237:   DMGetDMSNES(dm,&sdm);
2238:   if (sdm->ops->computefunction) {
2239:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2240:       PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2241:     }
2242:     VecLockPush(x);
2243:     PetscStackPush("SNES user function");
2244:     (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);
2245:     PetscStackPop;
2246:     VecLockPop(x);
2247:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2248:       PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2249:     }
2250:   } else if (snes->vec_rhs) {
2251:     MatMult(snes->jacobian, x, y);
2252:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2253:   if (snes->vec_rhs) {
2254:     VecAXPY(y,-1.0,snes->vec_rhs);
2255:   }
2256:   snes->nfuncs++;
2257:   /*
2258:      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2259:      propagate the value to all processes
2260:   */
2261:   if (snes->domainerror) {
2262:     VecSetInf(y);
2263:   }
2264:   return(0);
2265: }

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

2270:    Collective on SNES

2272:    Input Parameters:
2273: +  snes - the SNES context
2274: .  x - input vector
2275: -  b - rhs vector

2277:    Output Parameter:
2278: .  x - new solution vector

2280:    Notes:
2281:    SNESComputeNGS() is typically used within composed nonlinear solver
2282:    implementations, so most users would not generally call this routine
2283:    themselves.

2285:    Level: developer

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

2289: .seealso: SNESSetNGS(), SNESComputeFunction()
2290: @*/
2291: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2292: {
2294:   DM             dm;
2295:   DMSNES         sdm;

2303:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2304:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2305:   SNESGetDM(snes,&dm);
2306:   DMGetDMSNES(dm,&sdm);
2307:   if (sdm->ops->computegs) {
2308:     if (b) {VecLockPush(b);}
2309:     PetscStackPush("SNES user NGS");
2310:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2311:     PetscStackPop;
2312:     if (b) {VecLockPop(b);}
2313:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2314:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2315:   return(0);
2316: }

2318: PetscErrorCode SNESTestJacobian(SNES snes)
2319: {
2320:   Mat               A,B,C,D,jacobian;
2321:   Vec               x = snes->vec_sol,f = snes->vec_func;
2322:   PetscErrorCode    ierr;
2323:   PetscReal         nrm,gnorm;
2324:   PetscReal         threshold = 1.e-5;
2325:   PetscInt          m,n,M,N;
2326:   void              *functx;
2327:   PetscBool         complete_print = PETSC_FALSE,threshold_print = PETSC_FALSE,test = PETSC_FALSE,flg;
2328:   PetscViewer       viewer,mviewer;
2329:   MPI_Comm          comm;
2330:   PetscInt          tabs;
2331:   static PetscBool  directionsprinted = PETSC_FALSE;
2332:   PetscViewerFormat format;

2335:   PetscObjectOptionsBegin((PetscObject)snes);
2336:   PetscOptionsName("-snes_test_jacobian","Compare hand-coded and finite difference Jacobians","None",&test);
2337:   PetscOptionsReal("-snes_test_jacobian", "Threshold for element difference between hand-coded and finite difference being meaningful", "None", threshold, &threshold,NULL);
2338:   PetscOptionsViewer("-snes_test_jacobian_view","View difference between hand-coded and finite difference Jacobians element entries","None",&mviewer,&format,&complete_print);
2339:   if (!complete_print) {
2340:     PetscOptionsViewer("-snes_test_jacobian_display","Display difference between hand-coded and finite difference Jacobians","None",&mviewer,&format,&complete_print);
2341:   }
2342:   /* for compatibility with PETSc 3.9 and older. */
2343:   PetscOptionsReal("-snes_test_jacobian_display_threshold", "Display difference between hand-coded and finite difference Jacobians which exceed input threshold", "None", threshold, &threshold, &threshold_print);
2344:   PetscOptionsEnd();
2345:   if (!test) return(0);

2347:   PetscObjectGetComm((PetscObject)snes,&comm);
2348:   PetscViewerASCIIGetStdout(comm,&viewer);
2349:   PetscViewerASCIIGetTab(viewer, &tabs);
2350:   PetscViewerASCIISetTab(viewer, ((PetscObject)snes)->tablevel);
2351:   PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian -------------\n");
2352:   if (!complete_print && !directionsprinted) {
2353:     PetscViewerASCIIPrintf(viewer,"  Run with -snes_test_jacobian_view and optionally -snes_test_jacobian <threshold> to show difference\n");
2354:     PetscViewerASCIIPrintf(viewer,"    of hand-coded and finite difference Jacobian entries greater than <threshold>.\n");
2355:   }
2356:   if (!directionsprinted) {
2357:     PetscViewerASCIIPrintf(viewer,"  Testing hand-coded Jacobian, if (for double precision runs) ||J - Jfd||_F/||J||_F is\n");
2358:     PetscViewerASCIIPrintf(viewer,"    O(1.e-8), the hand-coded Jacobian is probably correct.\n");
2359:     directionsprinted = PETSC_TRUE;
2360:   }
2361:   if (complete_print) {
2362:     PetscViewerPushFormat(mviewer,format);
2363:   }

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

2368:   PetscObjectTypeCompare((PetscObject)snes->jacobian,MATMFFD,&flg);
2369:   if (!flg) jacobian = snes->jacobian;
2370:   else jacobian = snes->jacobian_pre;

2372:   while (jacobian) {
2373:     PetscObjectTypeCompareAny((PetscObject)jacobian,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2374:     if (flg) {
2375:       A    = jacobian;
2376:       PetscObjectReference((PetscObject)A);
2377:     } else {
2378:       MatComputeExplicitOperator(jacobian,&A);
2379:     }

2381:     MatCreate(PetscObjectComm((PetscObject)A),&B);
2382:     MatGetSize(A,&M,&N);
2383:     MatGetLocalSize(A,&m,&n);
2384:     MatSetSizes(B,m,n,M,N);
2385:     MatSetType(B,((PetscObject)A)->type_name);
2386:     MatSetUp(B);
2387:     MatSetOption(B,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);

2389:     SNESGetFunction(snes,NULL,NULL,&functx);
2390:     SNESComputeJacobianDefault(snes,x,B,B,functx);

2392:     MatDuplicate(B,MAT_COPY_VALUES,&D);
2393:     MatAYPX(D,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2394:     MatNorm(D,NORM_FROBENIUS,&nrm);
2395:     MatNorm(A,NORM_FROBENIUS,&gnorm);
2396:     MatDestroy(&D);
2397:     if (!gnorm) gnorm = 1; /* just in case */
2398:     PetscViewerASCIIPrintf(viewer,"  ||J - Jfd||_F/||J||_F = %g, ||J - Jfd||_F = %g\n",(double)(nrm/gnorm),(double)nrm);

2400:     if (complete_print) {
2401:       PetscViewerASCIIPrintf(viewer,"  Hand-coded Jacobian ----------\n");
2402:       MatView(jacobian,mviewer);
2403:       PetscViewerASCIIPrintf(viewer,"  Finite difference Jacobian ----------\n");
2404:       MatView(B,mviewer);
2405:     }

2407:     if (threshold_print) {
2408:       PetscInt          Istart, Iend, *ccols, bncols, cncols, j, row;
2409:       PetscScalar       *cvals;
2410:       const PetscInt    *bcols;
2411:       const PetscScalar *bvals;

2413:       MatAYPX(B,-1.0,A,DIFFERENT_NONZERO_PATTERN);
2414:       MatCreate(PetscObjectComm((PetscObject)A),&C);
2415:       MatSetSizes(C,m,n,M,N);
2416:       MatSetType(C,((PetscObject)A)->type_name);
2417:       MatSetUp(C);
2418:       MatSetOption(C,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
2419:       MatGetOwnershipRange(B,&Istart,&Iend);

2421:       for (row = Istart; row < Iend; row++) {
2422:         MatGetRow(B,row,&bncols,&bcols,&bvals);
2423:         PetscMalloc2(bncols,&ccols,bncols,&cvals);
2424:         for (j = 0, cncols = 0; j < bncols; j++) {
2425:           if (PetscAbsScalar(bvals[j]) > threshold) {
2426:             ccols[cncols] = bcols[j];
2427:             cvals[cncols] = bvals[j];
2428:             cncols += 1;
2429:           }
2430:         }
2431:         if (cncols) {
2432:           MatSetValues(C,1,&row,cncols,ccols,cvals,INSERT_VALUES);
2433:         }
2434:         MatRestoreRow(B,row,&bncols,&bcols,&bvals);
2435:         PetscFree2(ccols,cvals);
2436:       }
2437:       MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
2438:       MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
2439:       PetscViewerASCIIPrintf(viewer,"  Hand-coded minus finite-difference Jacobian with tolerance %g ----------\n",(double)threshold);
2440:       MatView(C,complete_print ? mviewer : viewer);
2441:       MatDestroy(&C);
2442:     }
2443:     MatDestroy(&A);
2444:     MatDestroy(&B);

2446:     if (jacobian != snes->jacobian_pre) {
2447:       jacobian = snes->jacobian_pre;
2448:       PetscViewerASCIIPrintf(viewer,"  ---------- Testing Jacobian for preconditioner -------------\n");
2449:     }
2450:     else jacobian = NULL;
2451:   }
2452:   if (complete_print) {
2453:     PetscViewerPopFormat(mviewer);
2454:   }
2455:   PetscViewerASCIISetTab(viewer,tabs);
2456:   return(0);
2457: }

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

2462:    Collective on SNES and Mat

2464:    Input Parameters:
2465: +  snes - the SNES context
2466: -  x - input vector

2468:    Output Parameters:
2469: +  A - Jacobian matrix
2470: -  B - optional preconditioning matrix

2472:   Options Database Keys:
2473: +    -snes_lag_preconditioner <lag>
2474: .    -snes_lag_jacobian <lag>
2475: .    -snes_test_jacobian - compare the user provided Jacobian with one compute via finite differences to check for errors
2476: .    -snes_test_jacobian_display - display the user provided Jacobian, the finite difference Jacobian and the difference between them to help users detect the location of errors in the user provided Jacobian
2477: .    -snes_test_jacobian_display_threshold <numerical value>  - display entries in the difference between the user provided Jacobian and finite difference Jacobian that are greater than a certain value to help users detect errors
2478: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2479: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2480: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2481: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2482: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2483: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2484: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2485: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2486: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2487: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2488: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2491:    Notes:
2492:    Most users should not need to explicitly call this routine, as it
2493:    is used internally within the nonlinear solvers.

2495:    Developer Notes:
2496:     This has duplicative ways of checking the accuracy of the user provided Jacobian (see the options above). This is for historical reasons, the routine SNESTestJacobian() use to used 
2497:       for with the SNESType of test that has been removed.

2499:    Level: developer

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

2503: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2504: @*/
2505: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2506: {
2508:   PetscBool      flag;
2509:   DM             dm;
2510:   DMSNES         sdm;
2511:   KSP            ksp;

2517:   VecValidValues(X,2,PETSC_TRUE);
2518:   SNESGetDM(snes,&dm);
2519:   DMGetDMSNES(dm,&sdm);

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

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

2525:   if (snes->lagjacobian == -2) {
2526:     snes->lagjacobian = -1;

2528:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2529:   } else if (snes->lagjacobian == -1) {
2530:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2531:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2532:     if (flag) {
2533:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2534:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2535:     }
2536:     return(0);
2537:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2538:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2539:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2540:     if (flag) {
2541:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2542:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2543:     }
2544:     return(0);
2545:   }
2546:   if (snes->npc && snes->npcside== PC_LEFT) {
2547:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2548:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2549:       return(0);
2550:   }

2552:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2553:   VecLockPush(X);
2554:   PetscStackPush("SNES user Jacobian function");
2555:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2556:   PetscStackPop;
2557:   VecLockPop(X);
2558:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2560:   /* the next line ensures that snes->ksp exists */
2561:   SNESGetKSP(snes,&ksp);
2562:   if (snes->lagpreconditioner == -2) {
2563:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2564:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2565:     snes->lagpreconditioner = -1;
2566:   } else if (snes->lagpreconditioner == -1) {
2567:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2568:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2569:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2570:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2571:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2572:   } else {
2573:     PetscInfo(snes,"Rebuilding preconditioner\n");
2574:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2575:   }

2577:   SNESTestJacobian(snes);
2578:   /* make sure user returned a correct Jacobian and preconditioner */
2581:   {
2582:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2583:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2584:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2585:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2586:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2587:     if (flag || flag_draw || flag_contour) {
2588:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2589:       PetscViewer  vdraw,vstdout;
2590:       PetscBool    flg;
2591:       if (flag_operator) {
2592:         MatComputeExplicitOperator(A,&Bexp_mine);
2593:         Bexp = Bexp_mine;
2594:       } else {
2595:         /* See if the preconditioning matrix can be viewed and added directly */
2596:         PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2597:         if (flg) Bexp = B;
2598:         else {
2599:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2600:           MatComputeExplicitOperator(B,&Bexp_mine);
2601:           Bexp = Bexp_mine;
2602:         }
2603:       }
2604:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2605:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2606:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2607:       if (flag_draw || flag_contour) {
2608:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2609:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2610:       } else vdraw = NULL;
2611:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2612:       if (flag) {MatView(Bexp,vstdout);}
2613:       if (vdraw) {MatView(Bexp,vdraw);}
2614:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2615:       if (flag) {MatView(FDexp,vstdout);}
2616:       if (vdraw) {MatView(FDexp,vdraw);}
2617:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2618:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2619:       if (flag) {MatView(FDexp,vstdout);}
2620:       if (vdraw) {              /* Always use contour for the difference */
2621:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2622:         MatView(FDexp,vdraw);
2623:         PetscViewerPopFormat(vdraw);
2624:       }
2625:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2626:       PetscViewerDestroy(&vdraw);
2627:       MatDestroy(&Bexp_mine);
2628:       MatDestroy(&FDexp);
2629:     }
2630:   }
2631:   {
2632:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2633:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2634:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2635:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2636:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2637:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2638:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2639:     if (flag_threshold) {
2640:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2641:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2642:     }
2643:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2644:       Mat            Bfd;
2645:       PetscViewer    vdraw,vstdout;
2646:       MatColoring    coloring;
2647:       ISColoring     iscoloring;
2648:       MatFDColoring  matfdcoloring;
2649:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2650:       void           *funcctx;
2651:       PetscReal      norm1,norm2,normmax;

2653:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2654:       MatColoringCreate(Bfd,&coloring);
2655:       MatColoringSetType(coloring,MATCOLORINGSL);
2656:       MatColoringSetFromOptions(coloring);
2657:       MatColoringApply(coloring,&iscoloring);
2658:       MatColoringDestroy(&coloring);
2659:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2660:       MatFDColoringSetFromOptions(matfdcoloring);
2661:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2662:       ISColoringDestroy(&iscoloring);

2664:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2665:       SNESGetFunction(snes,NULL,&func,&funcctx);
2666:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2667:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2668:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2669:       MatFDColoringSetFromOptions(matfdcoloring);
2670:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2671:       MatFDColoringDestroy(&matfdcoloring);

2673:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2674:       if (flag_draw || flag_contour) {
2675:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2676:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2677:       } else vdraw = NULL;
2678:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2679:       if (flag_display) {MatView(B,vstdout);}
2680:       if (vdraw) {MatView(B,vdraw);}
2681:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2682:       if (flag_display) {MatView(Bfd,vstdout);}
2683:       if (vdraw) {MatView(Bfd,vdraw);}
2684:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2685:       MatNorm(Bfd,NORM_1,&norm1);
2686:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2687:       MatNorm(Bfd,NORM_MAX,&normmax);
2688:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2689:       if (flag_display) {MatView(Bfd,vstdout);}
2690:       if (vdraw) {              /* Always use contour for the difference */
2691:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2692:         MatView(Bfd,vdraw);
2693:         PetscViewerPopFormat(vdraw);
2694:       }
2695:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2697:       if (flag_threshold) {
2698:         PetscInt bs,rstart,rend,i;
2699:         MatGetBlockSize(B,&bs);
2700:         MatGetOwnershipRange(B,&rstart,&rend);
2701:         for (i=rstart; i<rend; i++) {
2702:           const PetscScalar *ba,*ca;
2703:           const PetscInt    *bj,*cj;
2704:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2705:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2706:           MatGetRow(B,i,&bn,&bj,&ba);
2707:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2708:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2709:           for (j=0; j<bn; j++) {
2710:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2711:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2712:               maxentrycol = bj[j];
2713:               maxentry    = PetscRealPart(ba[j]);
2714:             }
2715:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2716:               maxdiffcol = bj[j];
2717:               maxdiff    = PetscRealPart(ca[j]);
2718:             }
2719:             if (rdiff > maxrdiff) {
2720:               maxrdiffcol = bj[j];
2721:               maxrdiff    = rdiff;
2722:             }
2723:           }
2724:           if (maxrdiff > 1) {
2725:             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);
2726:             for (j=0; j<bn; j++) {
2727:               PetscReal rdiff;
2728:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2729:               if (rdiff > 1) {
2730:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2731:               }
2732:             }
2733:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2734:           }
2735:           MatRestoreRow(B,i,&bn,&bj,&ba);
2736:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2737:         }
2738:       }
2739:       PetscViewerDestroy(&vdraw);
2740:       MatDestroy(&Bfd);
2741:     }
2742:   }
2743:   return(0);
2744: }

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

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

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

2758:    Level: intermediate

2760: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2761: M*/

2763: /*@C
2764:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2765:    location to store the matrix.

2767:    Logically Collective on SNES and Mat

2769:    Input Parameters:
2770: +  snes - the SNES context
2771: .  Amat - the matrix that defines the (approximate) Jacobian
2772: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2773: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2774: -  ctx - [optional] user-defined context for private data for the
2775:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2777:    Notes:
2778:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2779:    each matrix.

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

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

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

2790:    Level: beginner

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

2794: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J,
2795:           SNESSetPicard(), SNESJacobianFunction
2796: @*/
2797: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2798: {
2800:   DM             dm;

2808:   SNESGetDM(snes,&dm);
2809:   DMSNESSetJacobian(dm,J,ctx);
2810:   if (Amat) {
2811:     PetscObjectReference((PetscObject)Amat);
2812:     MatDestroy(&snes->jacobian);

2814:     snes->jacobian = Amat;
2815:   }
2816:   if (Pmat) {
2817:     PetscObjectReference((PetscObject)Pmat);
2818:     MatDestroy(&snes->jacobian_pre);

2820:     snes->jacobian_pre = Pmat;
2821:   }
2822:   return(0);
2823: }

2825: /*@C
2826:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2827:    provided context for evaluating the Jacobian.

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

2831:    Input Parameter:
2832: .  snes - the nonlinear solver context

2834:    Output Parameters:
2835: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2836: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2837: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2838: -  ctx - location to stash Jacobian ctx (or NULL)

2840:    Level: advanced

2842: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2843: @*/
2844: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2845: {
2847:   DM             dm;
2848:   DMSNES         sdm;

2852:   if (Amat) *Amat = snes->jacobian;
2853:   if (Pmat) *Pmat = snes->jacobian_pre;
2854:   SNESGetDM(snes,&dm);
2855:   DMGetDMSNES(dm,&sdm);
2856:   if (J) *J = sdm->ops->computejacobian;
2857:   if (ctx) *ctx = sdm->jacobianctx;
2858:   return(0);
2859: }

2861: /*@
2862:    SNESSetUp - Sets up the internal data structures for the later use
2863:    of a nonlinear solver.

2865:    Collective on SNES

2867:    Input Parameters:
2868: .  snes - the SNES context

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

2877:    Level: advanced

2879: .keywords: SNES, nonlinear, setup

2881: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2882: @*/
2883: PetscErrorCode  SNESSetUp(SNES snes)
2884: {
2886:   DM             dm;
2887:   DMSNES         sdm;
2888:   SNESLineSearch linesearch, pclinesearch;
2889:   void           *lsprectx,*lspostctx;
2890:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2891:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2892:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2893:   Vec            f,fpc;
2894:   void           *funcctx;
2895:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2896:   void           *jacctx,*appctx;
2897:   Mat            j,jpre;

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

2903:   if (!((PetscObject)snes)->type_name) {
2904:     SNESSetType(snes,SNESNEWTONLS);
2905:   }

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

2909:   SNESGetDM(snes,&dm);
2910:   DMGetDMSNES(dm,&sdm);
2911:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2912:   if (!sdm->ops->computejacobian) {
2913:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2914:   }
2915:   if (!snes->vec_func) {
2916:     DMCreateGlobalVector(dm,&snes->vec_func);
2917:   }

2919:   if (!snes->ksp) {
2920:     SNESGetKSP(snes, &snes->ksp);
2921:   }

2923:   if (!snes->linesearch) {
2924:     SNESGetLineSearch(snes, &snes->linesearch);
2925:   }
2926:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2928:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2929:     snes->mf          = PETSC_TRUE;
2930:     snes->mf_operator = PETSC_FALSE;
2931:   }

2933:   if (snes->npc) {
2934:     /* copy the DM over */
2935:     SNESGetDM(snes,&dm);
2936:     SNESSetDM(snes->npc,dm);

2938:     SNESGetFunction(snes,&f,&func,&funcctx);
2939:     VecDuplicate(f,&fpc);
2940:     SNESSetFunction(snes->npc,fpc,func,funcctx);
2941:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2942:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
2943:     SNESGetApplicationContext(snes,&appctx);
2944:     SNESSetApplicationContext(snes->npc,appctx);
2945:     VecDestroy(&fpc);

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

2950:     /* default to 1 iteration */
2951:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
2952:     if (snes->npcside==PC_RIGHT) {
2953:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
2954:     } else {
2955:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
2956:     }
2957:     SNESSetFromOptions(snes->npc);

2959:     /* copy the line search context over */
2960:     SNESGetLineSearch(snes,&linesearch);
2961:     SNESGetLineSearch(snes->npc,&pclinesearch);
2962:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2963:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2964:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2965:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2966:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2967:   }
2968:   if (snes->mf) {
2969:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2970:   }
2971:   if (snes->ops->usercompute && !snes->user) {
2972:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2973:   }

2975:   snes->jac_iter = 0;
2976:   snes->pre_iter = 0;

2978:   if (snes->ops->setup) {
2979:     (*snes->ops->setup)(snes);
2980:   }

2982:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2983:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2984:       SNESGetLineSearch(snes,&linesearch);
2985:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2986:     }
2987:   }

2989:   snes->setupcalled = PETSC_TRUE;
2990:   return(0);
2991: }

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

2996:    Collective on SNES

2998:    Input Parameter:
2999: .  snes - iterative context obtained from SNESCreate()

3001:    Level: intermediate

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

3006: .keywords: SNES, destroy

3008: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
3009: @*/
3010: PetscErrorCode  SNESReset(SNES snes)
3011: {

3016:   if (snes->ops->userdestroy && snes->user) {
3017:     (*snes->ops->userdestroy)((void**)&snes->user);
3018:     snes->user = NULL;
3019:   }
3020:   if (snes->npc) {
3021:     SNESReset(snes->npc);
3022:   }

3024:   if (snes->ops->reset) {
3025:     (*snes->ops->reset)(snes);
3026:   }
3027:   if (snes->ksp) {
3028:     KSPReset(snes->ksp);
3029:   }

3031:   if (snes->linesearch) {
3032:     SNESLineSearchReset(snes->linesearch);
3033:   }

3035:   VecDestroy(&snes->vec_rhs);
3036:   VecDestroy(&snes->vec_sol);
3037:   VecDestroy(&snes->vec_sol_update);
3038:   VecDestroy(&snes->vec_func);
3039:   MatDestroy(&snes->jacobian);
3040:   MatDestroy(&snes->jacobian_pre);
3041:   VecDestroyVecs(snes->nwork,&snes->work);
3042:   VecDestroyVecs(snes->nvwork,&snes->vwork);

3044:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

3046:   snes->nwork       = snes->nvwork = 0;
3047:   snes->setupcalled = PETSC_FALSE;
3048:   return(0);
3049: }

3051: /*@
3052:    SNESDestroy - Destroys the nonlinear solver context that was created
3053:    with SNESCreate().

3055:    Collective on SNES

3057:    Input Parameter:
3058: .  snes - the SNES context

3060:    Level: beginner

3062: .keywords: SNES, nonlinear, destroy

3064: .seealso: SNESCreate(), SNESSolve()
3065: @*/
3066: PetscErrorCode  SNESDestroy(SNES *snes)
3067: {

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

3075:   SNESReset((*snes));
3076:   SNESDestroy(&(*snes)->npc);

3078:   /* if memory was published with SAWs then destroy it */
3079:   PetscObjectSAWsViewOff((PetscObject)*snes);
3080:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

3082:   if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
3083:   DMDestroy(&(*snes)->dm);
3084:   KSPDestroy(&(*snes)->ksp);
3085:   SNESLineSearchDestroy(&(*snes)->linesearch);

3087:   PetscFree((*snes)->kspconvctx);
3088:   if ((*snes)->ops->convergeddestroy) {
3089:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
3090:   }
3091:   if ((*snes)->conv_malloc) {
3092:     PetscFree((*snes)->conv_hist);
3093:     PetscFree((*snes)->conv_hist_its);
3094:   }
3095:   SNESMonitorCancel((*snes));
3096:   PetscHeaderDestroy(snes);
3097:   return(0);
3098: }

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

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

3105:    Logically Collective on SNES

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

3112:    Options Database Keys:
3113: .    -snes_lag_preconditioner <lag>

3115:    Notes:
3116:    The default is 1
3117:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
3118:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

3120:    Level: intermediate

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

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

3126: @*/
3127: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
3128: {
3131:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3132:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3134:   snes->lagpreconditioner = lag;
3135:   return(0);
3136: }

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

3141:    Logically Collective on SNES

3143:    Input Parameters:
3144: +  snes - the SNES context
3145: -  steps - the number of refinements to do, defaults to 0

3147:    Options Database Keys:
3148: .    -snes_grid_sequence <steps>

3150:    Level: intermediate

3152:    Notes:
3153:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

3159: @*/
3160: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
3161: {
3165:   snes->gridsequence = steps;
3166:   return(0);
3167: }

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

3172:    Logically Collective on SNES

3174:    Input Parameter:
3175: .  snes - the SNES context

3177:    Output Parameter:
3178: .  steps - the number of refinements to do, defaults to 0

3180:    Options Database Keys:
3181: .    -snes_grid_sequence <steps>

3183:    Level: intermediate

3185:    Notes:
3186:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

3192: @*/
3193: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3194: {
3197:   *steps = snes->gridsequence;
3198:   return(0);
3199: }

3201: /*@
3202:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3204:    Not Collective

3206:    Input Parameter:
3207: .  snes - the SNES context

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

3213:    Options Database Keys:
3214: .    -snes_lag_preconditioner <lag>

3216:    Notes:
3217:    The default is 1
3218:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3220:    Level: intermediate

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

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

3226: @*/
3227: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3228: {
3231:   *lag = snes->lagpreconditioner;
3232:   return(0);
3233: }

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

3239:    Logically Collective on SNES

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

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

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

3255:    Level: intermediate

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

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

3261: @*/
3262: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3263: {
3266:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3267:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3269:   snes->lagjacobian = lag;
3270:   return(0);
3271: }

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

3276:    Not Collective

3278:    Input Parameter:
3279: .  snes - the SNES context

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

3285:    Options Database Keys:
3286: .    -snes_lag_jacobian <lag>

3288:    Notes:
3289:    The default is 1
3290:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3292:    Level: intermediate

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

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

3298: @*/
3299: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3300: {
3303:   *lag = snes->lagjacobian;
3304:   return(0);
3305: }

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

3310:    Logically collective on SNES

3312:    Input Parameter:
3313: +  snes - the SNES context
3314: -   flg - jacobian lagging persists if true

3316:    Options Database Keys:
3317: .    -snes_lag_jacobian_persists <flg>

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

3324:    Level: developer

3326: .keywords: SNES, nonlinear, lag

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

3330: @*/
3331: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3332: {
3336:   snes->lagjac_persist = flg;
3337:   return(0);
3338: }

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

3343:    Logically Collective on SNES

3345:    Input Parameter:
3346: +  snes - the SNES context
3347: -   flg - preconditioner lagging persists if true

3349:    Options Database Keys:
3350: .    -snes_lag_jacobian_persists <flg>

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

3357:    Level: developer

3359: .keywords: SNES, nonlinear, lag

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

3363: @*/
3364: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3365: {
3369:   snes->lagpre_persist = flg;
3370:   return(0);
3371: }

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

3376:    Logically Collective on SNES

3378:    Input Parameters:
3379: +  snes - the SNES context
3380: -  force - PETSC_TRUE require at least one iteration

3382:    Options Database Keys:
3383: .    -snes_force_iteration <force> - Sets forcing an iteration

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

3388:    Level: intermediate

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

3392: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3393: @*/
3394: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3395: {
3398:   snes->forceiteration = force;
3399:   return(0);
3400: }

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

3405:    Logically Collective on SNES

3407:    Input Parameters:
3408: .  snes - the SNES context

3410:    Output Parameter:
3411: .  force - PETSC_TRUE requires at least one iteration.

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

3415:    Level: intermediate

3417: .seealso: SNESSetForceIteration(), SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3418: @*/
3419: PetscErrorCode  SNESGetForceIteration(SNES snes,PetscBool *force)
3420: {
3423:   *force = snes->forceiteration;
3424:   return(0);
3425: }

3427: /*@
3428:    SNESSetTolerances - Sets various parameters used in convergence tests.

3430:    Logically Collective on SNES

3432:    Input Parameters:
3433: +  snes - the SNES context
3434: .  abstol - absolute convergence tolerance
3435: .  rtol - relative convergence tolerance
3436: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3437: .  maxit - maximum number of iterations
3438: -  maxf - maximum number of function evaluations (-1 indicates no limit)

3440:    Options Database Keys:
3441: +    -snes_atol <abstol> - Sets abstol
3442: .    -snes_rtol <rtol> - Sets rtol
3443: .    -snes_stol <stol> - Sets stol
3444: .    -snes_max_it <maxit> - Sets maxit
3445: -    -snes_max_funcs <maxf> - Sets maxf

3447:    Notes:
3448:    The default maximum number of iterations is 50.
3449:    The default maximum number of function evaluations is 1000.

3451:    Level: intermediate

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

3455: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3456: @*/
3457: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3458: {

3467:   if (abstol != PETSC_DEFAULT) {
3468:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3469:     snes->abstol = abstol;
3470:   }
3471:   if (rtol != PETSC_DEFAULT) {
3472:     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);
3473:     snes->rtol = rtol;
3474:   }
3475:   if (stol != PETSC_DEFAULT) {
3476:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3477:     snes->stol = stol;
3478:   }
3479:   if (maxit != PETSC_DEFAULT) {
3480:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3481:     snes->max_its = maxit;
3482:   }
3483:   if (maxf != PETSC_DEFAULT) {
3484:     if (maxf < -1) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be -1 or nonnegative",maxf);
3485:     snes->max_funcs = maxf;
3486:   }
3487:   snes->tolerancesset = PETSC_TRUE;
3488:   return(0);
3489: }

3491: /*@
3492:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3494:    Logically Collective on SNES

3496:    Input Parameters:
3497: +  snes - the SNES context
3498: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3500:    Options Database Keys:
3501: +    -snes_divergence_tolerance <divtol> - Sets divtol

3503:    Notes:
3504:    The default divergence tolerance is 1e4.

3506:    Level: intermediate

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

3510: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3511: @*/
3512: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3513: {

3518:   if (divtol != PETSC_DEFAULT) {
3519:     snes->divtol = divtol;
3520:   }
3521:   else {
3522:     snes->divtol = 1.0e4;
3523:   }
3524:   return(0);
3525: }

3527: /*@
3528:    SNESGetTolerances - Gets various parameters used in convergence tests.

3530:    Not Collective

3532:    Input Parameters:
3533: +  snes - the SNES context
3534: .  atol - absolute convergence tolerance
3535: .  rtol - relative convergence tolerance
3536: .  stol -  convergence tolerance in terms of the norm
3537:            of the change in the solution between steps
3538: .  maxit - maximum number of iterations
3539: -  maxf - maximum number of function evaluations

3541:    Notes:
3542:    The user can specify NULL for any parameter that is not needed.

3544:    Level: intermediate

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

3548: .seealso: SNESSetTolerances()
3549: @*/
3550: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3551: {
3554:   if (atol)  *atol  = snes->abstol;
3555:   if (rtol)  *rtol  = snes->rtol;
3556:   if (stol)  *stol  = snes->stol;
3557:   if (maxit) *maxit = snes->max_its;
3558:   if (maxf)  *maxf  = snes->max_funcs;
3559:   return(0);
3560: }

3562: /*@
3563:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3565:    Not Collective

3567:    Input Parameters:
3568: +  snes - the SNES context
3569: -  divtol - divergence tolerance

3571:    Level: intermediate

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

3575: .seealso: SNESSetDivergenceTolerance()
3576: @*/
3577: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3578: {
3581:   if (divtol) *divtol = snes->divtol;
3582:   return(0);
3583: }

3585: /*@
3586:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3588:    Logically Collective on SNES

3590:    Input Parameters:
3591: +  snes - the SNES context
3592: -  tol - tolerance

3594:    Options Database Key:
3595: .  -snes_trtol <tol> - Sets tol

3597:    Level: intermediate

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

3601: .seealso: SNESSetTolerances()
3602: @*/
3603: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3604: {
3608:   snes->deltatol = tol;
3609:   return(0);
3610: }

3612: /*
3613:    Duplicate the lg monitors for SNES from KSP; for some reason with
3614:    dynamic libraries things don't work under Sun4 if we just use
3615:    macros instead of functions
3616: */
3617: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3618: {

3623:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3624:   return(0);
3625: }

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

3632:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3633:   return(0);
3634: }

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

3638: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3639: {
3640:   PetscDrawLG      lg;
3641:   PetscErrorCode   ierr;
3642:   PetscReal        x,y,per;
3643:   PetscViewer      v = (PetscViewer)monctx;
3644:   static PetscReal prev; /* should be in the context */
3645:   PetscDraw        draw;

3649:   PetscViewerDrawGetDrawLG(v,0,&lg);
3650:   if (!n) {PetscDrawLGReset(lg);}
3651:   PetscDrawLGGetDraw(lg,&draw);
3652:   PetscDrawSetTitle(draw,"Residual norm");
3653:   x    = (PetscReal)n;
3654:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3655:   else y = -15.0;
3656:   PetscDrawLGAddPoint(lg,&x,&y);
3657:   if (n < 20 || !(n % 5) || snes->reason) {
3658:     PetscDrawLGDraw(lg);
3659:     PetscDrawLGSave(lg);
3660:   }

3662:   PetscViewerDrawGetDrawLG(v,1,&lg);
3663:   if (!n) {PetscDrawLGReset(lg);}
3664:   PetscDrawLGGetDraw(lg,&draw);
3665:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3666:    SNESMonitorRange_Private(snes,n,&per);
3667:   x    = (PetscReal)n;
3668:   y    = 100.0*per;
3669:   PetscDrawLGAddPoint(lg,&x,&y);
3670:   if (n < 20 || !(n % 5) || snes->reason) {
3671:     PetscDrawLGDraw(lg);
3672:     PetscDrawLGSave(lg);
3673:   }

3675:   PetscViewerDrawGetDrawLG(v,2,&lg);
3676:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3677:   PetscDrawLGGetDraw(lg,&draw);
3678:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3679:   x    = (PetscReal)n;
3680:   y    = (prev - rnorm)/prev;
3681:   PetscDrawLGAddPoint(lg,&x,&y);
3682:   if (n < 20 || !(n % 5) || snes->reason) {
3683:     PetscDrawLGDraw(lg);
3684:     PetscDrawLGSave(lg);
3685:   }

3687:   PetscViewerDrawGetDrawLG(v,3,&lg);
3688:   if (!n) {PetscDrawLGReset(lg);}
3689:   PetscDrawLGGetDraw(lg,&draw);
3690:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3691:   x    = (PetscReal)n;
3692:   y    = (prev - rnorm)/(prev*per);
3693:   if (n > 2) { /*skip initial crazy value */
3694:     PetscDrawLGAddPoint(lg,&x,&y);
3695:   }
3696:   if (n < 20 || !(n % 5) || snes->reason) {
3697:     PetscDrawLGDraw(lg);
3698:     PetscDrawLGSave(lg);
3699:   }
3700:   prev = rnorm;
3701:   return(0);
3702: }

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

3707:    Collective on SNES

3709:    Input Parameters:
3710: +  snes - nonlinear solver context obtained from SNESCreate()
3711: .  iter - iteration number
3712: -  rnorm - relative norm of the residual

3714:    Notes:
3715:    This routine is called by the SNES implementations.
3716:    It does not typically need to be called by the user.

3718:    Level: developer

3720: .seealso: SNESMonitorSet()
3721: @*/
3722: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3723: {
3725:   PetscInt       i,n = snes->numbermonitors;

3728:   VecLockPush(snes->vec_sol);
3729:   for (i=0; i<n; i++) {
3730:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3731:   }
3732:   VecLockPop(snes->vec_sol);
3733:   return(0);
3734: }

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

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

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

3745: +    snes - the SNES context
3746: .    its - iteration number
3747: .    norm - 2-norm function value (may be estimated)
3748: -    mctx - [optional] monitoring context

3750:    Level: advanced

3752: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3753: M*/

3755: /*@C
3756:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3757:    iteration of the nonlinear solver to display the iteration's
3758:    progress.

3760:    Logically Collective on SNES

3762:    Input Parameters:
3763: +  snes - the SNES context
3764: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3765: .  mctx - [optional] user-defined context for private data for the
3766:           monitor routine (use NULL if no context is desired)
3767: -  monitordestroy - [optional] routine that frees monitor context
3768:           (may be NULL)

3770:    Options Database Keys:
3771: +    -snes_monitor        - sets SNESMonitorDefault()
3772: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3773:                             uses SNESMonitorLGCreate()
3774: -    -snes_monitor_cancel - cancels all monitors that have
3775:                             been hardwired into a code by
3776:                             calls to SNESMonitorSet(), but
3777:                             does not cancel those set via
3778:                             the options database.

3780:    Notes:
3781:    Several different monitoring routines may be set by calling
3782:    SNESMonitorSet() multiple times; all will be called in the
3783:    order in which they were set.

3785:    Fortran Notes:
3786:     Only a single monitor function can be set for each SNES object

3788:    Level: intermediate

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

3792: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3793: @*/
3794: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3795: {
3796:   PetscInt       i;
3798:   PetscBool      identical;

3802:   for (i=0; i<snes->numbermonitors;i++) {
3803:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3804:     if (identical) return(0);
3805:   }
3806:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3807:   snes->monitor[snes->numbermonitors]          = f;
3808:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3809:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3810:   return(0);
3811: }

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

3816:    Logically Collective on SNES

3818:    Input Parameters:
3819: .  snes - the SNES context

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

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

3829:    Level: intermediate

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

3833: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3834: @*/
3835: PetscErrorCode  SNESMonitorCancel(SNES snes)
3836: {
3838:   PetscInt       i;

3842:   for (i=0; i<snes->numbermonitors; i++) {
3843:     if (snes->monitordestroy[i]) {
3844:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3845:     }
3846:   }
3847:   snes->numbermonitors = 0;
3848:   return(0);
3849: }

3851: /*MC
3852:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3858: +    snes - the SNES context
3859: .    it - current iteration (0 is the first and is before any Newton step)
3860: .    cctx - [optional] convergence context
3861: .    reason - reason for convergence/divergence
3862: .    xnorm - 2-norm of current iterate
3863: .    gnorm - 2-norm of current step
3864: -    f - 2-norm of function

3866:    Level: intermediate

3868: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3869: M*/

3871: /*@C
3872:    SNESSetConvergenceTest - Sets the function that is to be used
3873:    to test for convergence of the nonlinear iterative solution.

3875:    Logically Collective on SNES

3877:    Input Parameters:
3878: +  snes - the SNES context
3879: .  SNESConvergenceTestFunction - routine to test for convergence
3880: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3881: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3883:    Level: advanced

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

3887: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3888: @*/
3889: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3890: {

3895:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3896:   if (snes->ops->convergeddestroy) {
3897:     (*snes->ops->convergeddestroy)(snes->cnvP);
3898:   }
3899:   snes->ops->converged        = SNESConvergenceTestFunction;
3900:   snes->ops->convergeddestroy = destroy;
3901:   snes->cnvP                  = cctx;
3902:   return(0);
3903: }

3905: /*@
3906:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3908:    Not Collective

3910:    Input Parameter:
3911: .  snes - the SNES context

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

3917:    Options Database:
3918: .   -snes_converged_reason - prints the reason to standard out

3920:    Level: intermediate

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

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

3927: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
3928: @*/
3929: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3930: {
3934:   *reason = snes->reason;
3935:   return(0);
3936: }

3938: /*@
3939:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3941:    Not Collective

3943:    Input Parameters:
3944: +  snes - the SNES context
3945: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
3946:             manual pages for the individual convergence tests for complete lists

3948:    Level: intermediate

3950: .keywords: SNES, nonlinear, set, convergence, test
3951: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
3952: @*/
3953: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
3954: {
3957:   snes->reason = reason;
3958:   return(0);
3959: }

3961: /*@
3962:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3964:    Logically Collective on SNES

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

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

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

3982:    Level: intermediate

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

3986: .seealso: SNESGetConvergenceHistory()

3988: @*/
3989: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3990: {

3997:   if (!a) {
3998:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3999:     PetscCalloc1(na,&a);
4000:     PetscCalloc1(na,&its);

4002:     snes->conv_malloc = PETSC_TRUE;
4003:   }
4004:   snes->conv_hist       = a;
4005:   snes->conv_hist_its   = its;
4006:   snes->conv_hist_max   = na;
4007:   snes->conv_hist_len   = 0;
4008:   snes->conv_hist_reset = reset;
4009:   return(0);
4010: }

4012: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4013: #include <engine.h>   /* MATLAB include file */
4014: #include <mex.h>      /* MATLAB include file */

4016: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
4017: {
4018:   mxArray   *mat;
4019:   PetscInt  i;
4020:   PetscReal *ar;

4023:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
4024:   ar  = (PetscReal*) mxGetData(mat);
4025:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
4026:   PetscFunctionReturn(mat);
4027: }
4028: #endif

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

4033:    Not Collective

4035:    Input Parameter:
4036: .  snes - iterative context obtained from SNESCreate()

4038:    Output Parameters:
4039: .  a   - array to hold history
4040: .  its - integer array holds the number of linear iterations (or
4041:          negative if not converged) for each solve.
4042: -  na  - size of a and its

4044:    Notes:
4045:     The calling sequence for this routine in Fortran is
4046: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

4052:    Level: intermediate

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

4056: .seealso: SNESSetConvergencHistory()

4058: @*/
4059: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
4060: {
4063:   if (a)   *a   = snes->conv_hist;
4064:   if (its) *its = snes->conv_hist_its;
4065:   if (na)  *na  = snes->conv_hist_len;
4066:   return(0);
4067: }

4069: /*@C
4070:   SNESSetUpdate - Sets the general-purpose update function called
4071:   at the beginning of every iteration of the nonlinear solve. Specifically
4072:   it is called just before the Jacobian is "evaluated".

4074:   Logically Collective on SNES

4076:   Input Parameters:
4077: . snes - The nonlinear solver context
4078: . func - The function

4080:   Calling sequence of func:
4081: . func (SNES snes, PetscInt step);

4083: . step - The current step of the iteration

4085:   Level: advanced

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

4090: .keywords: SNES, update

4092: .seealso SNESSetJacobian(), SNESSolve()
4093: @*/
4094: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
4095: {
4098:   snes->ops->update = func;
4099:   return(0);
4100: }

4102: /*
4103:    SNESScaleStep_Private - Scales a step so that its length is less than the
4104:    positive parameter delta.

4106:     Input Parameters:
4107: +   snes - the SNES context
4108: .   y - approximate solution of linear system
4109: .   fnorm - 2-norm of current function
4110: -   delta - trust region size

4112:     Output Parameters:
4113: +   gpnorm - predicted function norm at the new point, assuming local
4114:     linearization.  The value is zero if the step lies within the trust
4115:     region, and exceeds zero otherwise.
4116: -   ynorm - 2-norm of the step

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

4122: .keywords: SNES, nonlinear, scale, step
4123: */
4124: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
4125: {
4126:   PetscReal      nrm;
4127:   PetscScalar    cnorm;


4135:   VecNorm(y,NORM_2,&nrm);
4136:   if (nrm > *delta) {
4137:     nrm     = *delta/nrm;
4138:     *gpnorm = (1.0 - nrm)*(*fnorm);
4139:     cnorm   = nrm;
4140:     VecScale(y,cnorm);
4141:     *ynorm  = *delta;
4142:   } else {
4143:     *gpnorm = 0.0;
4144:     *ynorm  = nrm;
4145:   }
4146:   return(0);
4147: }

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

4152:    Collective on SNES

4154:    Parameter:
4155: +  snes - iterative context obtained from SNESCreate()
4156: -  viewer - the viewer to display the reason


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

4162:    Level: beginner

4164: .keywords: SNES, solve, linear system

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

4168: @*/
4169: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
4170: {
4171:   PetscViewerFormat format;
4172:   PetscBool         isAscii;
4173:   PetscErrorCode    ierr;

4176:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
4177:   if (isAscii) {
4178:     PetscViewerGetFormat(viewer, &format);
4179:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
4180:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
4181:       DM                dm;
4182:       Vec               u;
4183:       PetscDS           prob;
4184:       PetscInt          Nf, f;
4185:       PetscErrorCode (**exactFuncs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
4186:       PetscReal         error;

4188:       SNESGetDM(snes, &dm);
4189:       SNESGetSolution(snes, &u);
4190:       DMGetDS(dm, &prob);
4191:       PetscDSGetNumFields(prob, &Nf);
4192:       PetscMalloc1(Nf, &exactFuncs);
4193:       for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactFuncs[f]);}
4194:       DMComputeL2Diff(dm, 0.0, exactFuncs, NULL, u, &error);
4195:       PetscFree(exactFuncs);
4196:       if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
4197:       else                 {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
4198:     }
4199:     if (snes->reason > 0) {
4200:       if (((PetscObject) snes)->prefix) {
4201:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4202:       } else {
4203:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4204:       }
4205:     } else {
4206:       if (((PetscObject) snes)->prefix) {
4207:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
4208:       } else {
4209:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
4210:       }
4211:     }
4212:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4213:   }
4214:   return(0);
4215: }

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

4220:   Collective on SNES

4222:   Input Parameters:
4223: . snes   - the SNES object

4225:   Level: intermediate

4227: @*/
4228: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
4229: {
4230:   PetscErrorCode    ierr;
4231:   PetscViewer       viewer;
4232:   PetscBool         flg;
4233:   static PetscBool  incall = PETSC_FALSE;
4234:   PetscViewerFormat format;

4237:   if (incall) return(0);
4238:   incall = PETSC_TRUE;
4239:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4240:   if (flg) {
4241:     PetscViewerPushFormat(viewer,format);
4242:     SNESReasonView(snes,viewer);
4243:     PetscViewerPopFormat(viewer);
4244:     PetscViewerDestroy(&viewer);
4245:   }
4246:   incall = PETSC_FALSE;
4247:   return(0);
4248: }

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

4254:    Collective on SNES

4256:    Input Parameters:
4257: +  snes - the SNES context
4258: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4259: -  x - the solution vector.

4261:    Notes:
4262:    The user should initialize the vector,x, with the initial guess
4263:    for the nonlinear solve prior to calling SNESSolve.  In particular,
4264:    to employ an initial guess of zero, the user should explicitly set
4265:    this vector to zero by calling VecSet().

4267:    Level: beginner

4269: .keywords: SNES, nonlinear, solve

4271: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4272: @*/
4273: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4274: {
4275:   PetscErrorCode    ierr;
4276:   PetscBool         flg;
4277:   PetscInt          grid;
4278:   Vec               xcreated = NULL;
4279:   DM                dm;


4288:   /* High level operations using the nonlinear solver */
4289:   {
4290:     PetscViewer       viewer;
4291:     PetscViewerFormat format;
4292:     PetscInt          num;
4293:     PetscBool         flg;
4294:     static PetscBool  incall = PETSC_FALSE;

4296:     if (!incall) {
4297:       /* Estimate the convergence rate of the discretization */
4298:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes), ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4299:       if (flg) {
4300:         PetscConvEst conv;
4301:         DM           dm;
4302:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4303:         PetscInt     Nf;

4305:         incall = PETSC_TRUE;
4306:         SNESGetDM(snes, &dm);
4307:         DMGetNumFields(dm, &Nf);
4308:         PetscMalloc1(Nf, &alpha);
4309:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4310:         PetscConvEstSetSolver(conv, snes);
4311:         PetscConvEstSetFromOptions(conv);
4312:         PetscConvEstSetUp(conv);
4313:         PetscConvEstGetConvRate(conv, alpha);
4314:         PetscViewerPushFormat(viewer, format);
4315:         PetscConvEstRateView(conv, alpha, viewer);
4316:         PetscViewerPopFormat(viewer);
4317:         PetscViewerDestroy(&viewer);
4318:         PetscConvEstDestroy(&conv);
4319:         PetscFree(alpha);
4320:         incall = PETSC_FALSE;
4321:       }
4322:       /* Adaptively refine the initial grid */
4323:       num  = 1;
4324:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &num, &flg);
4325:       if (flg) {
4326:         DMAdaptor adaptor;

4328:         incall = PETSC_TRUE;
4329:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4330:         DMAdaptorSetSolver(adaptor, snes);
4331:         DMAdaptorSetSequenceLength(adaptor, num);
4332:         DMAdaptorSetFromOptions(adaptor);
4333:         DMAdaptorSetUp(adaptor);
4334:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4335:         DMAdaptorDestroy(&adaptor);
4336:         incall = PETSC_FALSE;
4337:       }
4338:       /* Use grid sequencing to adapt */
4339:       num  = 0;
4340:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4341:       if (num) {
4342:         DMAdaptor adaptor;

4344:         incall = PETSC_TRUE;
4345:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4346:         DMAdaptorSetSolver(adaptor, snes);
4347:         DMAdaptorSetSequenceLength(adaptor, num);
4348:         DMAdaptorSetFromOptions(adaptor);
4349:         DMAdaptorSetUp(adaptor);
4350:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4351:         DMAdaptorDestroy(&adaptor);
4352:         incall = PETSC_FALSE;
4353:       }
4354:     }
4355:   }
4356:   if (!x) {
4357:     SNESGetDM(snes,&dm);
4358:     DMCreateGlobalVector(dm,&xcreated);
4359:     x    = xcreated;
4360:   }
4361:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4366:     /* set solution vector */
4367:     if (!grid) {PetscObjectReference((PetscObject)x);}
4368:     VecDestroy(&snes->vec_sol);
4369:     snes->vec_sol = x;
4370:     SNESGetDM(snes,&dm);

4372:     /* set affine vector if provided */
4373:     if (b) { PetscObjectReference((PetscObject)b); }
4374:     VecDestroy(&snes->vec_rhs);
4375:     snes->vec_rhs = b;

4377:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4378:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4379:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4380:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4381:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4382:     }
4383:     DMShellSetGlobalVector(dm,snes->vec_sol);
4384:     SNESSetUp(snes);

4386:     if (!grid) {
4387:       if (snes->ops->computeinitialguess) {
4388:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4389:       }
4390:     }

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

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

4401:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4402:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4408:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4409:     if (snes->reason < 0) break;
4410:     if (grid <  snes->gridsequence) {
4411:       DM  fine;
4412:       Vec xnew;
4413:       Mat interp;

4415:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4416:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4417:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4418:       DMCreateGlobalVector(fine,&xnew);
4419:       MatInterpolate(interp,x,xnew);
4420:       DMInterpolate(snes->dm,interp,fine);
4421:       MatDestroy(&interp);
4422:       x    = xnew;

4424:       SNESReset(snes);
4425:       SNESSetDM(snes,fine);
4426:       SNESResetFromOptions(snes);
4427:       DMDestroy(&fine);
4428:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4429:     }
4430:   }
4431:   SNESViewFromOptions(snes,NULL,"-snes_view");
4432:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4434:   VecDestroy(&xcreated);
4435:   PetscObjectSAWsBlock((PetscObject)snes);
4436:   return(0);
4437: }

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

4441: /*@C
4442:    SNESSetType - Sets the method for the nonlinear solver.

4444:    Collective on SNES

4446:    Input Parameters:
4447: +  snes - the SNES context
4448: -  type - a known method

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

4454:    Notes:
4455:    See "petsc/include/petscsnes.h" for available methods (for instance)
4456: +    SNESNEWTONLS - Newton's method with line search
4457:      (systems of nonlinear equations)
4458: .    SNESNEWTONTR - Newton's method with trust region
4459:      (systems of nonlinear equations)

4461:   Normally, it is best to use the SNESSetFromOptions() command and then
4462:   set the SNES solver type from the options database rather than by using
4463:   this routine.  Using the options database provides the user with
4464:   maximum flexibility in evaluating the many nonlinear solvers.
4465:   The SNESSetType() routine is provided for those situations where it
4466:   is necessary to set the nonlinear solver independently of the command
4467:   line or options database.  This might be the case, for example, when
4468:   the choice of solver changes during the execution of the program,
4469:   and the user's application is taking responsibility for choosing the
4470:   appropriate method.

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

4476:   Level: intermediate

4478: .keywords: SNES, set, type

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

4482: @*/
4483: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4484: {
4485:   PetscErrorCode ierr,(*r)(SNES);
4486:   PetscBool      match;


4492:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4493:   if (match) return(0);

4495:    PetscFunctionListFind(SNESList,type,&r);
4496:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4497:   /* Destroy the previous private SNES context */
4498:   if (snes->ops->destroy) {
4499:     (*(snes)->ops->destroy)(snes);
4500:     snes->ops->destroy = NULL;
4501:   }
4502:   /* Reinitialize function pointers in SNESOps structure */
4503:   snes->ops->setup          = 0;
4504:   snes->ops->solve          = 0;
4505:   snes->ops->view           = 0;
4506:   snes->ops->setfromoptions = 0;
4507:   snes->ops->destroy        = 0;
4508:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4509:   snes->setupcalled = PETSC_FALSE;

4511:   PetscObjectChangeTypeName((PetscObject)snes,type);
4512:   (*r)(snes);
4513:   return(0);
4514: }

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

4519:    Not Collective

4521:    Input Parameter:
4522: .  snes - nonlinear solver context

4524:    Output Parameter:
4525: .  type - SNES method (a character string)

4527:    Level: intermediate

4529: .keywords: SNES, nonlinear, get, type, name
4530: @*/
4531: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4532: {
4536:   *type = ((PetscObject)snes)->type_name;
4537:   return(0);
4538: }

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

4543:   Logically Collective on SNES and Vec

4545:   Input Parameters:
4546: + snes - the SNES context obtained from SNESCreate()
4547: - u    - the solution vector

4549:   Level: beginner

4551: .keywords: SNES, set, solution
4552: @*/
4553: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4554: {
4555:   DM             dm;

4561:   PetscObjectReference((PetscObject) u);
4562:   VecDestroy(&snes->vec_sol);

4564:   snes->vec_sol = u;

4566:   SNESGetDM(snes, &dm);
4567:   DMShellSetGlobalVector(dm, u);
4568:   return(0);
4569: }

4571: /*@
4572:    SNESGetSolution - Returns the vector where the approximate solution is
4573:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4577:    Input Parameter:
4578: .  snes - the SNES context

4580:    Output Parameter:
4581: .  x - the solution

4583:    Level: intermediate

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

4587: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4588: @*/
4589: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4590: {
4594:   *x = snes->vec_sol;
4595:   return(0);
4596: }

4598: /*@
4599:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4600:    stored.

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

4604:    Input Parameter:
4605: .  snes - the SNES context

4607:    Output Parameter:
4608: .  x - the solution update

4610:    Level: advanced

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

4614: .seealso: SNESGetSolution(), SNESGetFunction()
4615: @*/
4616: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4617: {
4621:   *x = snes->vec_sol_update;
4622:   return(0);
4623: }

4625: /*@C
4626:    SNESGetFunction - Returns the vector where the function is stored.

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

4630:    Input Parameter:
4631: .  snes - the SNES context

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

4638:    Level: advanced

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

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

4644: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4645: @*/
4646: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4647: {
4649:   DM             dm;

4653:   if (r) {
4654:     if (!snes->vec_func) {
4655:       if (snes->vec_rhs) {
4656:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4657:       } else if (snes->vec_sol) {
4658:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4659:       } else if (snes->dm) {
4660:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4661:       }
4662:     }
4663:     *r = snes->vec_func;
4664:   }
4665:   SNESGetDM(snes,&dm);
4666:   DMSNESGetFunction(dm,f,ctx);
4667:   return(0);
4668: }

4670: /*@C
4671:    SNESGetNGS - Returns the NGS function and context.

4673:    Input Parameter:
4674: .  snes - the SNES context

4676:    Output Parameter:
4677: +  f - the function (or NULL) see SNESNGSFunction for details
4678: -  ctx    - the function context (or NULL)

4680:    Level: advanced

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

4684: .seealso: SNESSetNGS(), SNESGetFunction()
4685: @*/

4687: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4688: {
4690:   DM             dm;

4694:   SNESGetDM(snes,&dm);
4695:   DMSNESGetNGS(dm,f,ctx);
4696:   return(0);
4697: }

4699: /*@C
4700:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4701:    SNES options in the database.

4703:    Logically Collective on SNES

4705:    Input Parameter:
4706: +  snes - the SNES context
4707: -  prefix - the prefix to prepend to all option names

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

4713:    Level: advanced

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

4717: .seealso: SNESSetFromOptions()
4718: @*/
4719: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4720: {

4725:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4726:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4727:   if (snes->linesearch) {
4728:     SNESGetLineSearch(snes,&snes->linesearch);
4729:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4730:   }
4731:   KSPSetOptionsPrefix(snes->ksp,prefix);
4732:   return(0);
4733: }

4735: /*@C
4736:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4737:    SNES options in the database.

4739:    Logically Collective on SNES

4741:    Input Parameters:
4742: +  snes - the SNES context
4743: -  prefix - the prefix to prepend to all option names

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

4749:    Level: advanced

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

4753: .seealso: SNESGetOptionsPrefix()
4754: @*/
4755: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4756: {

4761:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4762:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4763:   if (snes->linesearch) {
4764:     SNESGetLineSearch(snes,&snes->linesearch);
4765:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4766:   }
4767:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4768:   return(0);
4769: }

4771: /*@C
4772:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4773:    SNES options in the database.

4775:    Not Collective

4777:    Input Parameter:
4778: .  snes - the SNES context

4780:    Output Parameter:
4781: .  prefix - pointer to the prefix string used

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

4787:    Level: advanced

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

4791: .seealso: SNESAppendOptionsPrefix()
4792: @*/
4793: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4794: {

4799:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4800:   return(0);
4801: }


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

4807:    Not collective

4809:    Input Parameters:
4810: +  name_solver - name of a new user-defined solver
4811: -  routine_create - routine to create method context

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

4816:    Sample usage:
4817: .vb
4818:    SNESRegister("my_solver",MySolverCreate);
4819: .ve

4821:    Then, your solver can be chosen with the procedural interface via
4822: $     SNESSetType(snes,"my_solver")
4823:    or at runtime via the option
4824: $     -snes_type my_solver

4826:    Level: advanced

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

4830: .keywords: SNES, nonlinear, register

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

4834:   Level: advanced
4835: @*/
4836: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4837: {

4841:   SNESInitializePackage();
4842:   PetscFunctionListAdd(&SNESList,sname,function);
4843:   return(0);
4844: }

4846: PetscErrorCode  SNESTestLocalMin(SNES snes)
4847: {
4849:   PetscInt       N,i,j;
4850:   Vec            u,uh,fh;
4851:   PetscScalar    value;
4852:   PetscReal      norm;

4855:   SNESGetSolution(snes,&u);
4856:   VecDuplicate(u,&uh);
4857:   VecDuplicate(u,&fh);

4859:   /* currently only works for sequential */
4860:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4861:   VecGetSize(u,&N);
4862:   for (i=0; i<N; i++) {
4863:     VecCopy(u,uh);
4864:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4865:     for (j=-10; j<11; j++) {
4866:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4867:       VecSetValue(uh,i,value,ADD_VALUES);
4868:       SNESComputeFunction(snes,uh,fh);
4869:       VecNorm(fh,NORM_2,&norm);
4870:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4871:       value = -value;
4872:       VecSetValue(uh,i,value,ADD_VALUES);
4873:     }
4874:   }
4875:   VecDestroy(&uh);
4876:   VecDestroy(&fh);
4877:   return(0);
4878: }

4880: /*@
4881:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4882:    computing relative tolerance for linear solvers within an inexact
4883:    Newton method.

4885:    Logically Collective on SNES

4887:    Input Parameters:
4888: +  snes - SNES context
4889: -  flag - PETSC_TRUE or PETSC_FALSE

4891:     Options Database:
4892: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4893: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4894: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4895: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4896: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4897: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4898: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4899: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4901:    Notes:
4902:    Currently, the default is to use a constant relative tolerance for
4903:    the inner linear solvers.  Alternatively, one can use the
4904:    Eisenstat-Walker method, where the relative convergence tolerance
4905:    is reset at each Newton iteration according progress of the nonlinear
4906:    solver.

4908:    Level: advanced

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

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

4916: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4917: @*/
4918: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4919: {
4923:   snes->ksp_ewconv = flag;
4924:   return(0);
4925: }

4927: /*@
4928:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4929:    for computing relative tolerance for linear solvers within an
4930:    inexact Newton method.

4932:    Not Collective

4934:    Input Parameter:
4935: .  snes - SNES context

4937:    Output Parameter:
4938: .  flag - PETSC_TRUE or PETSC_FALSE

4940:    Notes:
4941:    Currently, the default is to use a constant relative tolerance for
4942:    the inner linear solvers.  Alternatively, one can use the
4943:    Eisenstat-Walker method, where the relative convergence tolerance
4944:    is reset at each Newton iteration according progress of the nonlinear
4945:    solver.

4947:    Level: advanced

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

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

4955: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4956: @*/
4957: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4958: {
4962:   *flag = snes->ksp_ewconv;
4963:   return(0);
4964: }

4966: /*@
4967:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4968:    convergence criteria for the linear solvers within an inexact
4969:    Newton method.

4971:    Logically Collective on SNES

4973:    Input Parameters:
4974: +    snes - SNES context
4975: .    version - version 1, 2 (default is 2) or 3
4976: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4977: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4978: .    gamma - multiplicative factor for version 2 rtol computation
4979:              (0 <= gamma2 <= 1)
4980: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4981: .    alpha2 - power for safeguard
4982: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4984:    Note:
4985:    Version 3 was contributed by Luis Chacon, June 2006.

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

4989:    Level: advanced

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

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

4998: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4999: @*/
5000: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
5001: {
5002:   SNESKSPEW *kctx;

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

5016:   if (version != PETSC_DEFAULT)   kctx->version   = version;
5017:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
5018:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
5019:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
5020:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
5021:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
5022:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

5024:   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);
5025:   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);
5026:   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);
5027:   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);
5028:   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);
5029:   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);
5030:   return(0);
5031: }

5033: /*@
5034:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
5035:    convergence criteria for the linear solvers within an inexact
5036:    Newton method.

5038:    Not Collective

5040:    Input Parameters:
5041:      snes - SNES context

5043:    Output Parameters:
5044: +    version - version 1, 2 (default is 2) or 3
5045: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
5046: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
5047: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
5048: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
5049: .    alpha2 - power for safeguard
5050: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

5052:    Level: advanced

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

5056: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
5057: @*/
5058: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
5059: {
5060:   SNESKSPEW *kctx;

5064:   kctx = (SNESKSPEW*)snes->kspconvctx;
5065:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
5066:   if (version)   *version   = kctx->version;
5067:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
5068:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
5069:   if (gamma)     *gamma     = kctx->gamma;
5070:   if (alpha)     *alpha     = kctx->alpha;
5071:   if (alpha2)    *alpha2    = kctx->alpha2;
5072:   if (threshold) *threshold = kctx->threshold;
5073:   return(0);
5074: }

5076:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5077: {
5079:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5080:   PetscReal      rtol  = PETSC_DEFAULT,stol;

5083:   if (!snes->ksp_ewconv) return(0);
5084:   if (!snes->iter) {
5085:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
5086:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
5087:   }
5088:   else {
5089:     if (kctx->version == 1) {
5090:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
5091:       if (rtol < 0.0) rtol = -rtol;
5092:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
5093:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5094:     } else if (kctx->version == 2) {
5095:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5096:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
5097:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
5098:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
5099:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
5100:       /* safeguard: avoid sharp decrease of rtol */
5101:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
5102:       stol = PetscMax(rtol,stol);
5103:       rtol = PetscMin(kctx->rtol_0,stol);
5104:       /* safeguard: avoid oversolving */
5105:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
5106:       stol = PetscMax(rtol,stol);
5107:       rtol = PetscMin(kctx->rtol_0,stol);
5108:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
5109:   }
5110:   /* safeguard: avoid rtol greater than one */
5111:   rtol = PetscMin(rtol,kctx->rtol_max);
5112:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
5113:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
5114:   return(0);
5115: }

5117: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
5118: {
5120:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
5121:   PCSide         pcside;
5122:   Vec            lres;

5125:   if (!snes->ksp_ewconv) return(0);
5126:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
5127:   kctx->norm_last = snes->norm;
5128:   if (kctx->version == 1) {
5129:     PC        pc;
5130:     PetscBool isNone;

5132:     KSPGetPC(ksp, &pc);
5133:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
5134:     KSPGetPCSide(ksp,&pcside);
5135:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
5136:       /* KSP residual is true linear residual */
5137:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
5138:     } else {
5139:       /* KSP residual is preconditioned residual */
5140:       /* compute true linear residual norm */
5141:       VecDuplicate(b,&lres);
5142:       MatMult(snes->jacobian,x,lres);
5143:       VecAYPX(lres,-1.0,b);
5144:       VecNorm(lres,NORM_2,&kctx->lresid_last);
5145:       VecDestroy(&lres);
5146:     }
5147:   }
5148:   return(0);
5149: }

5151: /*@
5152:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

5156:    Input Parameter:
5157: .  snes - the SNES context

5159:    Output Parameter:
5160: .  ksp - the KSP context

5162:    Notes:
5163:    The user can then directly manipulate the KSP context to set various
5164:    options, etc.  Likewise, the user can then extract and manipulate the
5165:    PC contexts as well.

5167:    Level: beginner

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

5171: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
5172: @*/
5173: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
5174: {


5181:   if (!snes->ksp) {
5182:     PetscBool monitor = PETSC_FALSE;

5184:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
5185:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
5186:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

5191:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
5192:     if (monitor) {
5193:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
5194:     }
5195:     monitor = PETSC_FALSE;
5196:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
5197:     if (monitor) {
5198:       PetscObject *objs;
5199:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
5200:       objs[0] = (PetscObject) snes;
5201:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
5202:     }
5203:   }
5204:   *ksp = snes->ksp;
5205:   return(0);
5206: }


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

5213:    Logically Collective on SNES

5215:    Input Parameters:
5216: +  snes - the nonlinear solver context
5217: -  dm - the dm, cannot be NULL

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

5224:    Level: intermediate

5226: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
5227: @*/
5228: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5229: {
5231:   KSP            ksp;
5232:   DMSNES         sdm;

5237:   PetscObjectReference((PetscObject)dm);
5238:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5239:     if (snes->dm->dmsnes && !dm->dmsnes) {
5240:       DMCopyDMSNES(snes->dm,dm);
5241:       DMGetDMSNES(snes->dm,&sdm);
5242:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5243:     }
5244:     DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5245:     DMDestroy(&snes->dm);
5246:   }
5247:   snes->dm     = dm;
5248:   snes->dmAuto = PETSC_FALSE;

5250:   SNESGetKSP(snes,&ksp);
5251:   KSPSetDM(ksp,dm);
5252:   KSPSetDMActive(ksp,PETSC_FALSE);
5253:   if (snes->npc) {
5254:     SNESSetDM(snes->npc, snes->dm);
5255:     SNESSetNPCSide(snes,snes->npcside);
5256:   }
5257:   return(0);
5258: }

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

5263:    Not Collective but DM obtained is parallel on SNES

5265:    Input Parameter:
5266: . snes - the preconditioner context

5268:    Output Parameter:
5269: .  dm - the dm

5271:    Level: intermediate

5273: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5274: @*/
5275: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5276: {

5281:   if (!snes->dm) {
5282:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5283:     snes->dmAuto = PETSC_TRUE;
5284:   }
5285:   *dm = snes->dm;
5286:   return(0);
5287: }

5289: /*@
5290:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5292:   Collective on SNES

5294:   Input Parameters:
5295: + snes - iterative context obtained from SNESCreate()
5296: - pc   - the preconditioner object

5298:   Notes:
5299:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5300:   to configure it using the API).

5302:   Level: developer

5304: .keywords: SNES, set, precondition
5305: .seealso: SNESGetNPC(), SNESHasNPC()
5306: @*/
5307: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5308: {

5315:   PetscObjectReference((PetscObject) pc);
5316:   SNESDestroy(&snes->npc);
5317:   snes->npc = pc;
5318:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5319:   return(0);
5320: }

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

5325:   Not Collective

5327:   Input Parameter:
5328: . snes - iterative context obtained from SNESCreate()

5330:   Output Parameter:
5331: . pc - preconditioner context

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

5336:   Level: developer

5338: .keywords: SNES, get, preconditioner
5339: .seealso: SNESSetNPC(), SNESHasNPC()
5340: @*/
5341: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5342: {
5344:   const char     *optionsprefix;

5349:   if (!snes->npc) {
5350:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5351:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5352:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5353:     SNESGetOptionsPrefix(snes,&optionsprefix);
5354:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5355:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5356:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5357:   }
5358:   *pc = snes->npc;
5359:   return(0);
5360: }

5362: /*@
5363:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5365:   Not Collective

5367:   Input Parameter:
5368: . snes - iterative context obtained from SNESCreate()

5370:   Output Parameter:
5371: . has_npc - whether the SNES has an NPC or not

5373:   Level: developer

5375: .keywords: SNES, has, preconditioner
5376: .seealso: SNESSetNPC(), SNESGetNPC()
5377: @*/
5378: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5379: {
5382:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5383:   return(0);
5384: }

5386: /*@
5387:     SNESSetNPCSide - Sets the preconditioning side.

5389:     Logically Collective on SNES

5391:     Input Parameter:
5392: .   snes - iterative context obtained from SNESCreate()

5394:     Output Parameter:
5395: .   side - the preconditioning side, where side is one of
5396: .vb
5397:       PC_LEFT - left preconditioning
5398:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5399: .ve

5401:     Options Database Keys:
5402: .   -snes_pc_side <right,left>

5404:     Notes:
5405:     SNESNRICHARDSON and SNESNCG only support left preconditioning.

5407:     Level: intermediate

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

5411: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5412: @*/
5413: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5414: {
5418:   snes->npcside= side;
5419:   return(0);
5420: }

5422: /*@
5423:     SNESGetNPCSide - Gets the preconditioning side.

5425:     Not Collective

5427:     Input Parameter:
5428: .   snes - iterative context obtained from SNESCreate()

5430:     Output Parameter:
5431: .   side - the preconditioning side, where side is one of
5432: .vb
5433:       PC_LEFT - left preconditioning
5434:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5435: .ve

5437:     Level: intermediate

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

5441: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5442: @*/
5443: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5444: {
5448:   *side = snes->npcside;
5449:   return(0);
5450: }

5452: /*@
5453:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5455:   Collective on SNES

5457:   Input Parameters:
5458: + snes - iterative context obtained from SNESCreate()
5459: - linesearch   - the linesearch object

5461:   Notes:
5462:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5463:   to configure it using the API).

5465:   Level: developer

5467: .keywords: SNES, set, linesearch
5468: .seealso: SNESGetLineSearch()
5469: @*/
5470: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5471: {

5478:   PetscObjectReference((PetscObject) linesearch);
5479:   SNESLineSearchDestroy(&snes->linesearch);

5481:   snes->linesearch = linesearch;

5483:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5484:   return(0);
5485: }

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

5491:   Not Collective

5493:   Input Parameter:
5494: . snes - iterative context obtained from SNESCreate()

5496:   Output Parameter:
5497: . linesearch - linesearch context

5499:   Level: beginner

5501: .keywords: SNES, get, linesearch
5502: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5503: @*/
5504: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5505: {
5507:   const char     *optionsprefix;

5512:   if (!snes->linesearch) {
5513:     SNESGetOptionsPrefix(snes, &optionsprefix);
5514:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5515:     SNESLineSearchSetSNES(snes->linesearch, snes);
5516:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5517:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5518:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5519:   }
5520:   *linesearch = snes->linesearch;
5521:   return(0);
5522: }

5524: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5525: #include <mex.h>

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

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

5532:    Collective on SNES

5534:    Input Parameters:
5535: +  snes - the SNES context
5536: -  x - input vector

5538:    Output Parameter:
5539: .  y - function vector, as set by SNESSetFunction()

5541:    Notes:
5542:    SNESComputeFunction() is typically used within nonlinear solvers
5543:    implementations, so most users would not generally call this routine
5544:    themselves.

5546:    Level: developer

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

5550: .seealso: SNESSetFunction(), SNESGetFunction()
5551: */
5552: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5553: {
5554:   PetscErrorCode    ierr;
5555:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5556:   int               nlhs  = 1,nrhs = 5;
5557:   mxArray           *plhs[1],*prhs[5];
5558:   long long int     lx = 0,ly = 0,ls = 0;


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

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

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

5592:    Logically Collective on SNES

5594:    Input Parameters:
5595: +  snes - the SNES context
5596: .  r - vector to store function value
5597: -  f - function evaluation routine

5599:    Notes:
5600:    The Newton-like methods typically solve linear systems of the form
5601: $      f'(x) x = -f(x),
5602:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5604:    Level: beginner

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

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

5610: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5611: */
5612: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5613: {
5614:   PetscErrorCode    ierr;
5615:   SNESMatlabContext *sctx;

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

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

5634:    Collective on SNES

5636:    Input Parameters:
5637: +  snes - the SNES context
5638: .  x - input vector
5639: .  A, B - the matrices
5640: -  ctx - user context

5642:    Level: developer

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

5646: .seealso: SNESSetFunction(), SNESGetFunction()
5647: @*/
5648: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5649: {
5650:   PetscErrorCode    ierr;
5651:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5652:   int               nlhs  = 2,nrhs = 6;
5653:   mxArray           *plhs[2],*prhs[6];
5654:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


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

5662:   PetscMemcpy(&ls,&snes,sizeof(snes));
5663:   PetscMemcpy(&lx,&x,sizeof(x));
5664:   PetscMemcpy(&lA,A,sizeof(x));
5665:   PetscMemcpy(&lB,B,sizeof(x));
5666:   prhs[0] = mxCreateDoubleScalar((double)ls);
5667:   prhs[1] = mxCreateDoubleScalar((double)lx);
5668:   prhs[2] = mxCreateDoubleScalar((double)lA);
5669:   prhs[3] = mxCreateDoubleScalar((double)lB);
5670:   prhs[4] = mxCreateString(sctx->funcname);
5671:   prhs[5] = sctx->ctx;
5672:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5673:   mxGetScalar(plhs[0]);
5674:   mxDestroyArray(prhs[0]);
5675:   mxDestroyArray(prhs[1]);
5676:   mxDestroyArray(prhs[2]);
5677:   mxDestroyArray(prhs[3]);
5678:   mxDestroyArray(prhs[4]);
5679:   mxDestroyArray(plhs[0]);
5680:   mxDestroyArray(plhs[1]);
5681:   return(0);
5682: }

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

5689:    Logically Collective on SNES

5691:    Input Parameters:
5692: +  snes - the SNES context
5693: .  A,B - Jacobian matrices
5694: .  J - function evaluation routine
5695: -  ctx - user context

5697:    Level: developer

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

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

5703: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5704: */
5705: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5706: {
5707:   PetscErrorCode    ierr;
5708:   SNESMatlabContext *sctx;

5711:   /* currently sctx is memory bleed */
5712:   PetscNew(&sctx);
5713:   PetscStrallocpy(J,&sctx->funcname);
5714:   /*
5715:      This should work, but it doesn't
5716:   sctx->ctx = ctx;
5717:   mexMakeArrayPersistent(sctx->ctx);
5718:   */
5719:   sctx->ctx = mxDuplicateArray(ctx);
5720:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5721:   return(0);
5722: }

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

5727:    Collective on SNES

5729: .seealso: SNESSetFunction(), SNESGetFunction()
5730: @*/
5731: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5732: {
5733:   PetscErrorCode    ierr;
5734:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5735:   int               nlhs  = 1,nrhs = 6;
5736:   mxArray           *plhs[1],*prhs[6];
5737:   long long int     lx = 0,ls = 0;
5738:   Vec               x  = snes->vec_sol;


5743:   PetscMemcpy(&ls,&snes,sizeof(snes));
5744:   PetscMemcpy(&lx,&x,sizeof(x));
5745:   prhs[0] = mxCreateDoubleScalar((double)ls);
5746:   prhs[1] = mxCreateDoubleScalar((double)it);
5747:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5748:   prhs[3] = mxCreateDoubleScalar((double)lx);
5749:   prhs[4] = mxCreateString(sctx->funcname);
5750:   prhs[5] = sctx->ctx;
5751:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5752:   mxGetScalar(plhs[0]);
5753:   mxDestroyArray(prhs[0]);
5754:   mxDestroyArray(prhs[1]);
5755:   mxDestroyArray(prhs[2]);
5756:   mxDestroyArray(prhs[3]);
5757:   mxDestroyArray(prhs[4]);
5758:   mxDestroyArray(plhs[0]);
5759:   return(0);
5760: }

5762: /*
5763:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5765:    Level: developer

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

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

5771: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5772: */
5773: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5774: {
5775:   PetscErrorCode    ierr;
5776:   SNESMatlabContext *sctx;

5779:   /* currently sctx is memory bleed */
5780:   PetscNew(&sctx);
5781:   PetscStrallocpy(f,&sctx->funcname);
5782:   /*
5783:      This should work, but it doesn't
5784:   sctx->ctx = ctx;
5785:   mexMakeArrayPersistent(sctx->ctx);
5786:   */
5787:   sctx->ctx = mxDuplicateArray(ctx);
5788:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5789:   return(0);
5790: }

5792: #endif