Actual source code: snes.c

petsc-master 2017-01-19
Report Typos and Errors

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

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

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

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

 17:    Logically Collective on SNES

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

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

 26:    Level: intermediate

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

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

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

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

 48:    Not Collective

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

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

 56:    Level: intermediate

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

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

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

 74:    Logically Collective on SNES

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

 80:    Level: advanced

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

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

 95:    Logically Collective on SNES

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

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

103:    Level: advanced

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

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

119:    Logically Collective on SNES

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

124:    Level: advanced

126: .keywords: SNES, view

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

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

142:    Logically Collective on SNES

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

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

150:    Level: advanced

152: .keywords: SNES, view

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

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

168:   Collective on PetscViewer

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

175:    Level: intermediate

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

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

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

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

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

222:  #include <petscdraw.h>
223: #if defined(PETSC_HAVE_SAWS)
224:  #include <petscviewersaws.h>
225: #endif
226: /*@C
227:    SNESView - Prints the SNES data structure.

229:    Collective on SNES

231:    Input Parameters:
232: +  SNES - the SNES context
233: -  viewer - visualization context

235:    Options Database Key:
236: .  -snes_view - Calls SNESView() at end of SNESSolve()

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

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

249:    Level: beginner

251: .keywords: SNES, view

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

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

275:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
276:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
277:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
278:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
279: #if defined(PETSC_HAVE_SAWS)
280:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
281: #endif
282:   if (iascii) {
283:     SNESNormSchedule normschedule;

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

331:     PetscObjectGetComm((PetscObject)snes,&comm);
332:     MPI_Comm_rank(comm,&rank);
333:     if (!rank) {
334:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
335:       PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));
336:       PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR,PETSC_FALSE);
337:     }
338:     if (snes->ops->view) {
339:       (*snes->ops->view)(snes,viewer);
340:     }
341:   } else if (isdraw) {
342:     PetscDraw draw;
343:     char      str[36];
344:     PetscReal x,y,bottom,h;

346:     PetscViewerDrawGetDraw(viewer,0,&draw);
347:     PetscDrawGetCurrentPoint(draw,&x,&y);
348:     PetscStrcpy(str,"SNES: ");
349:     PetscStrcat(str,((PetscObject)snes)->type_name);
350:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h);
351:     bottom = y - h;
352:     PetscDrawPushCurrentPoint(draw,x,bottom);
353:     if (snes->ops->view) {
354:       (*snes->ops->view)(snes,viewer);
355:     }
356: #if defined(PETSC_HAVE_SAWS)
357:   } else if (issaws) {
358:     PetscMPIInt rank;
359:     const char *name;

361:     PetscObjectGetName((PetscObject)snes,&name);
362:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
363:     if (!((PetscObject)snes)->amsmem && !rank) {
364:       char       dir[1024];

366:       PetscObjectViewSAWs((PetscObject)snes,viewer);
367:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);
368:       PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
369:       if (!snes->conv_hist) {
370:         SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE);
371:       }
372:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name);
373:       PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
374:     }
375: #endif
376:   }
377:   if (snes->linesearch) {
378:     PetscViewerASCIIPushTab(viewer);
379:     SNESGetLineSearch(snes, &linesearch);
380:     SNESLineSearchView(linesearch, viewer);
381:     PetscViewerASCIIPopTab(viewer);
382:   }
383:   if (snes->pc && snes->usespc) {
384:     PetscViewerASCIIPushTab(viewer);
385:     SNESView(snes->pc, viewer);
386:     PetscViewerASCIIPopTab(viewer);
387:   }
388:   PetscViewerASCIIPushTab(viewer);
389:   DMGetDMSNES(snes->dm,&dmsnes);
390:   DMSNESView(dmsnes, viewer);
391:   PetscViewerASCIIPopTab(viewer);
392:   if (snes->usesksp) {
393:     SNESGetKSP(snes,&ksp);
394:     PetscViewerASCIIPushTab(viewer);
395:     KSPView(ksp,viewer);
396:     PetscViewerASCIIPopTab(viewer);
397:   }
398:   if (isdraw) {
399:     PetscDraw draw;
400:     PetscViewerDrawGetDraw(viewer,0,&draw);
401:     PetscDrawPopCurrentPoint(draw);
402:   }
403:   return(0);
404: }

406: /*
407:   We retain a list of functions that also take SNES command
408:   line options. These are called at the end SNESSetFromOptions()
409: */
410: #define MAXSETFROMOPTIONS 5
411: static PetscInt numberofsetfromoptions;
412: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);

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

417:   Not Collective

419:   Input Parameter:
420: . snescheck - function that checks for options

422:   Level: developer

424: .seealso: SNESSetFromOptions()
425: @*/
426: PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
427: {
429:   if (numberofsetfromoptions >= MAXSETFROMOPTIONS) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %D allowed", MAXSETFROMOPTIONS);
430:   othersetfromoptions[numberofsetfromoptions++] = snescheck;
431:   return(0);
432: }

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

436: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
437: {
438:   Mat            J;
439:   KSP            ksp;
440:   PC             pc;
441:   PetscBool      match;
443:   MatNullSpace   nullsp;


448:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
449:     Mat A = snes->jacobian, B = snes->jacobian_pre;
450:     MatCreateVecs(A ? A : B, NULL,&snes->vec_func);
451:   }

453:   if (version == 1) {
454:     MatCreateSNESMF(snes,&J);
455:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
456:     MatSetFromOptions(J);
457:   } else if (version == 2) {
458:     if (!snes->vec_func) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
459: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128) && !defined(PETSC_USE_REAL___FP16)
460:     SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J);
461: #else
462:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator rutines (version 2)");
463: #endif
464:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator rutines, only version 1 and 2");

466:   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
467:   if (snes->jacobian) {
468:     MatGetNullSpace(snes->jacobian,&nullsp);
469:     if (nullsp) {
470:       MatSetNullSpace(J,nullsp);
471:     }
472:   }

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

477:     /* This version replaces the user provided Jacobian matrix with a
478:        matrix-free version but still employs the user-provided preconditioner matrix. */
479:     SNESSetJacobian(snes,J,0,0,0);
480:   } else {
481:     /* This version replaces both the user-provided Jacobian and the user-
482:      provided preconditioner Jacobian with the default matrix free version. */
483:     if ((snes->pcside == PC_LEFT) && snes->pc) {
484:       if (!snes->jacobian){SNESSetJacobian(snes,J,0,0,0);}
485:     } else {
486:       SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,0);
487:     }
488:     /* Force no preconditioner */
489:     SNESGetKSP(snes,&ksp);
490:     KSPGetPC(ksp,&pc);
491:     PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&match);
492:     if (!match) {
493:       PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n");
494:       PCSetType(pc,PCNONE);
495:     }
496:   }
497:   MatDestroy(&J);
498:   return(0);
499: }

501: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
502: {
503:   SNES           snes = (SNES)ctx;
505:   Vec            Xfine,Xfine_named = NULL,Xcoarse;

508:   if (PetscLogPrintInfo) {
509:     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
510:     DMGetRefineLevel(dmfine,&finelevel);
511:     DMGetCoarsenLevel(dmfine,&fineclevel);
512:     DMGetRefineLevel(dmcoarse,&coarselevel);
513:     DMGetCoarsenLevel(dmcoarse,&coarseclevel);
514:     PetscInfo4(dmfine,"Restricting SNES solution vector from level %D-%D to level %D-%D\n",finelevel,fineclevel,coarselevel,coarseclevel);
515:   }
516:   if (dmfine == snes->dm) Xfine = snes->vec_sol;
517:   else {
518:     DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);
519:     Xfine = Xfine_named;
520:   }
521:   DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
522:   if (Inject) {
523:     MatRestrict(Inject,Xfine,Xcoarse);
524:   } else {
525:     MatRestrict(Restrict,Xfine,Xcoarse);
526:     VecPointwiseMult(Xcoarse,Xcoarse,Rscale);
527:   }
528:   DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
529:   if (Xfine_named) {DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);}
530:   return(0);
531: }

533: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
534: {

538:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
539:   return(0);
540: }

542: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
543:  * safely call SNESGetDM() in their residual evaluation routine. */
544: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
545: {
546:   SNES           snes = (SNES)ctx;
548:   Mat            Asave = A,Bsave = B;
549:   Vec            X,Xnamed = NULL;
550:   DM             dmsave;
551:   void           *ctxsave;
552:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);

555:   dmsave = snes->dm;
556:   KSPGetDM(ksp,&snes->dm);
557:   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
558:   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
559:     DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
560:     X    = Xnamed;
561:     SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave);
562:     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
563:     if (jac == SNESComputeJacobianDefaultColor) {
564:       SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,0);
565:     }
566:   }
567:   /* put the previous context back */

569:   SNESComputeJacobian(snes,X,A,B);
570:   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
571:     SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);
572:   }

574:   if (A != Asave || B != Bsave) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_SUP,"No support for changing matrices at this time");
575:   if (Xnamed) {
576:     DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
577:   }
578:   snes->dm = dmsave;
579:   return(0);
580: }

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

585:    Collective

587:    Input Arguments:
588: .  snes - snes to configure

590:    Level: developer

592: .seealso: SNESSetUp()
593: @*/
594: PetscErrorCode SNESSetUpMatrices(SNES snes)
595: {
597:   DM             dm;
598:   DMSNES         sdm;

601:   SNESGetDM(snes,&dm);
602:   DMGetDMSNES(dm,&sdm);
603:   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_PLIB,"DMSNES not properly configured");
604:   else if (!snes->jacobian && snes->mf) {
605:     Mat  J;
606:     void *functx;
607:     MatCreateSNESMF(snes,&J);
608:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
609:     MatSetFromOptions(J);
610:     SNESGetFunction(snes,NULL,NULL,&functx);
611:     SNESSetJacobian(snes,J,J,0,0);
612:     MatDestroy(&J);
613:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
614:     Mat J,B;
615:     MatCreateSNESMF(snes,&J);
616:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
617:     MatSetFromOptions(J);
618:     DMCreateMatrix(snes->dm,&B);
619:     /* sdm->computejacobian was already set to reach here */
620:     SNESSetJacobian(snes,J,B,NULL,NULL);
621:     MatDestroy(&J);
622:     MatDestroy(&B);
623:   } else if (!snes->jacobian_pre) {
624:     PetscDS   prob;
625:     Mat       J, B;
626:     PetscBool hasPrec = PETSC_FALSE;

628:     J    = snes->jacobian;
629:     DMGetDS(dm, &prob);
630:     if (prob) {PetscDSHasJacobianPreconditioner(prob, &hasPrec);}
631:     if (J)            {PetscObjectReference((PetscObject) J);}
632:     else if (hasPrec) {DMCreateMatrix(snes->dm, &J);}
633:     DMCreateMatrix(snes->dm, &B);
634:     SNESSetJacobian(snes, J ? J : B, B, NULL, NULL);
635:     MatDestroy(&J);
636:     MatDestroy(&B);
637:   }
638:   {
639:     KSP ksp;
640:     SNESGetKSP(snes,&ksp);
641:     KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);
642:     DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
643:   }
644:   return(0);
645: }

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

650:    Collective on SNES

652:    Input Parameters:
653: +  snes - SNES object you wish to monitor
654: .  name - the monitor type one is seeking
655: .  help - message indicating what monitoring is done
656: .  manual - manual page for the monitor
657: .  monitor - the monitor function
658: -  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

660:    Level: developer

662: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
663:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
664:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
665:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
666:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
667:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
668:           PetscOptionsFList(), PetscOptionsEList()
669: @*/
670: PetscErrorCode  SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
671: {
672:   PetscErrorCode    ierr;
673:   PetscViewer       viewer;
674:   PetscViewerFormat format;
675:   PetscBool         flg;

678:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,name,&viewer,&format,&flg);
679:   if (flg) {
680:     PetscViewerAndFormat *vf;
681:     PetscViewerAndFormatCreate(viewer,format,&vf);
682:     PetscObjectDereference((PetscObject)viewer);
683:     if (monitorsetup) {
684:       (*monitorsetup)(snes,vf);
685:     }
686:     SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
687:   }
688:   return(0);
689: }

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

694:    Collective on SNES

696:    Input Parameter:
697: .  snes - the SNES context

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

728:     Options Database for Eisenstat-Walker method:
729: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
730: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
731: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
732: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
733: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
734: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
735: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
736: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

738:    Notes:
739:    To see all options, run your program with the -help option or consult
740:    Users-Manual: ch_snes

742:    Level: beginner

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

746: .seealso: SNESSetOptionsPrefix()
747: @*/
748: PetscErrorCode  SNESSetFromOptions(SNES snes)
749: {
750:   PetscBool      flg,pcset,persist,set;
751:   PetscInt       i,indx,lag,grids;
752:   const char     *deft        = SNESNEWTONLS;
753:   const char     *convtests[] = {"default","skip"};
754:   SNESKSPEW      *kctx        = NULL;
755:   char           type[256], monfilename[PETSC_MAX_PATH_LEN];
757:   PCSide         pcside;
758:   const char     *optionsprefix;

762:   SNESRegisterAll();
763:   PetscObjectOptionsBegin((PetscObject)snes);
764:   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
765:   PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg);
766:   if (flg) {
767:     SNESSetType(snes,type);
768:   } else if (!((PetscObject)snes)->type_name) {
769:     SNESSetType(snes,deft);
770:   }
771:   PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL);
772:   PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL);

774:   PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL);
775:   PetscOptionsReal("-snes_divergence_tolerance","Stop if residual norm increases by this factor","SNESSetDivergenceTolerance",snes->divtol,&snes->divtol,NULL);
776:   PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL);
777:   PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL);
778:   PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL);
779:   PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL);
780:   PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL);

782:   PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg);
783:   if (flg) {
784:     SNESSetLagPreconditioner(snes,lag);
785:   }
786:   PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg);
787:   if (flg) {
788:     SNESSetLagPreconditionerPersists(snes,persist);
789:   }
790:   PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg);
791:   if (flg) {
792:     SNESSetLagJacobian(snes,lag);
793:   }
794:   PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg);
795:   if (flg) {
796:     SNESSetLagJacobianPersists(snes,persist);
797:   }

799:   PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg);
800:   if (flg) {
801:     SNESSetGridSequence(snes,grids);
802:   }

804:   PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,2,"default",&indx,&flg);
805:   if (flg) {
806:     switch (indx) {
807:     case 0: SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL); break;
808:     case 1: SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL);    break;
809:     }
810:   }

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

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

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

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

822:   PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL);
823:   PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL);
824:   PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL);
825:   PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL);
826:   PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL);
827:   PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL);
828:   PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL);

830:   flg  = PETSC_FALSE;
831:   PetscOptionsBool("-snes_check_jacobian","Check each Jacobian with a differenced one","SNESUpdateCheckJacobian",flg,&flg,&set);
832:   if (set && flg) {
833:     SNESSetUpdate(snes,SNESUpdateCheckJacobian);
834:   }

836:   flg  = PETSC_FALSE;
837:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
838:   if (set && flg) {SNESMonitorCancel(snes);}

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

844:   SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp);
845:   SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL);
846:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL);
847:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL);
848:   SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL);
849:   SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL);
850:   SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL);

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


856:   flg  = PETSC_FALSE;
857:   PetscOptionsBool("-snes_monitor_lg_residualnorm","Plot function norm at each iteration","SNESMonitorLGResidualNorm",flg,&flg,NULL);
858:   if (flg) {
859:     PetscDrawLG ctx;

861:     SNESMonitorLGCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
862:     SNESMonitorSet(snes,SNESMonitorLGResidualNorm,ctx,(PetscErrorCode (*)(void**))PetscDrawLGDestroy);
863:   }
864:   flg  = PETSC_FALSE;
865:   PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);
866:   if (flg) {
867:     PetscViewer ctx;

869:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
870:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
871:   }



875:   flg  = PETSC_FALSE;
876:   PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);
877:   if (flg) {
878:     void *functx;
879:     SNESGetFunction(snes,NULL,NULL,&functx);
880:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);
881:     PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");
882:   }

884:   flg  = PETSC_FALSE;
885:   PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);
886:   if (flg) {
887:     SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);
888:   }

890:   flg  = PETSC_FALSE;
891:   PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL);
892:   if (flg) {
893:     DM             dm;
894:     DMSNES         sdm;
895:     SNESGetDM(snes,&dm);
896:     DMGetDMSNES(dm,&sdm);
897:     sdm->jacobianctx = NULL;
898:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,0);
899:     PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n");
900:   }

902:   flg  = PETSC_FALSE;
903:   PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","MatCreateSNESMF",PETSC_FALSE,&snes->mf_operator,&flg);
904:   if (flg && snes->mf_operator) {
905:     snes->mf_operator = PETSC_TRUE;
906:     snes->mf          = PETSC_TRUE;
907:   }
908:   flg  = PETSC_FALSE;
909:   PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","MatCreateSNESMF",PETSC_FALSE,&snes->mf,&flg);
910:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
911:   PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,0);

913:   flg  = PETSC_FALSE;
914:   SNESGetNPCSide(snes,&pcside);
915:   PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);
916:   if (flg) {SNESSetNPCSide(snes,pcside);}

918: #if defined(PETSC_HAVE_SAWS)
919:   /*
920:     Publish convergence information using SAWs
921:   */
922:   flg  = PETSC_FALSE;
923:   PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL);
924:   if (flg) {
925:     void *ctx;
926:     SNESMonitorSAWsCreate(snes,&ctx);
927:     SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy);
928:   }
929: #endif
930: #if defined(PETSC_HAVE_SAWS)
931:   {
932:   PetscBool set;
933:   flg  = PETSC_FALSE;
934:   PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set);
935:   if (set) {
936:     PetscObjectSAWsSetBlock((PetscObject)snes,flg);
937:   }
938:   }
939: #endif

941:   for (i = 0; i < numberofsetfromoptions; i++) {
942:     (*othersetfromoptions[i])(snes);
943:   }

945:   if (snes->ops->setfromoptions) {
946:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
947:   }

949:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
950:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
951:   PetscOptionsEnd();

953:   if (!snes->linesearch) {
954:     SNESGetLineSearch(snes, &snes->linesearch);
955:   }
956:   SNESLineSearchSetFromOptions(snes->linesearch);

958:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
959:   KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
960:   KSPSetFromOptions(snes->ksp);

962:   /* if someone has set the SNES NPC type, create it. */
963:   SNESGetOptionsPrefix(snes, &optionsprefix);
964:   PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset);
965:   if (pcset && (!snes->pc)) {
966:     SNESGetNPC(snes, &snes->pc);
967:   }
968:   return(0);
969: }

971: /*@C
972:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
973:    the nonlinear solvers.

975:    Logically Collective on SNES

977:    Input Parameters:
978: +  snes - the SNES context
979: .  compute - function to compute the context
980: -  destroy - function to destroy the context

982:    Level: intermediate

984:    Notes:
985:    This function is currently not available from Fortran.

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

989: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
990: @*/
991: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
992: {
995:   snes->ops->usercompute = compute;
996:   snes->ops->userdestroy = destroy;
997:   return(0);
998: }

1000: /*@
1001:    SNESSetApplicationContext - Sets the optional user-defined context for
1002:    the nonlinear solvers.

1004:    Logically Collective on SNES

1006:    Input Parameters:
1007: +  snes - the SNES context
1008: -  usrP - optional user context

1010:    Level: intermediate

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

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

1017: .seealso: SNESGetApplicationContext()
1018: @*/
1019: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1020: {
1022:   KSP            ksp;

1026:   SNESGetKSP(snes,&ksp);
1027:   KSPSetApplicationContext(ksp,usrP);
1028:   snes->user = usrP;
1029:   return(0);
1030: }

1032: /*@
1033:    SNESGetApplicationContext - Gets the user-defined context for the
1034:    nonlinear solvers.

1036:    Not Collective

1038:    Input Parameter:
1039: .  snes - SNES context

1041:    Output Parameter:
1042: .  usrP - user context

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

1047:    Level: intermediate

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

1051: .seealso: SNESSetApplicationContext()
1052: @*/
1053: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1054: {
1057:   *(void**)usrP = snes->user;
1058:   return(0);
1059: }

1061: /*@
1062:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1063:    at this time.

1065:    Not Collective

1067:    Input Parameter:
1068: .  snes - SNES context

1070:    Output Parameter:
1071: .  iter - iteration number

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

1076:    This is useful for using lagged Jacobians (where one does not recompute the
1077:    Jacobian at each SNES iteration). For example, the code
1078: .vb
1079:       SNESGetIterationNumber(snes,&it);
1080:       if (!(it % 2)) {
1081:         [compute Jacobian here]
1082:       }
1083: .ve
1084:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1085:    recomputed every second SNES iteration.

1087:    Level: intermediate

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

1091: .seealso:   SNESGetLinearSolveIterations()
1092: @*/
1093: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1094: {
1098:   *iter = snes->iter;
1099:   return(0);
1100: }

1102: /*@
1103:    SNESSetIterationNumber - Sets the current iteration number.

1105:    Not Collective

1107:    Input Parameter:
1108: .  snes - SNES context
1109: .  iter - iteration number

1111:    Level: developer

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

1115: .seealso:   SNESGetLinearSolveIterations()
1116: @*/
1117: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1118: {

1123:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1124:   snes->iter = iter;
1125:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1126:   return(0);
1127: }

1129: /*@
1130:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1131:    attempted by the nonlinear solver.

1133:    Not Collective

1135:    Input Parameter:
1136: .  snes - SNES context

1138:    Output Parameter:
1139: .  nfails - number of unsuccessful steps attempted

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

1144:    Level: intermediate

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

1148: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1149:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1150: @*/
1151: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1152: {
1156:   *nfails = snes->numFailures;
1157:   return(0);
1158: }

1160: /*@
1161:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1162:    attempted by the nonlinear solver before it gives up.

1164:    Not Collective

1166:    Input Parameters:
1167: +  snes     - SNES context
1168: -  maxFails - maximum of unsuccessful steps

1170:    Level: intermediate

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

1174: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1175:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1176: @*/
1177: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1178: {
1181:   snes->maxFailures = maxFails;
1182:   return(0);
1183: }

1185: /*@
1186:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1187:    attempted by the nonlinear solver before it gives up.

1189:    Not Collective

1191:    Input Parameter:
1192: .  snes     - SNES context

1194:    Output Parameter:
1195: .  maxFails - maximum of unsuccessful steps

1197:    Level: intermediate

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

1201: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1202:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1204: @*/
1205: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1206: {
1210:   *maxFails = snes->maxFailures;
1211:   return(0);
1212: }

1214: /*@
1215:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1216:      done by SNES.

1218:    Not Collective

1220:    Input Parameter:
1221: .  snes     - SNES context

1223:    Output Parameter:
1224: .  nfuncs - number of evaluations

1226:    Level: intermediate

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

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

1232: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1233: @*/
1234: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1235: {
1239:   *nfuncs = snes->nfuncs;
1240:   return(0);
1241: }

1243: /*@
1244:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1245:    linear solvers.

1247:    Not Collective

1249:    Input Parameter:
1250: .  snes - SNES context

1252:    Output Parameter:
1253: .  nfails - number of failed solves

1255:    Level: intermediate

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

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

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

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

1276: /*@
1277:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1278:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1280:    Logically Collective on SNES

1282:    Input Parameters:
1283: +  snes     - SNES context
1284: -  maxFails - maximum allowed linear solve failures

1286:    Level: intermediate

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

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

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

1295: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1296: @*/
1297: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1298: {
1302:   snes->maxLinearSolveFailures = maxFails;
1303:   return(0);
1304: }

1306: /*@
1307:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1308:      are allowed before SNES terminates

1310:    Not Collective

1312:    Input Parameter:
1313: .  snes     - SNES context

1315:    Output Parameter:
1316: .  maxFails - maximum of unsuccessful solves allowed

1318:    Level: intermediate

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

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

1324: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1325: @*/
1326: PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1327: {
1331:   *maxFails = snes->maxLinearSolveFailures;
1332:   return(0);
1333: }

1335: /*@
1336:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1337:    used by the nonlinear solver.

1339:    Not Collective

1341:    Input Parameter:
1342: .  snes - SNES context

1344:    Output Parameter:
1345: .  lits - number of linear iterations

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

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

1353:    Level: intermediate

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

1357: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1358: @*/
1359: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1360: {
1364:   *lits = snes->linear_its;
1365:   return(0);
1366: }

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

1372:    Logically Collective on SNES

1374:    Input Parameter:
1375: +  snes - SNES context
1376: -  reset - whether to reset the counters or not

1378:    Notes:
1379:    This defaults to PETSC_TRUE

1381:    Level: developer

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

1385: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1386: @*/
1387: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1388: {
1392:   snes->counters_reset = reset;
1393:   return(0);
1394: }


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

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

1402:    Input Parameters:
1403: +  snes - the SNES context
1404: -  ksp - the KSP context

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

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

1413:    Level: developer

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

1417: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1418: @*/
1419: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1420: {

1427:   PetscObjectReference((PetscObject)ksp);
1428:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1429:   snes->ksp = ksp;
1430:   return(0);
1431: }

1433: /* -----------------------------------------------------------*/
1434: /*@
1435:    SNESCreate - Creates a nonlinear solver context.

1437:    Collective on MPI_Comm

1439:    Input Parameters:
1440: .  comm - MPI communicator

1442:    Output Parameter:
1443: .  outsnes - the new SNES context

1445:    Options Database Keys:
1446: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1447:                and no preconditioning matrix
1448: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1449:                products, and a user-provided preconditioning matrix
1450:                as set by SNESSetJacobian()
1451: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1453:    Level: beginner

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

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

1459: @*/
1460: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1461: {
1463:   SNES           snes;
1464:   SNESKSPEW      *kctx;

1468:   *outsnes = NULL;
1469:   SNESInitializePackage();

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

1473:   snes->ops->converged    = SNESConvergedDefault;
1474:   snes->usesksp           = PETSC_TRUE;
1475:   snes->tolerancesset     = PETSC_FALSE;
1476:   snes->max_its           = 50;
1477:   snes->max_funcs         = 10000;
1478:   snes->norm              = 0.0;
1479:   snes->normschedule      = SNES_NORM_ALWAYS;
1480:   snes->functype          = SNES_FUNCTION_DEFAULT;
1481: #if defined(PETSC_USE_REAL_SINGLE)
1482:   snes->rtol              = 1.e-5;
1483: #else
1484:   snes->rtol              = 1.e-8;
1485: #endif
1486:   snes->ttol              = 0.0;
1487: #if defined(PETSC_USE_REAL_SINGLE)
1488:   snes->abstol            = 1.e-25;
1489: #else
1490:   snes->abstol            = 1.e-50;
1491: #endif
1492: #if defined(PETSC_USE_REAL_SINGLE)
1493:   snes->stol              = 1.e-5;
1494: #else
1495:   snes->stol              = 1.e-8;
1496: #endif
1497: #if defined(PETSC_USE_REAL_SINGLE)
1498:   snes->deltatol          = 1.e-6;
1499: #else
1500:   snes->deltatol          = 1.e-12;
1501: #endif
1502:   snes->divtol            = 1.e4;
1503:   snes->rnorm0            = 0;
1504:   snes->nfuncs            = 0;
1505:   snes->numFailures       = 0;
1506:   snes->maxFailures       = 1;
1507:   snes->linear_its        = 0;
1508:   snes->lagjacobian       = 1;
1509:   snes->jac_iter          = 0;
1510:   snes->lagjac_persist    = PETSC_FALSE;
1511:   snes->lagpreconditioner = 1;
1512:   snes->pre_iter          = 0;
1513:   snes->lagpre_persist    = PETSC_FALSE;
1514:   snes->numbermonitors    = 0;
1515:   snes->data              = 0;
1516:   snes->setupcalled       = PETSC_FALSE;
1517:   snes->ksp_ewconv        = PETSC_FALSE;
1518:   snes->nwork             = 0;
1519:   snes->work              = 0;
1520:   snes->nvwork            = 0;
1521:   snes->vwork             = 0;
1522:   snes->conv_hist_len     = 0;
1523:   snes->conv_hist_max     = 0;
1524:   snes->conv_hist         = NULL;
1525:   snes->conv_hist_its     = NULL;
1526:   snes->conv_hist_reset   = PETSC_TRUE;
1527:   snes->counters_reset    = PETSC_TRUE;
1528:   snes->vec_func_init_set = PETSC_FALSE;
1529:   snes->reason            = SNES_CONVERGED_ITERATING;
1530:   snes->pcside            = PC_RIGHT;

1532:   snes->mf          = PETSC_FALSE;
1533:   snes->mf_operator = PETSC_FALSE;
1534:   snes->mf_version  = 1;

1536:   snes->numLinearSolveFailures = 0;
1537:   snes->maxLinearSolveFailures = 1;

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

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

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

1547:   snes->kspconvctx  = (void*)kctx;
1548:   kctx->version     = 2;
1549:   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1550:                              this was too large for some test cases */
1551:   kctx->rtol_last   = 0.0;
1552:   kctx->rtol_max    = .9;
1553:   kctx->gamma       = 1.0;
1554:   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
1555:   kctx->alpha2      = kctx->alpha;
1556:   kctx->threshold   = .1;
1557:   kctx->lresid_last = 0.0;
1558:   kctx->norm_last   = 0.0;

1560:   *outsnes = snes;
1561:   return(0);
1562: }

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

1567:      Synopsis:
1568:      #include "petscsnes.h"
1569:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1571:      Input Parameters:
1572: +     snes - the SNES context
1573: .     x    - state at which to evaluate residual
1574: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1576:      Output Parameter:
1577: .     f  - vector to put residual (function value)

1579:    Level: intermediate

1581: .seealso:   SNESSetFunction(), SNESGetFunction()
1582: M*/

1584: /*@C
1585:    SNESSetFunction - Sets the function evaluation routine and function
1586:    vector for use by the SNES routines in solving systems of nonlinear
1587:    equations.

1589:    Logically Collective on SNES

1591:    Input Parameters:
1592: +  snes - the SNES context
1593: .  r - vector to store function value
1594: .  f - function evaluation routine; see SNESFunction for calling sequence details
1595: -  ctx - [optional] user-defined context for private data for the
1596:          function evaluation routine (may be NULL)

1598:    Notes:
1599:    The Newton-like methods typically solve linear systems of the form
1600: $      f'(x) x = -f(x),
1601:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1603:    Level: beginner

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

1607: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1608: @*/
1609: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1610: {
1612:   DM             dm;

1616:   if (r) {
1619:     PetscObjectReference((PetscObject)r);
1620:     VecDestroy(&snes->vec_func);

1622:     snes->vec_func = r;
1623:   }
1624:   SNESGetDM(snes,&dm);
1625:   DMSNESSetFunction(dm,f,ctx);
1626:   return(0);
1627: }


1630: /*@C
1631:    SNESSetInitialFunction - Sets the function vector to be used as the
1632:    function norm at the initialization of the method.  In some
1633:    instances, the user has precomputed the function before calling
1634:    SNESSolve.  This function allows one to avoid a redundant call
1635:    to SNESComputeFunction in that case.

1637:    Logically Collective on SNES

1639:    Input Parameters:
1640: +  snes - the SNES context
1641: -  f - vector to store function value

1643:    Notes:
1644:    This should not be modified during the solution procedure.

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

1648:    Level: developer

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

1652: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1653: @*/
1654: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1655: {
1657:   Vec            vec_func;

1663:   if (snes->pcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1664:     snes->vec_func_init_set = PETSC_FALSE;
1665:     return(0);
1666:   }
1667:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1668:   VecCopy(f, vec_func);

1670:   snes->vec_func_init_set = PETSC_TRUE;
1671:   return(0);
1672: }

1674: /*@
1675:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1676:    of the SNES method.

1678:    Logically Collective on SNES

1680:    Input Parameters:
1681: +  snes - the SNES context
1682: -  normschedule - the frequency of norm computation

1684:    Options Database Key:
1685: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1696:    Level: developer

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

1700: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1701: @*/
1702: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1703: {
1706:   snes->normschedule = normschedule;
1707:   return(0);
1708: }


1711: /*@
1712:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1713:    of the SNES method.

1715:    Logically Collective on SNES

1717:    Input Parameters:
1718: +  snes - the SNES context
1719: -  normschedule - the type of the norm used

1721:    Level: advanced

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

1725: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1726: @*/
1727: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1728: {
1731:   *normschedule = snes->normschedule;
1732:   return(0);
1733: }


1736: /*@
1737:   SNESSetFunctionNorm - Sets the last computed residual norm.

1739:   Logically Collective on SNES

1741:   Input Parameters:
1742: + snes - the SNES context

1744: - normschedule - the frequency of norm computation

1746:   Level: developer

1748: .keywords: SNES, nonlinear, set, function, norm, type
1749: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1750: @*/
1751: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1752: {
1755:   snes->norm = norm;
1756:   return(0);
1757: }

1759: /*@
1760:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1762:   Not Collective

1764:   Input Parameter:
1765: . snes - the SNES context

1767:   Output Parameter:
1768: . norm - the last computed residual norm

1770:   Level: developer

1772: .keywords: SNES, nonlinear, set, function, norm, type
1773: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1774: @*/
1775: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1776: {
1780:   *norm = snes->norm;
1781:   return(0);
1782: }

1784: /*@C
1785:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1786:    of the SNES method.

1788:    Logically Collective on SNES

1790:    Input Parameters:
1791: +  snes - the SNES context
1792: -  normschedule - the frequency of norm computation

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

1803:    Level: developer

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

1807: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1808: @*/
1809: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1810: {
1813:   snes->functype = type;
1814:   return(0);
1815: }


1818: /*@C
1819:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1820:    of the SNES method.

1822:    Logically Collective on SNES

1824:    Input Parameters:
1825: +  snes - the SNES context
1826: -  normschedule - the type of the norm used

1828:    Level: advanced

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

1832: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1833: @*/
1834: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
1835: {
1838:   *type = snes->functype;
1839:   return(0);
1840: }

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

1845:      Synopsis:
1846:      #include <petscsnes.h>
1847: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1849: +  X   - solution vector
1850: .  B   - RHS vector
1851: -  ctx - optional user-defined Gauss-Seidel context

1853:    Level: intermediate

1855: .seealso:   SNESSetNGS(), SNESGetNGS()
1856: M*/

1858: /*@C
1859:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1860:    use with composed nonlinear solvers.

1862:    Input Parameters:
1863: +  snes   - the SNES context
1864: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
1865: -  ctx    - [optional] user-defined context for private data for the
1866:             smoother evaluation routine (may be NULL)

1868:    Notes:
1869:    The NGS routines are used by the composed nonlinear solver to generate
1870:     a problem appropriate update to the solution, particularly FAS.

1872:    Level: intermediate

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

1876: .seealso: SNESGetFunction(), SNESComputeNGS()
1877: @*/
1878: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1879: {
1881:   DM             dm;

1885:   SNESGetDM(snes,&dm);
1886:   DMSNESSetNGS(dm,f,ctx);
1887:   return(0);
1888: }

1890: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1891: {
1893:   DM             dm;
1894:   DMSNES         sdm;

1897:   SNESGetDM(snes,&dm);
1898:   DMGetDMSNES(dm,&sdm);
1899:   /*  A(x)*x - b(x) */
1900:   if (sdm->ops->computepfunction) {
1901:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
1902:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");

1904:   if (sdm->ops->computepjacobian) {
1905:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
1906:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard matrix.");
1907:   VecScale(f,-1.0);
1908:   MatMultAdd(snes->jacobian,x,f,f);
1909:   return(0);
1910: }

1912: PETSC_EXTERN PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
1913: {
1915:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
1916:   return(0);
1917: }

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

1922:    Logically Collective on SNES

1924:    Input Parameters:
1925: +  snes - the SNES context
1926: .  r - vector to store function value
1927: .  b - function evaluation routine
1928: .  Amat - matrix with which A(x) x - b(x) is to be computed
1929: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
1930: .  J  - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
1931: -  ctx - [optional] user-defined context for private data for the
1932:          function evaluation routine (may be NULL)

1934:    Notes:
1935:     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
1936:     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.

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

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

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

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

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

1952:    Level: intermediate

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

1956: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
1957: @*/
1958: 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)
1959: {
1961:   DM             dm;

1965:   SNESGetDM(snes, &dm);
1966:   DMSNESSetPicard(dm,b,J,ctx);
1967:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
1968:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
1969:   return(0);
1970: }

1972: /*@C
1973:    SNESGetPicard - Returns the context for the Picard iteration

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

1977:    Input Parameter:
1978: .  snes - the SNES context

1980:    Output Parameter:
1981: +  r - the function (or NULL)
1982: .  f - the function (or NULL); see SNESFunction for calling sequence details
1983: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
1984: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
1985: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
1986: -  ctx - the function context (or NULL)

1988:    Level: advanced

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

1992: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
1993: @*/
1994: 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)
1995: {
1997:   DM             dm;

2001:   SNESGetFunction(snes,r,NULL,NULL);
2002:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2003:   SNESGetDM(snes,&dm);
2004:   DMSNESGetPicard(dm,f,J,ctx);
2005:   return(0);
2006: }

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

2011:    Logically Collective on SNES

2013:    Input Parameters:
2014: +  snes - the SNES context
2015: .  func - function evaluation routine
2016: -  ctx - [optional] user-defined context for private data for the
2017:          function evaluation routine (may be NULL)

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

2022: .  f - function vector
2023: -  ctx - optional user-defined function context

2025:    Level: intermediate

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

2029: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2030: @*/
2031: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2032: {
2035:   if (func) snes->ops->computeinitialguess = func;
2036:   if (ctx)  snes->initialguessP            = ctx;
2037:   return(0);
2038: }

2040: /* --------------------------------------------------------------- */
2041: /*@C
2042:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2043:    it assumes a zero right hand side.

2045:    Logically Collective on SNES

2047:    Input Parameter:
2048: .  snes - the SNES context

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

2053:    Level: intermediate

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

2057: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2058: @*/
2059: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2060: {
2064:   *rhs = snes->vec_rhs;
2065:   return(0);
2066: }

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

2071:    Collective on SNES

2073:    Input Parameters:
2074: +  snes - the SNES context
2075: -  x - input vector

2077:    Output Parameter:
2078: .  y - function vector, as set by SNESSetFunction()

2080:    Notes:
2081:    SNESComputeFunction() is typically used within nonlinear solvers
2082:    implementations, so most users would not generally call this routine
2083:    themselves.

2085:    Level: developer

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

2089: .seealso: SNESSetFunction(), SNESGetFunction()
2090: @*/
2091: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2092: {
2094:   DM             dm;
2095:   DMSNES         sdm;

2103:   VecValidValues(x,2,PETSC_TRUE);

2105:   SNESGetDM(snes,&dm);
2106:   DMGetDMSNES(dm,&sdm);
2107:   if (sdm->ops->computefunction) {
2108:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2109:       PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2110:     }
2111:     VecLockPush(x);
2112:     PetscStackPush("SNES user function");
2113:     (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);
2114:     PetscStackPop;
2115:     VecLockPop(x);
2116:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2117:       PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2118:     }
2119:   } else if (snes->vec_rhs) {
2120:     MatMult(snes->jacobian, x, y);
2121:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2122:   if (snes->vec_rhs) {
2123:     VecAXPY(y,-1.0,snes->vec_rhs);
2124:   }
2125:   snes->nfuncs++;
2126:   /*
2127:      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2128:      propagate the value to all processes
2129:   */
2130:   if (snes->domainerror) {
2131:     VecSetInf(y);
2132:   }
2133:   return(0);
2134: }

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

2139:    Collective on SNES

2141:    Input Parameters:
2142: +  snes - the SNES context
2143: .  x - input vector
2144: -  b - rhs vector

2146:    Output Parameter:
2147: .  x - new solution vector

2149:    Notes:
2150:    SNESComputeNGS() is typically used within composed nonlinear solver
2151:    implementations, so most users would not generally call this routine
2152:    themselves.

2154:    Level: developer

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

2158: .seealso: SNESSetNGS(), SNESComputeFunction()
2159: @*/
2160: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2161: {
2163:   DM             dm;
2164:   DMSNES         sdm;

2172:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2173:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2174:   SNESGetDM(snes,&dm);
2175:   DMGetDMSNES(dm,&sdm);
2176:   if (sdm->ops->computegs) {
2177:     if (b) {VecLockPush(b);}
2178:     PetscStackPush("SNES user NGS");
2179:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2180:     PetscStackPop;
2181:     if (b) {VecLockPop(b);}
2182:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2183:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2184:   return(0);
2185: }

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

2190:    Collective on SNES and Mat

2192:    Input Parameters:
2193: +  snes - the SNES context
2194: -  x - input vector

2196:    Output Parameters:
2197: +  A - Jacobian matrix
2198: -  B - optional preconditioning matrix

2200:   Options Database Keys:
2201: +    -snes_lag_preconditioner <lag>
2202: .    -snes_lag_jacobian <lag>
2203: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2204: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2205: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2206: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2207: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2208: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2209: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2210: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2211: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2212: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2213: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2216:    Notes:
2217:    Most users should not need to explicitly call this routine, as it
2218:    is used internally within the nonlinear solvers.

2220:    Level: developer

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

2224: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2225: @*/
2226: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2227: {
2229:   PetscBool      flag;
2230:   DM             dm;
2231:   DMSNES         sdm;
2232:   KSP            ksp;

2238:   VecValidValues(X,2,PETSC_TRUE);
2239:   SNESGetDM(snes,&dm);
2240:   DMGetDMSNES(dm,&sdm);

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

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

2246:   if (snes->lagjacobian == -2) {
2247:     snes->lagjacobian = -1;

2249:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2250:   } else if (snes->lagjacobian == -1) {
2251:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2252:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2253:     if (flag) {
2254:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2255:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2256:     }
2257:     return(0);
2258:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2259:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2260:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2261:     if (flag) {
2262:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2263:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2264:     }
2265:     return(0);
2266:   }
2267:   if (snes->pc && snes->pcside == PC_LEFT) {
2268:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2269:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2270:       return(0);
2271:   }

2273:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2274:   VecLockPush(X);
2275:   PetscStackPush("SNES user Jacobian function");
2276:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2277:   PetscStackPop;
2278:   VecLockPop(X);
2279:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2281:   /* the next line ensures that snes->ksp exists */
2282:   SNESGetKSP(snes,&ksp);
2283:   if (snes->lagpreconditioner == -2) {
2284:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2285:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2286:     snes->lagpreconditioner = -1;
2287:   } else if (snes->lagpreconditioner == -1) {
2288:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2289:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2290:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2291:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2292:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2293:   } else {
2294:     PetscInfo(snes,"Rebuilding preconditioner\n");
2295:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2296:   }

2298:   /* make sure user returned a correct Jacobian and preconditioner */
2301:   {
2302:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2303:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2304:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2305:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2306:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2307:     if (flag || flag_draw || flag_contour) {
2308:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2309:       PetscViewer  vdraw,vstdout;
2310:       PetscBool    flg;
2311:       if (flag_operator) {
2312:         MatComputeExplicitOperator(A,&Bexp_mine);
2313:         Bexp = Bexp_mine;
2314:       } else {
2315:         /* See if the preconditioning matrix can be viewed and added directly */
2316:         PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2317:         if (flg) Bexp = B;
2318:         else {
2319:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2320:           MatComputeExplicitOperator(B,&Bexp_mine);
2321:           Bexp = Bexp_mine;
2322:         }
2323:       }
2324:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2325:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2326:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2327:       if (flag_draw || flag_contour) {
2328:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2329:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2330:       } else vdraw = NULL;
2331:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2332:       if (flag) {MatView(Bexp,vstdout);}
2333:       if (vdraw) {MatView(Bexp,vdraw);}
2334:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2335:       if (flag) {MatView(FDexp,vstdout);}
2336:       if (vdraw) {MatView(FDexp,vdraw);}
2337:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2338:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2339:       if (flag) {MatView(FDexp,vstdout);}
2340:       if (vdraw) {              /* Always use contour for the difference */
2341:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2342:         MatView(FDexp,vdraw);
2343:         PetscViewerPopFormat(vdraw);
2344:       }
2345:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2346:       PetscViewerDestroy(&vdraw);
2347:       MatDestroy(&Bexp_mine);
2348:       MatDestroy(&FDexp);
2349:     }
2350:   }
2351:   {
2352:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2353:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2354:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2355:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2356:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2357:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2358:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2359:     if (flag_threshold) {
2360:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2361:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2362:     }
2363:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2364:       Mat            Bfd;
2365:       PetscViewer    vdraw,vstdout;
2366:       MatColoring    coloring;
2367:       ISColoring     iscoloring;
2368:       MatFDColoring  matfdcoloring;
2369:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2370:       void           *funcctx;
2371:       PetscReal      norm1,norm2,normmax;

2373:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2374:       MatColoringCreate(Bfd,&coloring);
2375:       MatColoringSetType(coloring,MATCOLORINGSL);
2376:       MatColoringSetFromOptions(coloring);
2377:       MatColoringApply(coloring,&iscoloring);
2378:       MatColoringDestroy(&coloring);
2379:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2380:       MatFDColoringSetFromOptions(matfdcoloring);
2381:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2382:       ISColoringDestroy(&iscoloring);

2384:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2385:       SNESGetFunction(snes,NULL,&func,&funcctx);
2386:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2387:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2388:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2389:       MatFDColoringSetFromOptions(matfdcoloring);
2390:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2391:       MatFDColoringDestroy(&matfdcoloring);

2393:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2394:       if (flag_draw || flag_contour) {
2395:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2396:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2397:       } else vdraw = NULL;
2398:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2399:       if (flag_display) {MatView(B,vstdout);}
2400:       if (vdraw) {MatView(B,vdraw);}
2401:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2402:       if (flag_display) {MatView(Bfd,vstdout);}
2403:       if (vdraw) {MatView(Bfd,vdraw);}
2404:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2405:       MatNorm(Bfd,NORM_1,&norm1);
2406:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2407:       MatNorm(Bfd,NORM_MAX,&normmax);
2408:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2409:       if (flag_display) {MatView(Bfd,vstdout);}
2410:       if (vdraw) {              /* Always use contour for the difference */
2411:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2412:         MatView(Bfd,vdraw);
2413:         PetscViewerPopFormat(vdraw);
2414:       }
2415:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2417:       if (flag_threshold) {
2418:         PetscInt bs,rstart,rend,i;
2419:         MatGetBlockSize(B,&bs);
2420:         MatGetOwnershipRange(B,&rstart,&rend);
2421:         for (i=rstart; i<rend; i++) {
2422:           const PetscScalar *ba,*ca;
2423:           const PetscInt    *bj,*cj;
2424:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2425:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2426:           MatGetRow(B,i,&bn,&bj,&ba);
2427:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2428:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2429:           for (j=0; j<bn; j++) {
2430:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2431:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2432:               maxentrycol = bj[j];
2433:               maxentry    = PetscRealPart(ba[j]);
2434:             }
2435:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2436:               maxdiffcol = bj[j];
2437:               maxdiff    = PetscRealPart(ca[j]);
2438:             }
2439:             if (rdiff > maxrdiff) {
2440:               maxrdiffcol = bj[j];
2441:               maxrdiff    = rdiff;
2442:             }
2443:           }
2444:           if (maxrdiff > 1) {
2445:             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);
2446:             for (j=0; j<bn; j++) {
2447:               PetscReal rdiff;
2448:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2449:               if (rdiff > 1) {
2450:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2451:               }
2452:             }
2453:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2454:           }
2455:           MatRestoreRow(B,i,&bn,&bj,&ba);
2456:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2457:         }
2458:       }
2459:       PetscViewerDestroy(&vdraw);
2460:       MatDestroy(&Bfd);
2461:     }
2462:   }
2463:   return(0);
2464: }

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

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

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

2478:    Level: intermediate

2480: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2481: M*/

2483: /*@C
2484:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2485:    location to store the matrix.

2487:    Logically Collective on SNES and Mat

2489:    Input Parameters:
2490: +  snes - the SNES context
2491: .  Amat - the matrix that defines the (approximate) Jacobian
2492: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2493: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2494: -  ctx - [optional] user-defined context for private data for the
2495:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2497:    Notes:
2498:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2499:    each matrix.

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

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

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

2510:    Level: beginner

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

2514: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J, 
2515:           SNESSetPicard(), SNESJacobianFunction
2516: @*/
2517: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2518: {
2520:   DM             dm;

2528:   SNESGetDM(snes,&dm);
2529:   DMSNESSetJacobian(dm,J,ctx);
2530:   if (Amat) {
2531:     PetscObjectReference((PetscObject)Amat);
2532:     MatDestroy(&snes->jacobian);

2534:     snes->jacobian = Amat;
2535:   }
2536:   if (Pmat) {
2537:     PetscObjectReference((PetscObject)Pmat);
2538:     MatDestroy(&snes->jacobian_pre);

2540:     snes->jacobian_pre = Pmat;
2541:   }
2542:   return(0);
2543: }

2545: /*@C
2546:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2547:    provided context for evaluating the Jacobian.

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

2551:    Input Parameter:
2552: .  snes - the nonlinear solver context

2554:    Output Parameters:
2555: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2556: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2557: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2558: -  ctx - location to stash Jacobian ctx (or NULL)

2560:    Level: advanced

2562: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2563: @*/
2564: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2565: {
2567:   DM             dm;
2568:   DMSNES         sdm;

2572:   if (Amat) *Amat = snes->jacobian;
2573:   if (Pmat) *Pmat = snes->jacobian_pre;
2574:   SNESGetDM(snes,&dm);
2575:   DMGetDMSNES(dm,&sdm);
2576:   if (J) *J = sdm->ops->computejacobian;
2577:   if (ctx) *ctx = sdm->jacobianctx;
2578:   return(0);
2579: }

2581: /*@
2582:    SNESSetUp - Sets up the internal data structures for the later use
2583:    of a nonlinear solver.

2585:    Collective on SNES

2587:    Input Parameters:
2588: .  snes - the SNES context

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

2597:    Level: advanced

2599: .keywords: SNES, nonlinear, setup

2601: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2602: @*/
2603: PetscErrorCode  SNESSetUp(SNES snes)
2604: {
2606:   DM             dm;
2607:   DMSNES         sdm;
2608:   SNESLineSearch linesearch, pclinesearch;
2609:   void           *lsprectx,*lspostctx;
2610:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2611:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2612:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2613:   Vec            f,fpc;
2614:   void           *funcctx;
2615:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2616:   void           *jacctx,*appctx;
2617:   Mat            j,jpre;

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

2623:   if (!((PetscObject)snes)->type_name) {
2624:     SNESSetType(snes,SNESNEWTONLS);
2625:   }

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

2629:   SNESGetDM(snes,&dm);
2630:   DMGetDMSNES(dm,&sdm);
2631:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2632:   if (!sdm->ops->computejacobian) {
2633:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2634:   }
2635:   if (!snes->vec_func) {
2636:     DMCreateGlobalVector(dm,&snes->vec_func);
2637:   }

2639:   if (!snes->ksp) {
2640:     SNESGetKSP(snes, &snes->ksp);
2641:   }

2643:   if (!snes->linesearch) {
2644:     SNESGetLineSearch(snes, &snes->linesearch);
2645:   }
2646:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2648:   if (snes->pc && (snes->pcside == PC_LEFT)) {
2649:     snes->mf          = PETSC_TRUE;
2650:     snes->mf_operator = PETSC_FALSE;
2651:   }

2653:   if (snes->pc) {
2654:     /* copy the DM over */
2655:     SNESGetDM(snes,&dm);
2656:     SNESSetDM(snes->pc,dm);

2658:     SNESGetFunction(snes,&f,&func,&funcctx);
2659:     VecDuplicate(f,&fpc);
2660:     SNESSetFunction(snes->pc,fpc,func,funcctx);
2661:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2662:     SNESSetJacobian(snes->pc,j,jpre,jac,jacctx);
2663:     SNESGetApplicationContext(snes,&appctx);
2664:     SNESSetApplicationContext(snes->pc,appctx);
2665:     VecDestroy(&fpc);

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

2670:     /* default to 1 iteration */
2671:     SNESSetTolerances(snes->pc,0.0,0.0,0.0,1,snes->pc->max_funcs);
2672:     if (snes->pcside==PC_RIGHT) {
2673:       SNESSetNormSchedule(snes->pc,SNES_NORM_FINAL_ONLY);
2674:     } else {
2675:       SNESSetNormSchedule(snes->pc,SNES_NORM_NONE);
2676:     }
2677:     SNESSetFromOptions(snes->pc);

2679:     /* copy the line search context over */
2680:     SNESGetLineSearch(snes,&linesearch);
2681:     SNESGetLineSearch(snes->pc,&pclinesearch);
2682:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2683:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2684:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2685:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2686:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2687:   }
2688:   if (snes->mf) {
2689:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2690:   }
2691:   if (snes->ops->usercompute && !snes->user) {
2692:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2693:   }

2695:   snes->jac_iter = 0;
2696:   snes->pre_iter = 0;

2698:   if (snes->ops->setup) {
2699:     (*snes->ops->setup)(snes);
2700:   }

2702:   if (snes->pc && (snes->pcside == PC_LEFT)) {
2703:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2704:       SNESGetLineSearch(snes,&linesearch);
2705:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2706:     }
2707:   }

2709:   snes->setupcalled = PETSC_TRUE;
2710:   return(0);
2711: }

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

2716:    Collective on SNES

2718:    Input Parameter:
2719: .  snes - iterative context obtained from SNESCreate()

2721:    Level: intermediate

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

2725: .keywords: SNES, destroy

2727: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
2728: @*/
2729: PetscErrorCode  SNESReset(SNES snes)
2730: {

2735:   if (snes->ops->userdestroy && snes->user) {
2736:     (*snes->ops->userdestroy)((void**)&snes->user);
2737:     snes->user = NULL;
2738:   }
2739:   if (snes->pc) {
2740:     SNESReset(snes->pc);
2741:   }

2743:   if (snes->ops->reset) {
2744:     (*snes->ops->reset)(snes);
2745:   }
2746:   if (snes->ksp) {
2747:     KSPReset(snes->ksp);
2748:   }

2750:   if (snes->linesearch) {
2751:     SNESLineSearchReset(snes->linesearch);
2752:   }

2754:   VecDestroy(&snes->vec_rhs);
2755:   VecDestroy(&snes->vec_sol);
2756:   VecDestroy(&snes->vec_sol_update);
2757:   VecDestroy(&snes->vec_func);
2758:   MatDestroy(&snes->jacobian);
2759:   MatDestroy(&snes->jacobian_pre);
2760:   VecDestroyVecs(snes->nwork,&snes->work);
2761:   VecDestroyVecs(snes->nvwork,&snes->vwork);

2763:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

2765:   snes->nwork       = snes->nvwork = 0;
2766:   snes->setupcalled = PETSC_FALSE;
2767:   return(0);
2768: }

2770: /*@
2771:    SNESDestroy - Destroys the nonlinear solver context that was created
2772:    with SNESCreate().

2774:    Collective on SNES

2776:    Input Parameter:
2777: .  snes - the SNES context

2779:    Level: beginner

2781: .keywords: SNES, nonlinear, destroy

2783: .seealso: SNESCreate(), SNESSolve()
2784: @*/
2785: PetscErrorCode  SNESDestroy(SNES *snes)
2786: {

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

2794:   SNESReset((*snes));
2795:   SNESDestroy(&(*snes)->pc);

2797:   /* if memory was published with SAWs then destroy it */
2798:   PetscObjectSAWsViewOff((PetscObject)*snes);
2799:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

2801:   DMDestroy(&(*snes)->dm);
2802:   KSPDestroy(&(*snes)->ksp);
2803:   SNESLineSearchDestroy(&(*snes)->linesearch);

2805:   PetscFree((*snes)->kspconvctx);
2806:   if ((*snes)->ops->convergeddestroy) {
2807:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
2808:   }
2809:   if ((*snes)->conv_malloc) {
2810:     PetscFree((*snes)->conv_hist);
2811:     PetscFree((*snes)->conv_hist_its);
2812:   }
2813:   SNESMonitorCancel((*snes));
2814:   PetscHeaderDestroy(snes);
2815:   return(0);
2816: }

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

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

2823:    Logically Collective on SNES

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

2830:    Options Database Keys:
2831: .    -snes_lag_preconditioner <lag>

2833:    Notes:
2834:    The default is 1
2835:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
2836:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

2838:    Level: intermediate

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

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

2844: @*/
2845: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
2846: {
2849:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
2850:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
2852:   snes->lagpreconditioner = lag;
2853:   return(0);
2854: }

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

2859:    Logically Collective on SNES

2861:    Input Parameters:
2862: +  snes - the SNES context
2863: -  steps - the number of refinements to do, defaults to 0

2865:    Options Database Keys:
2866: .    -snes_grid_sequence <steps>

2868:    Level: intermediate

2870:    Notes:
2871:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2877: @*/
2878: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
2879: {
2883:   snes->gridsequence = steps;
2884:   return(0);
2885: }

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

2890:    Logically Collective on SNES

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

2895:    Output Parameter:
2896: .  steps - the number of refinements to do, defaults to 0

2898:    Options Database Keys:
2899: .    -snes_grid_sequence <steps>

2901:    Level: intermediate

2903:    Notes:
2904:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2910: @*/
2911: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
2912: {
2915:   *steps = snes->gridsequence;
2916:   return(0);
2917: }

2919: /*@
2920:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

2922:    Not Collective

2924:    Input Parameter:
2925: .  snes - the SNES context

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

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

2934:    Notes:
2935:    The default is 1
2936:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

2938:    Level: intermediate

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

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

2944: @*/
2945: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
2946: {
2949:   *lag = snes->lagpreconditioner;
2950:   return(0);
2951: }

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

2957:    Logically Collective on SNES

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

2964:    Options Database Keys:
2965: .    -snes_lag_jacobian <lag>

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

2973:    Level: intermediate

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

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

2979: @*/
2980: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
2981: {
2984:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
2985:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
2987:   snes->lagjacobian = lag;
2988:   return(0);
2989: }

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

2994:    Not Collective

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

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

3003:    Options Database Keys:
3004: .    -snes_lag_jacobian <lag>

3006:    Notes:
3007:    The default is 1
3008:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3010:    Level: intermediate

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

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

3016: @*/
3017: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3018: {
3021:   *lag = snes->lagjacobian;
3022:   return(0);
3023: }

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

3028:    Logically collective on SNES

3030:    Input Parameter:
3031: +  snes - the SNES context
3032: -   flg - jacobian lagging persists if true

3034:    Options Database Keys:
3035: .    -snes_lag_jacobian_persists <flg>

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

3041:    Level: developer

3043: .keywords: SNES, nonlinear, lag

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

3047: @*/
3048: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3049: {
3053:   snes->lagjac_persist = flg;
3054:   return(0);
3055: }

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

3060:    Logically Collective on SNES

3062:    Input Parameter:
3063: +  snes - the SNES context
3064: -   flg - preconditioner lagging persists if true

3066:    Options Database Keys:
3067: .    -snes_lag_jacobian_persists <flg>

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

3073:    Level: developer

3075: .keywords: SNES, nonlinear, lag

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

3079: @*/
3080: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3081: {
3085:   snes->lagpre_persist = flg;
3086:   return(0);
3087: }

3089: /*@
3090:    SNESSetTolerances - Sets various parameters used in convergence tests.

3092:    Logically Collective on SNES

3094:    Input Parameters:
3095: +  snes - the SNES context
3096: .  abstol - absolute convergence tolerance
3097: .  rtol - relative convergence tolerance
3098: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3099: .  maxit - maximum number of iterations
3100: -  maxf - maximum number of function evaluations

3102:    Options Database Keys:
3103: +    -snes_atol <abstol> - Sets abstol
3104: .    -snes_rtol <rtol> - Sets rtol
3105: .    -snes_stol <stol> - Sets stol
3106: .    -snes_max_it <maxit> - Sets maxit
3107: -    -snes_max_funcs <maxf> - Sets maxf

3109:    Notes:
3110:    The default maximum number of iterations is 50.
3111:    The default maximum number of function evaluations is 1000.

3113:    Level: intermediate

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

3117: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3118: @*/
3119: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3120: {

3129:   if (abstol != PETSC_DEFAULT) {
3130:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3131:     snes->abstol = abstol;
3132:   }
3133:   if (rtol != PETSC_DEFAULT) {
3134:     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);
3135:     snes->rtol = rtol;
3136:   }
3137:   if (stol != PETSC_DEFAULT) {
3138:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3139:     snes->stol = stol;
3140:   }
3141:   if (maxit != PETSC_DEFAULT) {
3142:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3143:     snes->max_its = maxit;
3144:   }
3145:   if (maxf != PETSC_DEFAULT) {
3146:     if (maxf < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be non-negative",maxf);
3147:     snes->max_funcs = maxf;
3148:   }
3149:   snes->tolerancesset = PETSC_TRUE;
3150:   return(0);
3151: }

3153: /*@
3154:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3156:    Logically Collective on SNES

3158:    Input Parameters:
3159: +  snes - the SNES context
3160: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3162:    Options Database Keys:
3163: +    -snes_divergence_tolerance <divtol> - Sets divtol

3165:    Notes:
3166:    The default divergence tolerance is 1e4.

3168:    Level: intermediate

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

3172: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3173: @*/
3174: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3175: {

3180:   if (divtol != PETSC_DEFAULT) {
3181:     snes->divtol = divtol;
3182:   }
3183:   else {
3184:     snes->divtol = 1.0e4;
3185:   }
3186:   return(0);
3187: }

3189: /*@
3190:    SNESGetTolerances - Gets various parameters used in convergence tests.

3192:    Not Collective

3194:    Input Parameters:
3195: +  snes - the SNES context
3196: .  atol - absolute convergence tolerance
3197: .  rtol - relative convergence tolerance
3198: .  stol -  convergence tolerance in terms of the norm
3199:            of the change in the solution between steps
3200: .  maxit - maximum number of iterations
3201: -  maxf - maximum number of function evaluations

3203:    Notes:
3204:    The user can specify NULL for any parameter that is not needed.

3206:    Level: intermediate

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

3210: .seealso: SNESSetTolerances()
3211: @*/
3212: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3213: {
3216:   if (atol)  *atol  = snes->abstol;
3217:   if (rtol)  *rtol  = snes->rtol;
3218:   if (stol)  *stol  = snes->stol;
3219:   if (maxit) *maxit = snes->max_its;
3220:   if (maxf)  *maxf  = snes->max_funcs;
3221:   return(0);
3222: }

3224: /*@
3225:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3227:    Not Collective

3229:    Input Parameters:
3230: +  snes - the SNES context
3231: -  divtol - divergence tolerance

3233:    Level: intermediate

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

3237: .seealso: SNESSetDivergenceTolerance()
3238: @*/
3239: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3240: {
3243:   if (divtol) *divtol = snes->divtol;
3244:   return(0);
3245: }

3247: /*@
3248:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3250:    Logically Collective on SNES

3252:    Input Parameters:
3253: +  snes - the SNES context
3254: -  tol - tolerance

3256:    Options Database Key:
3257: .  -snes_trtol <tol> - Sets tol

3259:    Level: intermediate

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

3263: .seealso: SNESSetTolerances()
3264: @*/
3265: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3266: {
3270:   snes->deltatol = tol;
3271:   return(0);
3272: }

3274: /*
3275:    Duplicate the lg monitors for SNES from KSP; for some reason with
3276:    dynamic libraries things don't work under Sun4 if we just use
3277:    macros instead of functions
3278: */
3279: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3280: {

3285:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3286:   return(0);
3287: }

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

3294:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3295:   return(0);
3296: }

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

3300: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3301: {
3302:   PetscDrawLG      lg;
3303:   PetscErrorCode   ierr;
3304:   PetscReal        x,y,per;
3305:   PetscViewer      v = (PetscViewer)monctx;
3306:   static PetscReal prev; /* should be in the context */
3307:   PetscDraw        draw;

3311:   PetscViewerDrawGetDrawLG(v,0,&lg);
3312:   if (!n) {PetscDrawLGReset(lg);}
3313:   PetscDrawLGGetDraw(lg,&draw);
3314:   PetscDrawSetTitle(draw,"Residual norm");
3315:   x    = (PetscReal)n;
3316:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3317:   else y = -15.0;
3318:   PetscDrawLGAddPoint(lg,&x,&y);
3319:   if (n < 20 || !(n % 5) || snes->reason) {
3320:     PetscDrawLGDraw(lg);
3321:     PetscDrawLGSave(lg);
3322:   }

3324:   PetscViewerDrawGetDrawLG(v,1,&lg);
3325:   if (!n) {PetscDrawLGReset(lg);}
3326:   PetscDrawLGGetDraw(lg,&draw);
3327:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3328:    SNESMonitorRange_Private(snes,n,&per);
3329:   x    = (PetscReal)n;
3330:   y    = 100.0*per;
3331:   PetscDrawLGAddPoint(lg,&x,&y);
3332:   if (n < 20 || !(n % 5) || snes->reason) {
3333:     PetscDrawLGDraw(lg);
3334:     PetscDrawLGSave(lg);
3335:   }

3337:   PetscViewerDrawGetDrawLG(v,2,&lg);
3338:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3339:   PetscDrawLGGetDraw(lg,&draw);
3340:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3341:   x    = (PetscReal)n;
3342:   y    = (prev - rnorm)/prev;
3343:   PetscDrawLGAddPoint(lg,&x,&y);
3344:   if (n < 20 || !(n % 5) || snes->reason) {
3345:     PetscDrawLGDraw(lg);
3346:     PetscDrawLGSave(lg);
3347:   }

3349:   PetscViewerDrawGetDrawLG(v,3,&lg);
3350:   if (!n) {PetscDrawLGReset(lg);}
3351:   PetscDrawLGGetDraw(lg,&draw);
3352:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3353:   x    = (PetscReal)n;
3354:   y    = (prev - rnorm)/(prev*per);
3355:   if (n > 2) { /*skip initial crazy value */
3356:     PetscDrawLGAddPoint(lg,&x,&y);
3357:   }
3358:   if (n < 20 || !(n % 5) || snes->reason) {
3359:     PetscDrawLGDraw(lg);
3360:     PetscDrawLGSave(lg);
3361:   }
3362:   prev = rnorm;
3363:   return(0);
3364: }

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

3369:    Collective on SNES

3371:    Input Parameters:
3372: +  snes - nonlinear solver context obtained from SNESCreate()
3373: .  iter - iteration number
3374: -  rnorm - relative norm of the residual

3376:    Notes:
3377:    This routine is called by the SNES implementations.
3378:    It does not typically need to be called by the user.

3380:    Level: developer

3382: .seealso: SNESMonitorSet()
3383: @*/
3384: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3385: {
3387:   PetscInt       i,n = snes->numbermonitors;

3390:   VecLockPush(snes->vec_sol);
3391:   for (i=0; i<n; i++) {
3392:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3393:   }
3394:   VecLockPop(snes->vec_sol);
3395:   return(0);
3396: }

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

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

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

3407: +    snes - the SNES context
3408: .    its - iteration number
3409: .    norm - 2-norm function value (may be estimated)
3410: -    mctx - [optional] monitoring context

3412:    Level: advanced

3414: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3415: M*/

3417: /*@C
3418:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3419:    iteration of the nonlinear solver to display the iteration's
3420:    progress.

3422:    Logically Collective on SNES

3424:    Input Parameters:
3425: +  snes - the SNES context
3426: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3427: .  mctx - [optional] user-defined context for private data for the
3428:           monitor routine (use NULL if no context is desired)
3429: -  monitordestroy - [optional] routine that frees monitor context
3430:           (may be NULL)

3432:    Options Database Keys:
3433: +    -snes_monitor        - sets SNESMonitorDefault()
3434: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3435:                             uses SNESMonitorLGCreate()
3436: -    -snes_monitor_cancel - cancels all monitors that have
3437:                             been hardwired into a code by
3438:                             calls to SNESMonitorSet(), but
3439:                             does not cancel those set via
3440:                             the options database.

3442:    Notes:
3443:    Several different monitoring routines may be set by calling
3444:    SNESMonitorSet() multiple times; all will be called in the
3445:    order in which they were set.

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

3449:    Level: intermediate

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

3453: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3454: @*/
3455: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3456: {
3457:   PetscInt       i;
3459:   PetscBool      identical;

3463:   for (i=0; i<snes->numbermonitors;i++) {
3464:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3465:     if (identical) return(0);
3466:   }
3467:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3468:   snes->monitor[snes->numbermonitors]          = f;
3469:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3470:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3471:   return(0);
3472: }

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

3477:    Logically Collective on SNES

3479:    Input Parameters:
3480: .  snes - the SNES context

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

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

3490:    Level: intermediate

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

3494: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3495: @*/
3496: PetscErrorCode  SNESMonitorCancel(SNES snes)
3497: {
3499:   PetscInt       i;

3503:   for (i=0; i<snes->numbermonitors; i++) {
3504:     if (snes->monitordestroy[i]) {
3505:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3506:     }
3507:   }
3508:   snes->numbermonitors = 0;
3509:   return(0);
3510: }

3512: /*MC
3513:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3519: +    snes - the SNES context
3520: .    it - current iteration (0 is the first and is before any Newton step)
3521: .    cctx - [optional] convergence context
3522: .    reason - reason for convergence/divergence
3523: .    xnorm - 2-norm of current iterate
3524: .    gnorm - 2-norm of current step
3525: -    f - 2-norm of function

3527:    Level: intermediate

3529: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3530: M*/

3532: /*@C
3533:    SNESSetConvergenceTest - Sets the function that is to be used
3534:    to test for convergence of the nonlinear iterative solution.

3536:    Logically Collective on SNES

3538:    Input Parameters:
3539: +  snes - the SNES context
3540: .  SNESConvergenceTestFunction - routine to test for convergence
3541: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3542: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3544:    Level: advanced

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

3548: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3549: @*/
3550: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3551: {

3556:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3557:   if (snes->ops->convergeddestroy) {
3558:     (*snes->ops->convergeddestroy)(snes->cnvP);
3559:   }
3560:   snes->ops->converged        = SNESConvergenceTestFunction;
3561:   snes->ops->convergeddestroy = destroy;
3562:   snes->cnvP                  = cctx;
3563:   return(0);
3564: }

3566: /*@
3567:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3569:    Not Collective

3571:    Input Parameter:
3572: .  snes - the SNES context

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

3578:    Options Database:
3579: .   -snes_converged_reason - prints the reason to standard out

3581:    Level: intermediate

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

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

3587: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
3588: @*/
3589: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3590: {
3594:   *reason = snes->reason;
3595:   return(0);
3596: }

3598: /*@
3599:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3601:    Not Collective

3603:    Input Parameters:
3604: +  snes - the SNES context
3605: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
3606:             manual pages for the individual convergence tests for complete lists

3608:    Level: intermediate

3610: .keywords: SNES, nonlinear, set, convergence, test
3611: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
3612: @*/
3613: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
3614: {
3617:   snes->reason = reason;
3618:   return(0);
3619: }

3621: /*@
3622:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3624:    Logically Collective on SNES

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

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

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

3642:    Level: intermediate

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

3646: .seealso: SNESGetConvergenceHistory()

3648: @*/
3649: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3650: {

3657:   if (!a) {
3658:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3659:     PetscCalloc1(na,&a);
3660:     PetscCalloc1(na,&its);

3662:     snes->conv_malloc = PETSC_TRUE;
3663:   }
3664:   snes->conv_hist       = a;
3665:   snes->conv_hist_its   = its;
3666:   snes->conv_hist_max   = na;
3667:   snes->conv_hist_len   = 0;
3668:   snes->conv_hist_reset = reset;
3669:   return(0);
3670: }

3672: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3673: #include <engine.h>   /* MATLAB include file */
3674: #include <mex.h>      /* MATLAB include file */

3676: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3677: {
3678:   mxArray   *mat;
3679:   PetscInt  i;
3680:   PetscReal *ar;

3683:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3684:   ar  = (PetscReal*) mxGetData(mat);
3685:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3686:   PetscFunctionReturn(mat);
3687: }
3688: #endif

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

3693:    Not Collective

3695:    Input Parameter:
3696: .  snes - iterative context obtained from SNESCreate()

3698:    Output Parameters:
3699: .  a   - array to hold history
3700: .  its - integer array holds the number of linear iterations (or
3701:          negative if not converged) for each solve.
3702: -  na  - size of a and its

3704:    Notes:
3705:     The calling sequence for this routine in Fortran is
3706: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

3712:    Level: intermediate

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

3716: .seealso: SNESSetConvergencHistory()

3718: @*/
3719: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
3720: {
3723:   if (a)   *a   = snes->conv_hist;
3724:   if (its) *its = snes->conv_hist_its;
3725:   if (na)  *na  = snes->conv_hist_len;
3726:   return(0);
3727: }

3729: /*@C
3730:   SNESSetUpdate - Sets the general-purpose update function called
3731:   at the beginning of every iteration of the nonlinear solve. Specifically
3732:   it is called just before the Jacobian is "evaluated".

3734:   Logically Collective on SNES

3736:   Input Parameters:
3737: . snes - The nonlinear solver context
3738: . func - The function

3740:   Calling sequence of func:
3741: . func (SNES snes, PetscInt step);

3743: . step - The current step of the iteration

3745:   Level: advanced

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

3750: .keywords: SNES, update

3752: .seealso SNESSetJacobian(), SNESSolve()
3753: @*/
3754: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
3755: {
3758:   snes->ops->update = func;
3759:   return(0);
3760: }

3762: /*
3763:    SNESScaleStep_Private - Scales a step so that its length is less than the
3764:    positive parameter delta.

3766:     Input Parameters:
3767: +   snes - the SNES context
3768: .   y - approximate solution of linear system
3769: .   fnorm - 2-norm of current function
3770: -   delta - trust region size

3772:     Output Parameters:
3773: +   gpnorm - predicted function norm at the new point, assuming local
3774:     linearization.  The value is zero if the step lies within the trust
3775:     region, and exceeds zero otherwise.
3776: -   ynorm - 2-norm of the step

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

3782: .keywords: SNES, nonlinear, scale, step
3783: */
3784: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
3785: {
3786:   PetscReal      nrm;
3787:   PetscScalar    cnorm;


3795:   VecNorm(y,NORM_2,&nrm);
3796:   if (nrm > *delta) {
3797:     nrm     = *delta/nrm;
3798:     *gpnorm = (1.0 - nrm)*(*fnorm);
3799:     cnorm   = nrm;
3800:     VecScale(y,cnorm);
3801:     *ynorm  = *delta;
3802:   } else {
3803:     *gpnorm = 0.0;
3804:     *ynorm  = nrm;
3805:   }
3806:   return(0);
3807: }

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

3812:    Collective on SNES

3814:    Parameter:
3815: +  snes - iterative context obtained from SNESCreate()
3816: -  viewer - the viewer to display the reason


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

3822:    Level: beginner

3824: .keywords: SNES, solve, linear system

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

3828: @*/
3829: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
3830: {
3832:   PetscBool      isAscii;

3835:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
3836:   if (isAscii) {
3837:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
3838:     if (snes->reason > 0) {
3839:       if (((PetscObject) snes)->prefix) {
3840:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3841:       } else {
3842:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3843:       }
3844:     } else {
3845:       if (((PetscObject) snes)->prefix) {
3846:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3847:       } else {
3848:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3849:       }
3850:     }
3851:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
3852:   }
3853:   return(0);
3854: }

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

3859:   Collective on SNES

3861:   Input Parameters:
3862: . snes   - the SNES object

3864:   Level: intermediate

3866: @*/
3867: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
3868: {
3869:   PetscErrorCode    ierr;
3870:   PetscViewer       viewer;
3871:   PetscBool         flg;
3872:   static PetscBool  incall = PETSC_FALSE;
3873:   PetscViewerFormat format;

3876:   if (incall) return(0);
3877:   incall = PETSC_TRUE;
3878:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
3879:   if (flg) {
3880:     PetscViewerPushFormat(viewer,format);
3881:     SNESReasonView(snes,viewer);
3882:     PetscViewerPopFormat(viewer);
3883:     PetscViewerDestroy(&viewer);
3884:   }
3885:   incall = PETSC_FALSE;
3886:   return(0);
3887: }

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

3893:    Collective on SNES

3895:    Input Parameters:
3896: +  snes - the SNES context
3897: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
3898: -  x - the solution vector.

3900:    Notes:
3901:    The user should initialize the vector,x, with the initial guess
3902:    for the nonlinear solve prior to calling SNESSolve.  In particular,
3903:    to employ an initial guess of zero, the user should explicitly set
3904:    this vector to zero by calling VecSet().

3906:    Level: beginner

3908: .keywords: SNES, nonlinear, solve

3910: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
3911: @*/
3912: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
3913: {
3914:   PetscErrorCode    ierr;
3915:   PetscBool         flg;
3916:   PetscInt          grid;
3917:   Vec               xcreated = NULL;
3918:   DM                dm;


3927:   if (!x) {
3928:     SNESGetDM(snes,&dm);
3929:     DMCreateGlobalVector(dm,&xcreated);
3930:     x    = xcreated;
3931:   }
3932:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

3937:     /* set solution vector */
3938:     if (!grid) {PetscObjectReference((PetscObject)x);}
3939:     VecDestroy(&snes->vec_sol);
3940:     snes->vec_sol = x;
3941:     SNESGetDM(snes,&dm);

3943:     /* set affine vector if provided */
3944:     if (b) { PetscObjectReference((PetscObject)b); }
3945:     VecDestroy(&snes->vec_rhs);
3946:     snes->vec_rhs = b;

3948:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
3949:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
3950:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
3951:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
3952:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
3953:     }
3954:     DMShellSetGlobalVector(dm,snes->vec_sol);
3955:     SNESSetUp(snes);

3957:     if (!grid) {
3958:       if (snes->ops->computeinitialguess) {
3959:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
3960:       }
3961:     }

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

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

3972:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
3973:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

3979:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
3980:     if (snes->reason < 0) break;
3981:     if (grid <  snes->gridsequence) {
3982:       DM  fine;
3983:       Vec xnew;
3984:       Mat interp;

3986:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
3987:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
3988:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
3989:       DMCreateGlobalVector(fine,&xnew);
3990:       MatInterpolate(interp,x,xnew);
3991:       DMInterpolate(snes->dm,interp,fine);
3992:       MatDestroy(&interp);
3993:       x    = xnew;

3995:       SNESReset(snes);
3996:       SNESSetDM(snes,fine);
3997:       DMDestroy(&fine);
3998:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
3999:     }
4000:   }
4001:   SNESViewFromOptions(snes,NULL,"-snes_view");
4002:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4004:   VecDestroy(&xcreated);
4005:   PetscObjectSAWsBlock((PetscObject)snes);
4006:   return(0);
4007: }

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

4011: /*@C
4012:    SNESSetType - Sets the method for the nonlinear solver.

4014:    Collective on SNES

4016:    Input Parameters:
4017: +  snes - the SNES context
4018: -  type - a known method

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

4024:    Notes:
4025:    See "petsc/include/petscsnes.h" for available methods (for instance)
4026: +    SNESNEWTONLS - Newton's method with line search
4027:      (systems of nonlinear equations)
4028: .    SNESNEWTONTR - Newton's method with trust region
4029:      (systems of nonlinear equations)

4031:   Normally, it is best to use the SNESSetFromOptions() command and then
4032:   set the SNES solver type from the options database rather than by using
4033:   this routine.  Using the options database provides the user with
4034:   maximum flexibility in evaluating the many nonlinear solvers.
4035:   The SNESSetType() routine is provided for those situations where it
4036:   is necessary to set the nonlinear solver independently of the command
4037:   line or options database.  This might be the case, for example, when
4038:   the choice of solver changes during the execution of the program,
4039:   and the user's application is taking responsibility for choosing the
4040:   appropriate method.

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

4045:   Level: intermediate

4047: .keywords: SNES, set, type

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

4051: @*/
4052: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4053: {
4054:   PetscErrorCode ierr,(*r)(SNES);
4055:   PetscBool      match;


4061:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4062:   if (match) return(0);

4064:    PetscFunctionListFind(SNESList,type,&r);
4065:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4066:   /* Destroy the previous private SNES context */
4067:   if (snes->ops->destroy) {
4068:     (*(snes)->ops->destroy)(snes);
4069:     snes->ops->destroy = NULL;
4070:   }
4071:   /* Reinitialize function pointers in SNESOps structure */
4072:   snes->ops->setup          = 0;
4073:   snes->ops->solve          = 0;
4074:   snes->ops->view           = 0;
4075:   snes->ops->setfromoptions = 0;
4076:   snes->ops->destroy        = 0;
4077:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4078:   snes->setupcalled = PETSC_FALSE;

4080:   PetscObjectChangeTypeName((PetscObject)snes,type);
4081:   (*r)(snes);
4082:   return(0);
4083: }

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

4088:    Not Collective

4090:    Input Parameter:
4091: .  snes - nonlinear solver context

4093:    Output Parameter:
4094: .  type - SNES method (a character string)

4096:    Level: intermediate

4098: .keywords: SNES, nonlinear, get, type, name
4099: @*/
4100: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4101: {
4105:   *type = ((PetscObject)snes)->type_name;
4106:   return(0);
4107: }

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

4112:   Logically Collective on SNES and Vec

4114:   Input Parameters:
4115: + snes - the SNES context obtained from SNESCreate()
4116: - u    - the solution vector

4118:   Level: beginner

4120: .keywords: SNES, set, solution
4121: @*/
4122: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4123: {
4124:   DM             dm;

4130:   PetscObjectReference((PetscObject) u);
4131:   VecDestroy(&snes->vec_sol);

4133:   snes->vec_sol = u;

4135:   SNESGetDM(snes, &dm);
4136:   DMShellSetGlobalVector(dm, u);
4137:   return(0);
4138: }

4140: /*@
4141:    SNESGetSolution - Returns the vector where the approximate solution is
4142:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4146:    Input Parameter:
4147: .  snes - the SNES context

4149:    Output Parameter:
4150: .  x - the solution

4152:    Level: intermediate

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

4156: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4157: @*/
4158: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4159: {
4163:   *x = snes->vec_sol;
4164:   return(0);
4165: }

4167: /*@
4168:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4169:    stored.

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

4173:    Input Parameter:
4174: .  snes - the SNES context

4176:    Output Parameter:
4177: .  x - the solution update

4179:    Level: advanced

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

4183: .seealso: SNESGetSolution(), SNESGetFunction()
4184: @*/
4185: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4186: {
4190:   *x = snes->vec_sol_update;
4191:   return(0);
4192: }

4194: /*@C
4195:    SNESGetFunction - Returns the vector where the function is stored.

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

4199:    Input Parameter:
4200: .  snes - the SNES context

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

4207:    Level: advanced

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

4211: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4212: @*/
4213: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4214: {
4216:   DM             dm;

4220:   if (r) {
4221:     if (!snes->vec_func) {
4222:       if (snes->vec_rhs) {
4223:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4224:       } else if (snes->vec_sol) {
4225:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4226:       } else if (snes->dm) {
4227:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4228:       }
4229:     }
4230:     *r = snes->vec_func;
4231:   }
4232:   SNESGetDM(snes,&dm);
4233:   DMSNESGetFunction(dm,f,ctx);
4234:   return(0);
4235: }

4237: /*@C
4238:    SNESGetNGS - Returns the NGS function and context.

4240:    Input Parameter:
4241: .  snes - the SNES context

4243:    Output Parameter:
4244: +  f - the function (or NULL) see SNESNGSFunction for details
4245: -  ctx    - the function context (or NULL)

4247:    Level: advanced

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

4251: .seealso: SNESSetNGS(), SNESGetFunction()
4252: @*/

4254: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4255: {
4257:   DM             dm;

4261:   SNESGetDM(snes,&dm);
4262:   DMSNESGetNGS(dm,f,ctx);
4263:   return(0);
4264: }

4266: /*@C
4267:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4268:    SNES options in the database.

4270:    Logically Collective on SNES

4272:    Input Parameter:
4273: +  snes - the SNES context
4274: -  prefix - the prefix to prepend to all option names

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

4280:    Level: advanced

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

4284: .seealso: SNESSetFromOptions()
4285: @*/
4286: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4287: {

4292:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4293:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4294:   if (snes->linesearch) {
4295:     SNESGetLineSearch(snes,&snes->linesearch);
4296:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4297:   }
4298:   KSPSetOptionsPrefix(snes->ksp,prefix);
4299:   return(0);
4300: }

4302: /*@C
4303:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4304:    SNES options in the database.

4306:    Logically Collective on SNES

4308:    Input Parameters:
4309: +  snes - the SNES context
4310: -  prefix - the prefix to prepend to all option names

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

4316:    Level: advanced

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

4320: .seealso: SNESGetOptionsPrefix()
4321: @*/
4322: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4323: {

4328:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4329:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4330:   if (snes->linesearch) {
4331:     SNESGetLineSearch(snes,&snes->linesearch);
4332:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4333:   }
4334:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4335:   return(0);
4336: }

4338: /*@C
4339:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4340:    SNES options in the database.

4342:    Not Collective

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

4347:    Output Parameter:
4348: .  prefix - pointer to the prefix string used

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

4353:    Level: advanced

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

4357: .seealso: SNESAppendOptionsPrefix()
4358: @*/
4359: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4360: {

4365:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4366:   return(0);
4367: }


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

4373:    Not collective

4375:    Input Parameters:
4376: +  name_solver - name of a new user-defined solver
4377: -  routine_create - routine to create method context

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

4382:    Sample usage:
4383: .vb
4384:    SNESRegister("my_solver",MySolverCreate);
4385: .ve

4387:    Then, your solver can be chosen with the procedural interface via
4388: $     SNESSetType(snes,"my_solver")
4389:    or at runtime via the option
4390: $     -snes_type my_solver

4392:    Level: advanced

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

4396: .keywords: SNES, nonlinear, register

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

4400:   Level: advanced
4401: @*/
4402: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4403: {

4407:   PetscFunctionListAdd(&SNESList,sname,function);
4408:   return(0);
4409: }

4411: PetscErrorCode  SNESTestLocalMin(SNES snes)
4412: {
4414:   PetscInt       N,i,j;
4415:   Vec            u,uh,fh;
4416:   PetscScalar    value;
4417:   PetscReal      norm;

4420:   SNESGetSolution(snes,&u);
4421:   VecDuplicate(u,&uh);
4422:   VecDuplicate(u,&fh);

4424:   /* currently only works for sequential */
4425:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4426:   VecGetSize(u,&N);
4427:   for (i=0; i<N; i++) {
4428:     VecCopy(u,uh);
4429:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4430:     for (j=-10; j<11; j++) {
4431:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4432:       VecSetValue(uh,i,value,ADD_VALUES);
4433:       SNESComputeFunction(snes,uh,fh);
4434:       VecNorm(fh,NORM_2,&norm);
4435:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4436:       value = -value;
4437:       VecSetValue(uh,i,value,ADD_VALUES);
4438:     }
4439:   }
4440:   VecDestroy(&uh);
4441:   VecDestroy(&fh);
4442:   return(0);
4443: }

4445: /*@
4446:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4447:    computing relative tolerance for linear solvers within an inexact
4448:    Newton method.

4450:    Logically Collective on SNES

4452:    Input Parameters:
4453: +  snes - SNES context
4454: -  flag - PETSC_TRUE or PETSC_FALSE

4456:     Options Database:
4457: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4458: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4459: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4460: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4461: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4462: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4463: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4464: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4466:    Notes:
4467:    Currently, the default is to use a constant relative tolerance for
4468:    the inner linear solvers.  Alternatively, one can use the
4469:    Eisenstat-Walker method, where the relative convergence tolerance
4470:    is reset at each Newton iteration according progress of the nonlinear
4471:    solver.

4473:    Level: advanced

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

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

4481: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4482: @*/
4483: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4484: {
4488:   snes->ksp_ewconv = flag;
4489:   return(0);
4490: }

4492: /*@
4493:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4494:    for computing relative tolerance for linear solvers within an
4495:    inexact Newton method.

4497:    Not Collective

4499:    Input Parameter:
4500: .  snes - SNES context

4502:    Output Parameter:
4503: .  flag - PETSC_TRUE or PETSC_FALSE

4505:    Notes:
4506:    Currently, the default is to use a constant relative tolerance for
4507:    the inner linear solvers.  Alternatively, one can use the
4508:    Eisenstat-Walker method, where the relative convergence tolerance
4509:    is reset at each Newton iteration according progress of the nonlinear
4510:    solver.

4512:    Level: advanced

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

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

4520: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4521: @*/
4522: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4523: {
4527:   *flag = snes->ksp_ewconv;
4528:   return(0);
4529: }

4531: /*@
4532:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4533:    convergence criteria for the linear solvers within an inexact
4534:    Newton method.

4536:    Logically Collective on SNES

4538:    Input Parameters:
4539: +    snes - SNES context
4540: .    version - version 1, 2 (default is 2) or 3
4541: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4542: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4543: .    gamma - multiplicative factor for version 2 rtol computation
4544:              (0 <= gamma2 <= 1)
4545: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4546: .    alpha2 - power for safeguard
4547: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4549:    Note:
4550:    Version 3 was contributed by Luis Chacon, June 2006.

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

4554:    Level: advanced

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

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

4563: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4564: @*/
4565: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4566: {
4567:   SNESKSPEW *kctx;

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

4581:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4582:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4583:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4584:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4585:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4586:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4587:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4589:   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);
4590:   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);
4591:   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);
4592:   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);
4593:   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);
4594:   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);
4595:   return(0);
4596: }

4598: /*@
4599:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4600:    convergence criteria for the linear solvers within an inexact
4601:    Newton method.

4603:    Not Collective

4605:    Input Parameters:
4606:      snes - SNES context

4608:    Output Parameters:
4609: +    version - version 1, 2 (default is 2) or 3
4610: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4611: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4612: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
4613: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4614: .    alpha2 - power for safeguard
4615: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4617:    Level: advanced

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

4621: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
4622: @*/
4623: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
4624: {
4625:   SNESKSPEW *kctx;

4629:   kctx = (SNESKSPEW*)snes->kspconvctx;
4630:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
4631:   if (version)   *version   = kctx->version;
4632:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
4633:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
4634:   if (gamma)     *gamma     = kctx->gamma;
4635:   if (alpha)     *alpha     = kctx->alpha;
4636:   if (alpha2)    *alpha2    = kctx->alpha2;
4637:   if (threshold) *threshold = kctx->threshold;
4638:   return(0);
4639: }

4641:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4642: {
4644:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4645:   PetscReal      rtol  = PETSC_DEFAULT,stol;

4648:   if (!snes->ksp_ewconv) return(0);
4649:   if (!snes->iter) {
4650:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
4651:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
4652:   }
4653:   else {
4654:     if (kctx->version == 1) {
4655:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
4656:       if (rtol < 0.0) rtol = -rtol;
4657:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
4658:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4659:     } else if (kctx->version == 2) {
4660:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4661:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
4662:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4663:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
4664:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4665:       /* safeguard: avoid sharp decrease of rtol */
4666:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
4667:       stol = PetscMax(rtol,stol);
4668:       rtol = PetscMin(kctx->rtol_0,stol);
4669:       /* safeguard: avoid oversolving */
4670:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
4671:       stol = PetscMax(rtol,stol);
4672:       rtol = PetscMin(kctx->rtol_0,stol);
4673:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
4674:   }
4675:   /* safeguard: avoid rtol greater than one */
4676:   rtol = PetscMin(rtol,kctx->rtol_max);
4677:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
4678:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
4679:   return(0);
4680: }

4682: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4683: {
4685:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4686:   PCSide         pcside;
4687:   Vec            lres;

4690:   if (!snes->ksp_ewconv) return(0);
4691:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
4692:   kctx->norm_last = snes->norm;
4693:   if (kctx->version == 1) {
4694:     PC        pc;
4695:     PetscBool isNone;

4697:     KSPGetPC(ksp, &pc);
4698:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
4699:     KSPGetPCSide(ksp,&pcside);
4700:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
4701:       /* KSP residual is true linear residual */
4702:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
4703:     } else {
4704:       /* KSP residual is preconditioned residual */
4705:       /* compute true linear residual norm */
4706:       VecDuplicate(b,&lres);
4707:       MatMult(snes->jacobian,x,lres);
4708:       VecAYPX(lres,-1.0,b);
4709:       VecNorm(lres,NORM_2,&kctx->lresid_last);
4710:       VecDestroy(&lres);
4711:     }
4712:   }
4713:   return(0);
4714: }

4716: /*@
4717:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

4721:    Input Parameter:
4722: .  snes - the SNES context

4724:    Output Parameter:
4725: .  ksp - the KSP context

4727:    Notes:
4728:    The user can then directly manipulate the KSP context to set various
4729:    options, etc.  Likewise, the user can then extract and manipulate the
4730:    PC contexts as well.

4732:    Level: beginner

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

4736: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
4737: @*/
4738: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
4739: {


4746:   if (!snes->ksp) {
4747:     PetscBool monitor = PETSC_FALSE;

4749:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
4750:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
4751:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

4756:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
4757:     if (monitor) {
4758:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
4759:     }
4760:     monitor = PETSC_FALSE;
4761:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
4762:     if (monitor) {
4763:       PetscObject *objs;
4764:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
4765:       objs[0] = (PetscObject) snes;
4766:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
4767:     }
4768:   }
4769:   *ksp = snes->ksp;
4770:   return(0);
4771: }


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

4778:    Logically Collective on SNES

4780:    Input Parameters:
4781: +  snes - the nonlinear solver context
4782: -  dm - the dm, cannot be NULL

4784:    Level: intermediate

4786: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
4787: @*/
4788: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
4789: {
4791:   KSP            ksp;
4792:   DMSNES         sdm;

4797:   PetscObjectReference((PetscObject)dm);
4798:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
4799:     if (snes->dm->dmsnes && !dm->dmsnes) {
4800:       DMCopyDMSNES(snes->dm,dm);
4801:       DMGetDMSNES(snes->dm,&sdm);
4802:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
4803:     }
4804:     DMDestroy(&snes->dm);
4805:   }
4806:   snes->dm     = dm;
4807:   snes->dmAuto = PETSC_FALSE;

4809:   SNESGetKSP(snes,&ksp);
4810:   KSPSetDM(ksp,dm);
4811:   KSPSetDMActive(ksp,PETSC_FALSE);
4812:   if (snes->pc) {
4813:     SNESSetDM(snes->pc, snes->dm);
4814:     SNESSetNPCSide(snes,snes->pcside);
4815:   }
4816:   return(0);
4817: }

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

4822:    Not Collective but DM obtained is parallel on SNES

4824:    Input Parameter:
4825: . snes - the preconditioner context

4827:    Output Parameter:
4828: .  dm - the dm

4830:    Level: intermediate

4832: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
4833: @*/
4834: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
4835: {

4840:   if (!snes->dm) {
4841:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
4842:     snes->dmAuto = PETSC_TRUE;
4843:   }
4844:   *dm = snes->dm;
4845:   return(0);
4846: }

4848: /*@
4849:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

4851:   Collective on SNES

4853:   Input Parameters:
4854: + snes - iterative context obtained from SNESCreate()
4855: - pc   - the preconditioner object

4857:   Notes:
4858:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
4859:   to configure it using the API).

4861:   Level: developer

4863: .keywords: SNES, set, precondition
4864: .seealso: SNESGetNPC(), SNESHasNPC()
4865: @*/
4866: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
4867: {

4874:   PetscObjectReference((PetscObject) pc);
4875:   SNESDestroy(&snes->pc);
4876:   snes->pc = pc;
4877:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->pc);
4878:   return(0);
4879: }

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

4884:   Not Collective

4886:   Input Parameter:
4887: . snes - iterative context obtained from SNESCreate()

4889:   Output Parameter:
4890: . pc - preconditioner context

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

4894:   Level: developer

4896: .keywords: SNES, get, preconditioner
4897: .seealso: SNESSetNPC(), SNESHasNPC()
4898: @*/
4899: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
4900: {
4902:   const char     *optionsprefix;

4907:   if (!snes->pc) {
4908:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->pc);
4909:     PetscObjectIncrementTabLevel((PetscObject)snes->pc,(PetscObject)snes,1);
4910:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->pc);
4911:     SNESGetOptionsPrefix(snes,&optionsprefix);
4912:     SNESSetOptionsPrefix(snes->pc,optionsprefix);
4913:     SNESAppendOptionsPrefix(snes->pc,"npc_");
4914:     SNESSetCountersReset(snes->pc,PETSC_FALSE);
4915:   }
4916:   *pc = snes->pc;
4917:   return(0);
4918: }

4920: /*@
4921:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

4923:   Not Collective

4925:   Input Parameter:
4926: . snes - iterative context obtained from SNESCreate()

4928:   Output Parameter:
4929: . has_npc - whether the SNES has an NPC or not

4931:   Level: developer

4933: .keywords: SNES, has, preconditioner
4934: .seealso: SNESSetNPC(), SNESGetNPC()
4935: @*/
4936: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
4937: {
4940:   *has_npc = (PetscBool) (snes->pc ? PETSC_TRUE : PETSC_FALSE);
4941:   return(0);
4942: }

4944: /*@
4945:     SNESSetNPCSide - Sets the preconditioning side.

4947:     Logically Collective on SNES

4949:     Input Parameter:
4950: .   snes - iterative context obtained from SNESCreate()

4952:     Output Parameter:
4953: .   side - the preconditioning side, where side is one of
4954: .vb
4955:       PC_LEFT - left preconditioning
4956:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
4957: .ve

4959:     Options Database Keys:
4960: .   -snes_pc_side <right,left>

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

4964:     Level: intermediate

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

4968: .seealso: SNESGetNPCSide(), KSPSetPCSide()
4969: @*/
4970: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
4971: {
4975:   snes->pcside = side;
4976:   return(0);
4977: }

4979: /*@
4980:     SNESGetNPCSide - Gets the preconditioning side.

4982:     Not Collective

4984:     Input Parameter:
4985: .   snes - iterative context obtained from SNESCreate()

4987:     Output Parameter:
4988: .   side - the preconditioning side, where side is one of
4989: .vb
4990:       PC_LEFT - left preconditioning
4991:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
4992: .ve

4994:     Level: intermediate

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

4998: .seealso: SNESSetNPCSide(), KSPGetPCSide()
4999: @*/
5000: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5001: {
5005:   *side = snes->pcside;
5006:   return(0);
5007: }

5009: /*@
5010:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5012:   Collective on SNES

5014:   Input Parameters:
5015: + snes - iterative context obtained from SNESCreate()
5016: - linesearch   - the linesearch object

5018:   Notes:
5019:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5020:   to configure it using the API).

5022:   Level: developer

5024: .keywords: SNES, set, linesearch
5025: .seealso: SNESGetLineSearch()
5026: @*/
5027: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5028: {

5035:   PetscObjectReference((PetscObject) linesearch);
5036:   SNESLineSearchDestroy(&snes->linesearch);

5038:   snes->linesearch = linesearch;

5040:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5041:   return(0);
5042: }

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

5048:   Not Collective

5050:   Input Parameter:
5051: . snes - iterative context obtained from SNESCreate()

5053:   Output Parameter:
5054: . linesearch - linesearch context

5056:   Level: beginner

5058: .keywords: SNES, get, linesearch
5059: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5060: @*/
5061: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5062: {
5064:   const char     *optionsprefix;

5069:   if (!snes->linesearch) {
5070:     SNESGetOptionsPrefix(snes, &optionsprefix);
5071:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5072:     SNESLineSearchSetSNES(snes->linesearch, snes);
5073:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5074:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5075:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5076:   }
5077:   *linesearch = snes->linesearch;
5078:   return(0);
5079: }

5081: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5082: #include <mex.h>

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

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

5089:    Collective on SNES

5091:    Input Parameters:
5092: +  snes - the SNES context
5093: -  x - input vector

5095:    Output Parameter:
5096: .  y - function vector, as set by SNESSetFunction()

5098:    Notes:
5099:    SNESComputeFunction() is typically used within nonlinear solvers
5100:    implementations, so most users would not generally call this routine
5101:    themselves.

5103:    Level: developer

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

5107: .seealso: SNESSetFunction(), SNESGetFunction()
5108: */
5109: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5110: {
5111:   PetscErrorCode    ierr;
5112:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5113:   int               nlhs  = 1,nrhs = 5;
5114:   mxArray           *plhs[1],*prhs[5];
5115:   long long int     lx = 0,ly = 0,ls = 0;


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

5126:   PetscMemcpy(&ls,&snes,sizeof(snes));
5127:   PetscMemcpy(&lx,&x,sizeof(x));
5128:   PetscMemcpy(&ly,&y,sizeof(x));
5129:   prhs[0] = mxCreateDoubleScalar((double)ls);
5130:   prhs[1] = mxCreateDoubleScalar((double)lx);
5131:   prhs[2] = mxCreateDoubleScalar((double)ly);
5132:   prhs[3] = mxCreateString(sctx->funcname);
5133:   prhs[4] = sctx->ctx;
5134:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");
5135:   mxGetScalar(plhs[0]);
5136:   mxDestroyArray(prhs[0]);
5137:   mxDestroyArray(prhs[1]);
5138:   mxDestroyArray(prhs[2]);
5139:   mxDestroyArray(prhs[3]);
5140:   mxDestroyArray(plhs[0]);
5141:   return(0);
5142: }

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

5149:    Logically Collective on SNES

5151:    Input Parameters:
5152: +  snes - the SNES context
5153: .  r - vector to store function value
5154: -  f - function evaluation routine

5156:    Notes:
5157:    The Newton-like methods typically solve linear systems of the form
5158: $      f'(x) x = -f(x),
5159:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5161:    Level: beginner

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

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

5167: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5168: */
5169: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5170: {
5171:   PetscErrorCode    ierr;
5172:   SNESMatlabContext *sctx;

5175:   /* currently sctx is memory bleed */
5176:   PetscNew(&sctx);
5177:   PetscStrallocpy(f,&sctx->funcname);
5178:   /*
5179:      This should work, but it doesn't
5180:   sctx->ctx = ctx;
5181:   mexMakeArrayPersistent(sctx->ctx);
5182:   */
5183:   sctx->ctx = mxDuplicateArray(ctx);
5184:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5185:   return(0);
5186: }

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

5191:    Collective on SNES

5193:    Input Parameters:
5194: +  snes - the SNES context
5195: .  x - input vector
5196: .  A, B - the matrices
5197: -  ctx - user context

5199:    Level: developer

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

5203: .seealso: SNESSetFunction(), SNESGetFunction()
5204: @*/
5205: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5206: {
5207:   PetscErrorCode    ierr;
5208:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5209:   int               nlhs  = 2,nrhs = 6;
5210:   mxArray           *plhs[2],*prhs[6];
5211:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


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

5219:   PetscMemcpy(&ls,&snes,sizeof(snes));
5220:   PetscMemcpy(&lx,&x,sizeof(x));
5221:   PetscMemcpy(&lA,A,sizeof(x));
5222:   PetscMemcpy(&lB,B,sizeof(x));
5223:   prhs[0] = mxCreateDoubleScalar((double)ls);
5224:   prhs[1] = mxCreateDoubleScalar((double)lx);
5225:   prhs[2] = mxCreateDoubleScalar((double)lA);
5226:   prhs[3] = mxCreateDoubleScalar((double)lB);
5227:   prhs[4] = mxCreateString(sctx->funcname);
5228:   prhs[5] = sctx->ctx;
5229:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5230:   mxGetScalar(plhs[0]);
5231:   mxDestroyArray(prhs[0]);
5232:   mxDestroyArray(prhs[1]);
5233:   mxDestroyArray(prhs[2]);
5234:   mxDestroyArray(prhs[3]);
5235:   mxDestroyArray(prhs[4]);
5236:   mxDestroyArray(plhs[0]);
5237:   mxDestroyArray(plhs[1]);
5238:   return(0);
5239: }

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

5246:    Logically Collective on SNES

5248:    Input Parameters:
5249: +  snes - the SNES context
5250: .  A,B - Jacobian matrices
5251: .  J - function evaluation routine
5252: -  ctx - user context

5254:    Level: developer

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

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

5260: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5261: */
5262: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5263: {
5264:   PetscErrorCode    ierr;
5265:   SNESMatlabContext *sctx;

5268:   /* currently sctx is memory bleed */
5269:   PetscNew(&sctx);
5270:   PetscStrallocpy(J,&sctx->funcname);
5271:   /*
5272:      This should work, but it doesn't
5273:   sctx->ctx = ctx;
5274:   mexMakeArrayPersistent(sctx->ctx);
5275:   */
5276:   sctx->ctx = mxDuplicateArray(ctx);
5277:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5278:   return(0);
5279: }

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

5284:    Collective on SNES

5286: .seealso: SNESSetFunction(), SNESGetFunction()
5287: @*/
5288: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5289: {
5290:   PetscErrorCode    ierr;
5291:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5292:   int               nlhs  = 1,nrhs = 6;
5293:   mxArray           *plhs[1],*prhs[6];
5294:   long long int     lx = 0,ls = 0;
5295:   Vec               x  = snes->vec_sol;


5300:   PetscMemcpy(&ls,&snes,sizeof(snes));
5301:   PetscMemcpy(&lx,&x,sizeof(x));
5302:   prhs[0] = mxCreateDoubleScalar((double)ls);
5303:   prhs[1] = mxCreateDoubleScalar((double)it);
5304:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5305:   prhs[3] = mxCreateDoubleScalar((double)lx);
5306:   prhs[4] = mxCreateString(sctx->funcname);
5307:   prhs[5] = sctx->ctx;
5308:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5309:   mxGetScalar(plhs[0]);
5310:   mxDestroyArray(prhs[0]);
5311:   mxDestroyArray(prhs[1]);
5312:   mxDestroyArray(prhs[2]);
5313:   mxDestroyArray(prhs[3]);
5314:   mxDestroyArray(prhs[4]);
5315:   mxDestroyArray(plhs[0]);
5316:   return(0);
5317: }

5319: /*
5320:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5322:    Level: developer

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

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

5328: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5329: */
5330: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5331: {
5332:   PetscErrorCode    ierr;
5333:   SNESMatlabContext *sctx;

5336:   /* currently sctx is memory bleed */
5337:   PetscNew(&sctx);
5338:   PetscStrallocpy(f,&sctx->funcname);
5339:   /*
5340:      This should work, but it doesn't
5341:   sctx->ctx = ctx;
5342:   mexMakeArrayPersistent(sctx->ctx);
5343:   */
5344:   sctx->ctx = mxDuplicateArray(ctx);
5345:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5346:   return(0);
5347: }

5349: #endif