Actual source code: snes.c

petsc-master 2017-12-11
Report Typos and Errors

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

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

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

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

 19:    Logically Collective on SNES

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

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

 28:    Level: intermediate

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

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

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

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

 50:    Not Collective

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

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

 58:    Level: intermediate

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

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

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

 76:    Logically Collective on SNES

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

 82:    Level: advanced

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

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

 97:    Logically Collective on SNES

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

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

105:    Level: advanced

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

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

121:    Logically Collective on SNES

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

126:    Level: advanced

128: .keywords: SNES, view

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

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

144:    Logically Collective on SNES

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

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

152:    Level: advanced

154: .keywords: SNES, view

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

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

170:   Collective on PetscViewer

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

177:    Level: intermediate

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

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

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

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

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

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

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

232:    Collective on SNES

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

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

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

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

252:    Level: beginner

254: .keywords: SNES, view

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

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

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

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

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

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

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

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

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

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

432:   Not Collective

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

437:   Level: developer

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

600:    Collective

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

605:    Level: developer

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

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

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

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

665:    Collective on SNES

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

675:    Level: developer

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

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

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

709:    Collective on SNES

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

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

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

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

758:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

847:   flg  = PETSC_FALSE;
848:   PetscOptionsBool("-snes_check_jacobian","Check each Jacobian with a differenced one","SNESUpdateCheckJacobian",flg,&flg,&set);
849:   if (set && flg) {
850:     SNESSetUpdate(snes,SNESUpdateCheckJacobian);
851:   }

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

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

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

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


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

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

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



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

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

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

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

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

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

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

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

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

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

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

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

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

997:    Logically Collective on SNES

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

1004:    Level: intermediate

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

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

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

1022: /*@
1023:    SNESSetApplicationContext - Sets the optional user-defined context for
1024:    the nonlinear solvers.

1026:    Logically Collective on SNES

1028:    Input Parameters:
1029: +  snes - the SNES context
1030: -  usrP - optional user context

1032:    Level: intermediate

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

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

1039: .seealso: SNESGetApplicationContext()
1040: @*/
1041: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1042: {
1044:   KSP            ksp;

1048:   SNESGetKSP(snes,&ksp);
1049:   KSPSetApplicationContext(ksp,usrP);
1050:   snes->user = usrP;
1051:   return(0);
1052: }

1054: /*@
1055:    SNESGetApplicationContext - Gets the user-defined context for the
1056:    nonlinear solvers.

1058:    Not Collective

1060:    Input Parameter:
1061: .  snes - SNES context

1063:    Output Parameter:
1064: .  usrP - user context

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

1069:    Level: intermediate

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

1073: .seealso: SNESSetApplicationContext()
1074: @*/
1075: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1076: {
1079:   *(void**)usrP = snes->user;
1080:   return(0);
1081: }

1083: /*@
1084:    SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply
1085:                           the Jacobian.

1087:    Collective on SNES

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

1094:    Options Database:
1095: + -snes_mf - use matrix free for both the mat and pmat operator
1096: - -snes_mf_operator - use matrix free only for the mat operator

1098:    Level: intermediate

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

1102: .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF()
1103: @*/
1104: PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1105: {
1110:   if (mf && !mf_operator) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"If using mf must also use mf_operator");
1111:   snes->mf          = mf;
1112:   snes->mf_operator = mf_operator;
1113:   return(0);
1114: }

1116: /*@
1117:    SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply
1118:                           the Jacobian.

1120:    Collective on SNES

1122:    Input Parameter:
1123: .  snes - SNES context

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

1129:    Options Database:
1130: + -snes_mf - use matrix free for both the mat and pmat operator
1131: - -snes_mf_operator - use matrix free only for the mat operator

1133:    Level: intermediate

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

1137: .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
1138: @*/
1139: PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1140: {
1143:   if (mf)          *mf          = snes->mf;
1144:   if (mf_operator) *mf_operator = snes->mf_operator;
1145:   return(0);
1146: }

1148: /*@
1149:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1150:    at this time.

1152:    Not Collective

1154:    Input Parameter:
1155: .  snes - SNES context

1157:    Output Parameter:
1158: .  iter - iteration number

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

1163:    This is useful for using lagged Jacobians (where one does not recompute the
1164:    Jacobian at each SNES iteration). For example, the code
1165: .vb
1166:       SNESGetIterationNumber(snes,&it);
1167:       if (!(it % 2)) {
1168:         [compute Jacobian here]
1169:       }
1170: .ve
1171:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1172:    recomputed every second SNES iteration.

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

1176:    Level: intermediate

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

1180: .seealso:   SNESGetLinearSolveIterations()
1181: @*/
1182: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1183: {
1187:   *iter = snes->iter;
1188:   return(0);
1189: }

1191: /*@
1192:    SNESSetIterationNumber - Sets the current iteration number.

1194:    Not Collective

1196:    Input Parameter:
1197: .  snes - SNES context
1198: .  iter - iteration number

1200:    Level: developer

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

1204: .seealso:   SNESGetLinearSolveIterations()
1205: @*/
1206: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1207: {

1212:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1213:   snes->iter = iter;
1214:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1215:   return(0);
1216: }

1218: /*@
1219:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1220:    attempted by the nonlinear solver.

1222:    Not Collective

1224:    Input Parameter:
1225: .  snes - SNES context

1227:    Output Parameter:
1228: .  nfails - number of unsuccessful steps attempted

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

1233:    Level: intermediate

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

1237: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1238:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1239: @*/
1240: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1241: {
1245:   *nfails = snes->numFailures;
1246:   return(0);
1247: }

1249: /*@
1250:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1251:    attempted by the nonlinear solver before it gives up.

1253:    Not Collective

1255:    Input Parameters:
1256: +  snes     - SNES context
1257: -  maxFails - maximum of unsuccessful steps

1259:    Level: intermediate

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

1263: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1264:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1265: @*/
1266: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1267: {
1270:   snes->maxFailures = maxFails;
1271:   return(0);
1272: }

1274: /*@
1275:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1276:    attempted by the nonlinear solver before it gives up.

1278:    Not Collective

1280:    Input Parameter:
1281: .  snes     - SNES context

1283:    Output Parameter:
1284: .  maxFails - maximum of unsuccessful steps

1286:    Level: intermediate

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

1290: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1291:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1293: @*/
1294: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1295: {
1299:   *maxFails = snes->maxFailures;
1300:   return(0);
1301: }

1303: /*@
1304:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1305:      done by SNES.

1307:    Not Collective

1309:    Input Parameter:
1310: .  snes     - SNES context

1312:    Output Parameter:
1313: .  nfuncs - number of evaluations

1315:    Level: intermediate

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

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

1321: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1322: @*/
1323: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1324: {
1328:   *nfuncs = snes->nfuncs;
1329:   return(0);
1330: }

1332: /*@
1333:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1334:    linear solvers.

1336:    Not Collective

1338:    Input Parameter:
1339: .  snes - SNES context

1341:    Output Parameter:
1342: .  nfails - number of failed solves

1344:    Level: intermediate

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

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

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

1354: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1355: @*/
1356: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1357: {
1361:   *nfails = snes->numLinearSolveFailures;
1362:   return(0);
1363: }

1365: /*@
1366:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1367:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1369:    Logically Collective on SNES

1371:    Input Parameters:
1372: +  snes     - SNES context
1373: -  maxFails - maximum allowed linear solve failures

1375:    Level: intermediate

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

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

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

1384: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1385: @*/
1386: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1387: {
1391:   snes->maxLinearSolveFailures = maxFails;
1392:   return(0);
1393: }

1395: /*@
1396:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1397:      are allowed before SNES terminates

1399:    Not Collective

1401:    Input Parameter:
1402: .  snes     - SNES context

1404:    Output Parameter:
1405: .  maxFails - maximum of unsuccessful solves allowed

1407:    Level: intermediate

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

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

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

1424: /*@
1425:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1426:    used by the nonlinear solver.

1428:    Not Collective

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

1433:    Output Parameter:
1434: .  lits - number of linear iterations

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

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

1442:    Level: intermediate

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

1446: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1447: @*/
1448: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1449: {
1453:   *lits = snes->linear_its;
1454:   return(0);
1455: }

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

1461:    Logically Collective on SNES

1463:    Input Parameter:
1464: +  snes - SNES context
1465: -  reset - whether to reset the counters or not

1467:    Notes:
1468:    This defaults to PETSC_TRUE

1470:    Level: developer

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

1474: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1475: @*/
1476: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1477: {
1481:   snes->counters_reset = reset;
1482:   return(0);
1483: }


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

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

1491:    Input Parameters:
1492: +  snes - the SNES context
1493: -  ksp - the KSP context

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

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

1502:    Level: developer

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

1506: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1507: @*/
1508: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1509: {

1516:   PetscObjectReference((PetscObject)ksp);
1517:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1518:   snes->ksp = ksp;
1519:   return(0);
1520: }

1522: /* -----------------------------------------------------------*/
1523: /*@
1524:    SNESCreate - Creates a nonlinear solver context.

1526:    Collective on MPI_Comm

1528:    Input Parameters:
1529: .  comm - MPI communicator

1531:    Output Parameter:
1532: .  outsnes - the new SNES context

1534:    Options Database Keys:
1535: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1536:                and no preconditioning matrix
1537: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1538:                products, and a user-provided preconditioning matrix
1539:                as set by SNESSetJacobian()
1540: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1542:    Level: beginner

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

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

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

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

1557: @*/
1558: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1559: {
1561:   SNES           snes;
1562:   SNESKSPEW      *kctx;

1566:   *outsnes = NULL;
1567:   SNESInitializePackage();

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

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

1630:   snes->mf          = PETSC_FALSE;
1631:   snes->mf_operator = PETSC_FALSE;
1632:   snes->mf_version  = 1;

1634:   snes->numLinearSolveFailures = 0;
1635:   snes->maxLinearSolveFailures = 1;

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

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

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

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

1658:   *outsnes = snes;
1659:   return(0);
1660: }

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

1665:      Synopsis:
1666:      #include "petscsnes.h"
1667:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1669:      Input Parameters:
1670: +     snes - the SNES context
1671: .     x    - state at which to evaluate residual
1672: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1674:      Output Parameter:
1675: .     f  - vector to put residual (function value)

1677:    Level: intermediate

1679: .seealso:   SNESSetFunction(), SNESGetFunction()
1680: M*/

1682: /*@C
1683:    SNESSetFunction - Sets the function evaluation routine and function
1684:    vector for use by the SNES routines in solving systems of nonlinear
1685:    equations.

1687:    Logically Collective on SNES

1689:    Input Parameters:
1690: +  snes - the SNES context
1691: .  r - vector to store function value
1692: .  f - function evaluation routine; see SNESFunction for calling sequence details
1693: -  ctx - [optional] user-defined context for private data for the
1694:          function evaluation routine (may be NULL)

1696:    Notes:
1697:    The Newton-like methods typically solve linear systems of the form
1698: $      f'(x) x = -f(x),
1699:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1701:    Level: beginner

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

1705: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1706: @*/
1707: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1708: {
1710:   DM             dm;

1714:   if (r) {
1717:     PetscObjectReference((PetscObject)r);
1718:     VecDestroy(&snes->vec_func);

1720:     snes->vec_func = r;
1721:   }
1722:   SNESGetDM(snes,&dm);
1723:   DMSNESSetFunction(dm,f,ctx);
1724:   return(0);
1725: }


1728: /*@C
1729:    SNESSetInitialFunction - Sets the function vector to be used as the
1730:    function norm at the initialization of the method.  In some
1731:    instances, the user has precomputed the function before calling
1732:    SNESSolve.  This function allows one to avoid a redundant call
1733:    to SNESComputeFunction in that case.

1735:    Logically Collective on SNES

1737:    Input Parameters:
1738: +  snes - the SNES context
1739: -  f - vector to store function value

1741:    Notes:
1742:    This should not be modified during the solution procedure.

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

1746:    Level: developer

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

1750: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1751: @*/
1752: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1753: {
1755:   Vec            vec_func;

1761:   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1762:     snes->vec_func_init_set = PETSC_FALSE;
1763:     return(0);
1764:   }
1765:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1766:   VecCopy(f, vec_func);

1768:   snes->vec_func_init_set = PETSC_TRUE;
1769:   return(0);
1770: }

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

1776:    Logically Collective on SNES

1778:    Input Parameters:
1779: +  snes - the SNES context
1780: -  normschedule - the frequency of norm computation

1782:    Options Database Key:
1783: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1794:    Level: developer

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

1798: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1799: @*/
1800: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1801: {
1804:   snes->normschedule = normschedule;
1805:   return(0);
1806: }


1809: /*@
1810:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1811:    of the SNES method.

1813:    Logically Collective on SNES

1815:    Input Parameters:
1816: +  snes - the SNES context
1817: -  normschedule - the type of the norm used

1819:    Level: advanced

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

1823: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1824: @*/
1825: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1826: {
1829:   *normschedule = snes->normschedule;
1830:   return(0);
1831: }


1834: /*@
1835:   SNESSetFunctionNorm - Sets the last computed residual norm.

1837:   Logically Collective on SNES

1839:   Input Parameters:
1840: + snes - the SNES context

1842: - normschedule - the frequency of norm computation

1844:   Level: developer

1846: .keywords: SNES, nonlinear, set, function, norm, type
1847: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1848: @*/
1849: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1850: {
1853:   snes->norm = norm;
1854:   return(0);
1855: }

1857: /*@
1858:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1860:   Not Collective

1862:   Input Parameter:
1863: . snes - the SNES context

1865:   Output Parameter:
1866: . norm - the last computed residual norm

1868:   Level: developer

1870: .keywords: SNES, nonlinear, set, function, norm, type
1871: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1872: @*/
1873: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1874: {
1878:   *norm = snes->norm;
1879:   return(0);
1880: }

1882: /*@C
1883:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1884:    of the SNES method.

1886:    Logically Collective on SNES

1888:    Input Parameters:
1889: +  snes - the SNES context
1890: -  normschedule - the frequency of norm computation

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

1901:    Level: developer

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

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


1916: /*@C
1917:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1918:    of the SNES method.

1920:    Logically Collective on SNES

1922:    Input Parameters:
1923: +  snes - the SNES context
1924: -  normschedule - the type of the norm used

1926:    Level: advanced

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

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

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

1943:      Synopsis:
1944:      #include <petscsnes.h>
1945: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1947: +  X   - solution vector
1948: .  B   - RHS vector
1949: -  ctx - optional user-defined Gauss-Seidel context

1951:    Level: intermediate

1953: .seealso:   SNESSetNGS(), SNESGetNGS()
1954: M*/

1956: /*@C
1957:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1958:    use with composed nonlinear solvers.

1960:    Input Parameters:
1961: +  snes   - the SNES context
1962: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
1963: -  ctx    - [optional] user-defined context for private data for the
1964:             smoother evaluation routine (may be NULL)

1966:    Notes:
1967:    The NGS routines are used by the composed nonlinear solver to generate
1968:     a problem appropriate update to the solution, particularly FAS.

1970:    Level: intermediate

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

1974: .seealso: SNESGetFunction(), SNESComputeNGS()
1975: @*/
1976: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1977: {
1979:   DM             dm;

1983:   SNESGetDM(snes,&dm);
1984:   DMSNESSetNGS(dm,f,ctx);
1985:   return(0);
1986: }

1988: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1989: {
1991:   DM             dm;
1992:   DMSNES         sdm;

1995:   SNESGetDM(snes,&dm);
1996:   DMGetDMSNES(dm,&sdm);
1997:   /*  A(x)*x - b(x) */
1998:   if (sdm->ops->computepfunction) {
1999:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
2000:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");

2002:   if (sdm->ops->computepjacobian) {
2003:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
2004:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard matrix.");
2005:   VecScale(f,-1.0);
2006:   MatMultAdd(snes->jacobian,x,f,f);
2007:   return(0);
2008: }

2010: PETSC_EXTERN PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
2011: {
2013:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
2014:   return(0);
2015: }

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

2020:    Logically Collective on SNES

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

2032:    Notes:
2033:     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
2034:     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.

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

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

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

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

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

2050:    Level: intermediate

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

2054: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2055: @*/
2056: 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)
2057: {
2059:   DM             dm;

2063:   SNESGetDM(snes, &dm);
2064:   DMSNESSetPicard(dm,b,J,ctx);
2065:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2066:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2067:   return(0);
2068: }

2070: /*@C
2071:    SNESGetPicard - Returns the context for the Picard iteration

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

2075:    Input Parameter:
2076: .  snes - the SNES context

2078:    Output Parameter:
2079: +  r - the function (or NULL)
2080: .  f - the function (or NULL); see SNESFunction for calling sequence details
2081: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2082: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2083: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2084: -  ctx - the function context (or NULL)

2086:    Level: advanced

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

2090: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2091: @*/
2092: 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)
2093: {
2095:   DM             dm;

2099:   SNESGetFunction(snes,r,NULL,NULL);
2100:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2101:   SNESGetDM(snes,&dm);
2102:   DMSNESGetPicard(dm,f,J,ctx);
2103:   return(0);
2104: }

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

2109:    Logically Collective on SNES

2111:    Input Parameters:
2112: +  snes - the SNES context
2113: .  func - function evaluation routine
2114: -  ctx - [optional] user-defined context for private data for the
2115:          function evaluation routine (may be NULL)

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

2120: .  f - function vector
2121: -  ctx - optional user-defined function context

2123:    Level: intermediate

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

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

2138: /* --------------------------------------------------------------- */
2139: /*@C
2140:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2141:    it assumes a zero right hand side.

2143:    Logically Collective on SNES

2145:    Input Parameter:
2146: .  snes - the SNES context

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

2151:    Level: intermediate

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

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

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

2169:    Collective on SNES

2171:    Input Parameters:
2172: +  snes - the SNES context
2173: -  x - input vector

2175:    Output Parameter:
2176: .  y - function vector, as set by SNESSetFunction()

2178:    Notes:
2179:    SNESComputeFunction() is typically used within nonlinear solvers
2180:    implementations, so most users would not generally call this routine
2181:    themselves.

2183:    Level: developer

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

2187: .seealso: SNESSetFunction(), SNESGetFunction()
2188: @*/
2189: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2190: {
2192:   DM             dm;
2193:   DMSNES         sdm;

2201:   VecValidValues(x,2,PETSC_TRUE);

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

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

2237:    Collective on SNES

2239:    Input Parameters:
2240: +  snes - the SNES context
2241: .  x - input vector
2242: -  b - rhs vector

2244:    Output Parameter:
2245: .  x - new solution vector

2247:    Notes:
2248:    SNESComputeNGS() is typically used within composed nonlinear solver
2249:    implementations, so most users would not generally call this routine
2250:    themselves.

2252:    Level: developer

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

2256: .seealso: SNESSetNGS(), SNESComputeFunction()
2257: @*/
2258: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2259: {
2261:   DM             dm;
2262:   DMSNES         sdm;

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

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

2288:    Collective on SNES and Mat

2290:    Input Parameters:
2291: +  snes - the SNES context
2292: -  x - input vector

2294:    Output Parameters:
2295: +  A - Jacobian matrix
2296: -  B - optional preconditioning matrix

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


2314:    Notes:
2315:    Most users should not need to explicitly call this routine, as it
2316:    is used internally within the nonlinear solvers.

2318:    Level: developer

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

2322: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2323: @*/
2324: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2325: {
2327:   PetscBool      flag;
2328:   DM             dm;
2329:   DMSNES         sdm;
2330:   KSP            ksp;

2336:   VecValidValues(X,2,PETSC_TRUE);
2337:   SNESGetDM(snes,&dm);
2338:   DMGetDMSNES(dm,&sdm);

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

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

2344:   if (snes->lagjacobian == -2) {
2345:     snes->lagjacobian = -1;

2347:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2348:   } else if (snes->lagjacobian == -1) {
2349:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2350:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2351:     if (flag) {
2352:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2353:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2354:     }
2355:     return(0);
2356:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2357:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2358:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2359:     if (flag) {
2360:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2361:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2362:     }
2363:     return(0);
2364:   }
2365:   if (snes->npc && snes->npcside== PC_LEFT) {
2366:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2367:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2368:       return(0);
2369:   }

2371:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2372:   VecLockPush(X);
2373:   PetscStackPush("SNES user Jacobian function");
2374:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2375:   PetscStackPop;
2376:   VecLockPop(X);
2377:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2379:   /* the next line ensures that snes->ksp exists */
2380:   SNESGetKSP(snes,&ksp);
2381:   if (snes->lagpreconditioner == -2) {
2382:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2383:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2384:     snes->lagpreconditioner = -1;
2385:   } else if (snes->lagpreconditioner == -1) {
2386:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2387:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2388:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2389:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2390:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2391:   } else {
2392:     PetscInfo(snes,"Rebuilding preconditioner\n");
2393:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2394:   }

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

2471:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2472:       MatColoringCreate(Bfd,&coloring);
2473:       MatColoringSetType(coloring,MATCOLORINGSL);
2474:       MatColoringSetFromOptions(coloring);
2475:       MatColoringApply(coloring,&iscoloring);
2476:       MatColoringDestroy(&coloring);
2477:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2478:       MatFDColoringSetFromOptions(matfdcoloring);
2479:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2480:       ISColoringDestroy(&iscoloring);

2482:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2483:       SNESGetFunction(snes,NULL,&func,&funcctx);
2484:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2485:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2486:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2487:       MatFDColoringSetFromOptions(matfdcoloring);
2488:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2489:       MatFDColoringDestroy(&matfdcoloring);

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

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

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

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

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

2576:    Level: intermediate

2578: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2579: M*/

2581: /*@C
2582:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2583:    location to store the matrix.

2585:    Logically Collective on SNES and Mat

2587:    Input Parameters:
2588: +  snes - the SNES context
2589: .  Amat - the matrix that defines the (approximate) Jacobian
2590: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2591: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2592: -  ctx - [optional] user-defined context for private data for the
2593:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2595:    Notes:
2596:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2597:    each matrix.

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

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

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

2608:    Level: beginner

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

2612: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J, 
2613:           SNESSetPicard(), SNESJacobianFunction
2614: @*/
2615: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2616: {
2618:   DM             dm;

2626:   SNESGetDM(snes,&dm);
2627:   DMSNESSetJacobian(dm,J,ctx);
2628:   if (Amat) {
2629:     PetscObjectReference((PetscObject)Amat);
2630:     MatDestroy(&snes->jacobian);

2632:     snes->jacobian = Amat;
2633:   }
2634:   if (Pmat) {
2635:     PetscObjectReference((PetscObject)Pmat);
2636:     MatDestroy(&snes->jacobian_pre);

2638:     snes->jacobian_pre = Pmat;
2639:   }
2640:   return(0);
2641: }

2643: /*@C
2644:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2645:    provided context for evaluating the Jacobian.

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

2649:    Input Parameter:
2650: .  snes - the nonlinear solver context

2652:    Output Parameters:
2653: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2654: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2655: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2656: -  ctx - location to stash Jacobian ctx (or NULL)

2658:    Level: advanced

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

2670:   if (Amat) *Amat = snes->jacobian;
2671:   if (Pmat) *Pmat = snes->jacobian_pre;
2672:   SNESGetDM(snes,&dm);
2673:   DMGetDMSNES(dm,&sdm);
2674:   if (J) *J = sdm->ops->computejacobian;
2675:   if (ctx) *ctx = sdm->jacobianctx;
2676:   return(0);
2677: }

2679: /*@
2680:    SNESSetUp - Sets up the internal data structures for the later use
2681:    of a nonlinear solver.

2683:    Collective on SNES

2685:    Input Parameters:
2686: .  snes - the SNES context

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

2695:    Level: advanced

2697: .keywords: SNES, nonlinear, setup

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

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

2721:   if (!((PetscObject)snes)->type_name) {
2722:     SNESSetType(snes,SNESNEWTONLS);
2723:   }

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

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

2737:   if (!snes->ksp) {
2738:     SNESGetKSP(snes, &snes->ksp);
2739:   }

2741:   if (!snes->linesearch) {
2742:     SNESGetLineSearch(snes, &snes->linesearch);
2743:   }
2744:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2746:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2747:     snes->mf          = PETSC_TRUE;
2748:     snes->mf_operator = PETSC_FALSE;
2749:   }

2751:   if (snes->npc) {
2752:     /* copy the DM over */
2753:     SNESGetDM(snes,&dm);
2754:     SNESSetDM(snes->npc,dm);

2756:     SNESGetFunction(snes,&f,&func,&funcctx);
2757:     VecDuplicate(f,&fpc);
2758:     SNESSetFunction(snes->npc,fpc,func,funcctx);
2759:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2760:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
2761:     SNESGetApplicationContext(snes,&appctx);
2762:     SNESSetApplicationContext(snes->npc,appctx);
2763:     VecDestroy(&fpc);

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

2768:     /* default to 1 iteration */
2769:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
2770:     if (snes->npcside==PC_RIGHT) {
2771:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
2772:     } else {
2773:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
2774:     }
2775:     SNESSetFromOptions(snes->npc);

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

2793:   snes->jac_iter = 0;
2794:   snes->pre_iter = 0;

2796:   if (snes->ops->setup) {
2797:     (*snes->ops->setup)(snes);
2798:   }

2800:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2801:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2802:       SNESGetLineSearch(snes,&linesearch);
2803:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2804:     }
2805:   }

2807:   snes->setupcalled = PETSC_TRUE;
2808:   return(0);
2809: }

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

2814:    Collective on SNES

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

2819:    Level: intermediate

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

2823: .keywords: SNES, destroy

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

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

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

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

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

2861:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

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

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

2872:    Collective on SNES

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

2877:    Level: beginner

2879: .keywords: SNES, nonlinear, destroy

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

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

2892:   SNESReset((*snes));
2893:   SNESDestroy(&(*snes)->npc);

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

2899:   if ((*snes)->dm) {DMCoarsenHookRemove((*snes)->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,*snes);}
2900:   DMDestroy(&(*snes)->dm);
2901:   KSPDestroy(&(*snes)->ksp);
2902:   SNESLineSearchDestroy(&(*snes)->linesearch);

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

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

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

2922:    Logically Collective on SNES

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

2929:    Options Database Keys:
2930: .    -snes_lag_preconditioner <lag>

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

2937:    Level: intermediate

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

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

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

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

2958:    Logically Collective on SNES

2960:    Input Parameters:
2961: +  snes - the SNES context
2962: -  steps - the number of refinements to do, defaults to 0

2964:    Options Database Keys:
2965: .    -snes_grid_sequence <steps>

2967:    Level: intermediate

2969:    Notes:
2970:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2976: @*/
2977: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
2978: {
2982:   snes->gridsequence = steps;
2983:   return(0);
2984: }

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

2989:    Logically Collective on SNES

2991:    Input Parameter:
2992: .  snes - the SNES context

2994:    Output Parameter:
2995: .  steps - the number of refinements to do, defaults to 0

2997:    Options Database Keys:
2998: .    -snes_grid_sequence <steps>

3000:    Level: intermediate

3002:    Notes:
3003:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

3009: @*/
3010: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
3011: {
3014:   *steps = snes->gridsequence;
3015:   return(0);
3016: }

3018: /*@
3019:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3021:    Not Collective

3023:    Input Parameter:
3024: .  snes - the SNES context

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

3030:    Options Database Keys:
3031: .    -snes_lag_preconditioner <lag>

3033:    Notes:
3034:    The default is 1
3035:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3037:    Level: intermediate

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

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

3043: @*/
3044: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3045: {
3048:   *lag = snes->lagpreconditioner;
3049:   return(0);
3050: }

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

3056:    Logically Collective on SNES

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

3063:    Options Database Keys:
3064: .    -snes_lag_jacobian <lag>

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

3072:    Level: intermediate

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

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

3078: @*/
3079: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3080: {
3083:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3084:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3086:   snes->lagjacobian = lag;
3087:   return(0);
3088: }

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

3093:    Not Collective

3095:    Input Parameter:
3096: .  snes - the SNES context

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

3102:    Options Database Keys:
3103: .    -snes_lag_jacobian <lag>

3105:    Notes:
3106:    The default is 1
3107:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3109:    Level: intermediate

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

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

3115: @*/
3116: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3117: {
3120:   *lag = snes->lagjacobian;
3121:   return(0);
3122: }

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

3127:    Logically collective on SNES

3129:    Input Parameter:
3130: +  snes - the SNES context
3131: -   flg - jacobian lagging persists if true

3133:    Options Database Keys:
3134: .    -snes_lag_jacobian_persists <flg>

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

3140:    Level: developer

3142: .keywords: SNES, nonlinear, lag

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

3146: @*/
3147: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3148: {
3152:   snes->lagjac_persist = flg;
3153:   return(0);
3154: }

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

3159:    Logically Collective on SNES

3161:    Input Parameter:
3162: +  snes - the SNES context
3163: -   flg - preconditioner lagging persists if true

3165:    Options Database Keys:
3166: .    -snes_lag_jacobian_persists <flg>

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

3172:    Level: developer

3174: .keywords: SNES, nonlinear, lag

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

3178: @*/
3179: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3180: {
3184:   snes->lagpre_persist = flg;
3185:   return(0);
3186: }

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

3191:    Logically Collective on SNES

3193:    Input Parameters:
3194: +  snes - the SNES context
3195: -  force - PETSC_TRUE require at least one iteration

3197:    Options Database Keys:
3198: .    -snes_force_iteration <force> - Sets forcing an iteration

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

3203:    Level: intermediate

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

3207: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3208: @*/
3209: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3210: {
3213:   snes->forceiteration = force;
3214:   return(0);
3215: }


3218: /*@
3219:    SNESSetTolerances - Sets various parameters used in convergence tests.

3221:    Logically Collective on SNES

3223:    Input Parameters:
3224: +  snes - the SNES context
3225: .  abstol - absolute convergence tolerance
3226: .  rtol - relative convergence tolerance
3227: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3228: .  maxit - maximum number of iterations
3229: -  maxf - maximum number of function evaluations

3231:    Options Database Keys:
3232: +    -snes_atol <abstol> - Sets abstol
3233: .    -snes_rtol <rtol> - Sets rtol
3234: .    -snes_stol <stol> - Sets stol
3235: .    -snes_max_it <maxit> - Sets maxit
3236: -    -snes_max_funcs <maxf> - Sets maxf

3238:    Notes:
3239:    The default maximum number of iterations is 50.
3240:    The default maximum number of function evaluations is 1000.

3242:    Level: intermediate

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

3246: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3247: @*/
3248: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3249: {

3258:   if (abstol != PETSC_DEFAULT) {
3259:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3260:     snes->abstol = abstol;
3261:   }
3262:   if (rtol != PETSC_DEFAULT) {
3263:     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);
3264:     snes->rtol = rtol;
3265:   }
3266:   if (stol != PETSC_DEFAULT) {
3267:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3268:     snes->stol = stol;
3269:   }
3270:   if (maxit != PETSC_DEFAULT) {
3271:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3272:     snes->max_its = maxit;
3273:   }
3274:   if (maxf != PETSC_DEFAULT) {
3275:     if (maxf < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be non-negative",maxf);
3276:     snes->max_funcs = maxf;
3277:   }
3278:   snes->tolerancesset = PETSC_TRUE;
3279:   return(0);
3280: }

3282: /*@
3283:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3285:    Logically Collective on SNES

3287:    Input Parameters:
3288: +  snes - the SNES context
3289: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3291:    Options Database Keys:
3292: +    -snes_divergence_tolerance <divtol> - Sets divtol

3294:    Notes:
3295:    The default divergence tolerance is 1e4.

3297:    Level: intermediate

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

3301: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3302: @*/
3303: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3304: {

3309:   if (divtol != PETSC_DEFAULT) {
3310:     snes->divtol = divtol;
3311:   }
3312:   else {
3313:     snes->divtol = 1.0e4;
3314:   }
3315:   return(0);
3316: }

3318: /*@
3319:    SNESGetTolerances - Gets various parameters used in convergence tests.

3321:    Not Collective

3323:    Input Parameters:
3324: +  snes - the SNES context
3325: .  atol - absolute convergence tolerance
3326: .  rtol - relative convergence tolerance
3327: .  stol -  convergence tolerance in terms of the norm
3328:            of the change in the solution between steps
3329: .  maxit - maximum number of iterations
3330: -  maxf - maximum number of function evaluations

3332:    Notes:
3333:    The user can specify NULL for any parameter that is not needed.

3335:    Level: intermediate

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

3339: .seealso: SNESSetTolerances()
3340: @*/
3341: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3342: {
3345:   if (atol)  *atol  = snes->abstol;
3346:   if (rtol)  *rtol  = snes->rtol;
3347:   if (stol)  *stol  = snes->stol;
3348:   if (maxit) *maxit = snes->max_its;
3349:   if (maxf)  *maxf  = snes->max_funcs;
3350:   return(0);
3351: }

3353: /*@
3354:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3356:    Not Collective

3358:    Input Parameters:
3359: +  snes - the SNES context
3360: -  divtol - divergence tolerance

3362:    Level: intermediate

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

3366: .seealso: SNESSetDivergenceTolerance()
3367: @*/
3368: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3369: {
3372:   if (divtol) *divtol = snes->divtol;
3373:   return(0);
3374: }

3376: /*@
3377:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3379:    Logically Collective on SNES

3381:    Input Parameters:
3382: +  snes - the SNES context
3383: -  tol - tolerance

3385:    Options Database Key:
3386: .  -snes_trtol <tol> - Sets tol

3388:    Level: intermediate

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

3392: .seealso: SNESSetTolerances()
3393: @*/
3394: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3395: {
3399:   snes->deltatol = tol;
3400:   return(0);
3401: }

3403: /*
3404:    Duplicate the lg monitors for SNES from KSP; for some reason with
3405:    dynamic libraries things don't work under Sun4 if we just use
3406:    macros instead of functions
3407: */
3408: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3409: {

3414:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3415:   return(0);
3416: }

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

3423:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3424:   return(0);
3425: }

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

3429: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3430: {
3431:   PetscDrawLG      lg;
3432:   PetscErrorCode   ierr;
3433:   PetscReal        x,y,per;
3434:   PetscViewer      v = (PetscViewer)monctx;
3435:   static PetscReal prev; /* should be in the context */
3436:   PetscDraw        draw;

3440:   PetscViewerDrawGetDrawLG(v,0,&lg);
3441:   if (!n) {PetscDrawLGReset(lg);}
3442:   PetscDrawLGGetDraw(lg,&draw);
3443:   PetscDrawSetTitle(draw,"Residual norm");
3444:   x    = (PetscReal)n;
3445:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3446:   else y = -15.0;
3447:   PetscDrawLGAddPoint(lg,&x,&y);
3448:   if (n < 20 || !(n % 5) || snes->reason) {
3449:     PetscDrawLGDraw(lg);
3450:     PetscDrawLGSave(lg);
3451:   }

3453:   PetscViewerDrawGetDrawLG(v,1,&lg);
3454:   if (!n) {PetscDrawLGReset(lg);}
3455:   PetscDrawLGGetDraw(lg,&draw);
3456:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3457:    SNESMonitorRange_Private(snes,n,&per);
3458:   x    = (PetscReal)n;
3459:   y    = 100.0*per;
3460:   PetscDrawLGAddPoint(lg,&x,&y);
3461:   if (n < 20 || !(n % 5) || snes->reason) {
3462:     PetscDrawLGDraw(lg);
3463:     PetscDrawLGSave(lg);
3464:   }

3466:   PetscViewerDrawGetDrawLG(v,2,&lg);
3467:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3468:   PetscDrawLGGetDraw(lg,&draw);
3469:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3470:   x    = (PetscReal)n;
3471:   y    = (prev - rnorm)/prev;
3472:   PetscDrawLGAddPoint(lg,&x,&y);
3473:   if (n < 20 || !(n % 5) || snes->reason) {
3474:     PetscDrawLGDraw(lg);
3475:     PetscDrawLGSave(lg);
3476:   }

3478:   PetscViewerDrawGetDrawLG(v,3,&lg);
3479:   if (!n) {PetscDrawLGReset(lg);}
3480:   PetscDrawLGGetDraw(lg,&draw);
3481:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3482:   x    = (PetscReal)n;
3483:   y    = (prev - rnorm)/(prev*per);
3484:   if (n > 2) { /*skip initial crazy value */
3485:     PetscDrawLGAddPoint(lg,&x,&y);
3486:   }
3487:   if (n < 20 || !(n % 5) || snes->reason) {
3488:     PetscDrawLGDraw(lg);
3489:     PetscDrawLGSave(lg);
3490:   }
3491:   prev = rnorm;
3492:   return(0);
3493: }

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

3498:    Collective on SNES

3500:    Input Parameters:
3501: +  snes - nonlinear solver context obtained from SNESCreate()
3502: .  iter - iteration number
3503: -  rnorm - relative norm of the residual

3505:    Notes:
3506:    This routine is called by the SNES implementations.
3507:    It does not typically need to be called by the user.

3509:    Level: developer

3511: .seealso: SNESMonitorSet()
3512: @*/
3513: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3514: {
3516:   PetscInt       i,n = snes->numbermonitors;

3519:   VecLockPush(snes->vec_sol);
3520:   for (i=0; i<n; i++) {
3521:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3522:   }
3523:   VecLockPop(snes->vec_sol);
3524:   return(0);
3525: }

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

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

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

3536: +    snes - the SNES context
3537: .    its - iteration number
3538: .    norm - 2-norm function value (may be estimated)
3539: -    mctx - [optional] monitoring context

3541:    Level: advanced

3543: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3544: M*/

3546: /*@C
3547:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3548:    iteration of the nonlinear solver to display the iteration's
3549:    progress.

3551:    Logically Collective on SNES

3553:    Input Parameters:
3554: +  snes - the SNES context
3555: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3556: .  mctx - [optional] user-defined context for private data for the
3557:           monitor routine (use NULL if no context is desired)
3558: -  monitordestroy - [optional] routine that frees monitor context
3559:           (may be NULL)

3561:    Options Database Keys:
3562: +    -snes_monitor        - sets SNESMonitorDefault()
3563: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3564:                             uses SNESMonitorLGCreate()
3565: -    -snes_monitor_cancel - cancels all monitors that have
3566:                             been hardwired into a code by
3567:                             calls to SNESMonitorSet(), but
3568:                             does not cancel those set via
3569:                             the options database.

3571:    Notes:
3572:    Several different monitoring routines may be set by calling
3573:    SNESMonitorSet() multiple times; all will be called in the
3574:    order in which they were set.

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

3578:    Level: intermediate

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

3582: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3583: @*/
3584: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3585: {
3586:   PetscInt       i;
3588:   PetscBool      identical;

3592:   for (i=0; i<snes->numbermonitors;i++) {
3593:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3594:     if (identical) return(0);
3595:   }
3596:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3597:   snes->monitor[snes->numbermonitors]          = f;
3598:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3599:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3600:   return(0);
3601: }

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

3606:    Logically Collective on SNES

3608:    Input Parameters:
3609: .  snes - the SNES context

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

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

3619:    Level: intermediate

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

3623: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3624: @*/
3625: PetscErrorCode  SNESMonitorCancel(SNES snes)
3626: {
3628:   PetscInt       i;

3632:   for (i=0; i<snes->numbermonitors; i++) {
3633:     if (snes->monitordestroy[i]) {
3634:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3635:     }
3636:   }
3637:   snes->numbermonitors = 0;
3638:   return(0);
3639: }

3641: /*MC
3642:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3648: +    snes - the SNES context
3649: .    it - current iteration (0 is the first and is before any Newton step)
3650: .    cctx - [optional] convergence context
3651: .    reason - reason for convergence/divergence
3652: .    xnorm - 2-norm of current iterate
3653: .    gnorm - 2-norm of current step
3654: -    f - 2-norm of function

3656:    Level: intermediate

3658: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3659: M*/

3661: /*@C
3662:    SNESSetConvergenceTest - Sets the function that is to be used
3663:    to test for convergence of the nonlinear iterative solution.

3665:    Logically Collective on SNES

3667:    Input Parameters:
3668: +  snes - the SNES context
3669: .  SNESConvergenceTestFunction - routine to test for convergence
3670: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3671: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3673:    Level: advanced

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

3677: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3678: @*/
3679: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3680: {

3685:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3686:   if (snes->ops->convergeddestroy) {
3687:     (*snes->ops->convergeddestroy)(snes->cnvP);
3688:   }
3689:   snes->ops->converged        = SNESConvergenceTestFunction;
3690:   snes->ops->convergeddestroy = destroy;
3691:   snes->cnvP                  = cctx;
3692:   return(0);
3693: }

3695: /*@
3696:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3698:    Not Collective

3700:    Input Parameter:
3701: .  snes - the SNES context

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

3707:    Options Database:
3708: .   -snes_converged_reason - prints the reason to standard out

3710:    Level: intermediate

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

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

3716: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
3717: @*/
3718: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3719: {
3723:   *reason = snes->reason;
3724:   return(0);
3725: }

3727: /*@
3728:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3730:    Not Collective

3732:    Input Parameters:
3733: +  snes - the SNES context
3734: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
3735:             manual pages for the individual convergence tests for complete lists

3737:    Level: intermediate

3739: .keywords: SNES, nonlinear, set, convergence, test
3740: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
3741: @*/
3742: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
3743: {
3746:   snes->reason = reason;
3747:   return(0);
3748: }

3750: /*@
3751:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3753:    Logically Collective on SNES

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

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

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

3771:    Level: intermediate

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

3775: .seealso: SNESGetConvergenceHistory()

3777: @*/
3778: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3779: {

3786:   if (!a) {
3787:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3788:     PetscCalloc1(na,&a);
3789:     PetscCalloc1(na,&its);

3791:     snes->conv_malloc = PETSC_TRUE;
3792:   }
3793:   snes->conv_hist       = a;
3794:   snes->conv_hist_its   = its;
3795:   snes->conv_hist_max   = na;
3796:   snes->conv_hist_len   = 0;
3797:   snes->conv_hist_reset = reset;
3798:   return(0);
3799: }

3801: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3802: #include <engine.h>   /* MATLAB include file */
3803: #include <mex.h>      /* MATLAB include file */

3805: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3806: {
3807:   mxArray   *mat;
3808:   PetscInt  i;
3809:   PetscReal *ar;

3812:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3813:   ar  = (PetscReal*) mxGetData(mat);
3814:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3815:   PetscFunctionReturn(mat);
3816: }
3817: #endif

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

3822:    Not Collective

3824:    Input Parameter:
3825: .  snes - iterative context obtained from SNESCreate()

3827:    Output Parameters:
3828: .  a   - array to hold history
3829: .  its - integer array holds the number of linear iterations (or
3830:          negative if not converged) for each solve.
3831: -  na  - size of a and its

3833:    Notes:
3834:     The calling sequence for this routine in Fortran is
3835: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

3841:    Level: intermediate

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

3845: .seealso: SNESSetConvergencHistory()

3847: @*/
3848: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
3849: {
3852:   if (a)   *a   = snes->conv_hist;
3853:   if (its) *its = snes->conv_hist_its;
3854:   if (na)  *na  = snes->conv_hist_len;
3855:   return(0);
3856: }

3858: /*@C
3859:   SNESSetUpdate - Sets the general-purpose update function called
3860:   at the beginning of every iteration of the nonlinear solve. Specifically
3861:   it is called just before the Jacobian is "evaluated".

3863:   Logically Collective on SNES

3865:   Input Parameters:
3866: . snes - The nonlinear solver context
3867: . func - The function

3869:   Calling sequence of func:
3870: . func (SNES snes, PetscInt step);

3872: . step - The current step of the iteration

3874:   Level: advanced

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

3879: .keywords: SNES, update

3881: .seealso SNESSetJacobian(), SNESSolve()
3882: @*/
3883: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
3884: {
3887:   snes->ops->update = func;
3888:   return(0);
3889: }

3891: /*
3892:    SNESScaleStep_Private - Scales a step so that its length is less than the
3893:    positive parameter delta.

3895:     Input Parameters:
3896: +   snes - the SNES context
3897: .   y - approximate solution of linear system
3898: .   fnorm - 2-norm of current function
3899: -   delta - trust region size

3901:     Output Parameters:
3902: +   gpnorm - predicted function norm at the new point, assuming local
3903:     linearization.  The value is zero if the step lies within the trust
3904:     region, and exceeds zero otherwise.
3905: -   ynorm - 2-norm of the step

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

3911: .keywords: SNES, nonlinear, scale, step
3912: */
3913: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
3914: {
3915:   PetscReal      nrm;
3916:   PetscScalar    cnorm;


3924:   VecNorm(y,NORM_2,&nrm);
3925:   if (nrm > *delta) {
3926:     nrm     = *delta/nrm;
3927:     *gpnorm = (1.0 - nrm)*(*fnorm);
3928:     cnorm   = nrm;
3929:     VecScale(y,cnorm);
3930:     *ynorm  = *delta;
3931:   } else {
3932:     *gpnorm = 0.0;
3933:     *ynorm  = nrm;
3934:   }
3935:   return(0);
3936: }

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

3941:    Collective on SNES

3943:    Parameter:
3944: +  snes - iterative context obtained from SNESCreate()
3945: -  viewer - the viewer to display the reason


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

3951:    Level: beginner

3953: .keywords: SNES, solve, linear system

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

3957: @*/
3958: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
3959: {
3960:   PetscViewerFormat format;
3961:   PetscBool         isAscii;
3962:   PetscErrorCode    ierr;

3965:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
3966:   if (isAscii) {
3967:     PetscViewerGetFormat(viewer, &format);
3968:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
3969:     if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
3970:       DM                dm;
3971:       Vec               u;
3972:       PetscDS           prob;
3973:       PetscInt          Nf, f;
3974:       PetscErrorCode (**exactFuncs)(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
3975:       PetscReal         error;

3977:       SNESGetDM(snes, &dm);
3978:       SNESGetSolution(snes, &u);
3979:       DMGetDS(dm, &prob);
3980:       PetscDSGetNumFields(prob, &Nf);
3981:       PetscMalloc1(Nf, &exactFuncs);
3982:       for (f = 0; f < Nf; ++f) {PetscDSGetExactSolution(prob, f, &exactFuncs[f]);}
3983:       DMComputeL2Diff(dm, 0.0, exactFuncs, NULL, u, &error);
3984:       PetscFree(exactFuncs);
3985:       if (error < 1.0e-11) {PetscViewerASCIIPrintf(viewer, "L_2 Error: < 1.0e-11\n");}
3986:       else                 {PetscViewerASCIIPrintf(viewer, "L_2 Error: %g\n", error);}
3987:     }
3988:     if (snes->reason > 0) {
3989:       if (((PetscObject) snes)->prefix) {
3990:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3991:       } else {
3992:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3993:       }
3994:     } else {
3995:       if (((PetscObject) snes)->prefix) {
3996:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3997:       } else {
3998:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3999:       }
4000:     }
4001:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
4002:   }
4003:   return(0);
4004: }

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

4009:   Collective on SNES

4011:   Input Parameters:
4012: . snes   - the SNES object

4014:   Level: intermediate

4016: @*/
4017: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
4018: {
4019:   PetscErrorCode    ierr;
4020:   PetscViewer       viewer;
4021:   PetscBool         flg;
4022:   static PetscBool  incall = PETSC_FALSE;
4023:   PetscViewerFormat format;

4026:   if (incall) return(0);
4027:   incall = PETSC_TRUE;
4028:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
4029:   if (flg) {
4030:     PetscViewerPushFormat(viewer,format);
4031:     SNESReasonView(snes,viewer);
4032:     PetscViewerPopFormat(viewer);
4033:     PetscViewerDestroy(&viewer);
4034:   }
4035:   incall = PETSC_FALSE;
4036:   return(0);
4037: }

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

4043:    Collective on SNES

4045:    Input Parameters:
4046: +  snes - the SNES context
4047: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4048: -  x - the solution vector.

4050:    Notes:
4051:    The user should initialize the vector,x, with the initial guess
4052:    for the nonlinear solve prior to calling SNESSolve.  In particular,
4053:    to employ an initial guess of zero, the user should explicitly set
4054:    this vector to zero by calling VecSet().

4056:    Level: beginner

4058: .keywords: SNES, nonlinear, solve

4060: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4061: @*/
4062: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4063: {
4064:   PetscErrorCode    ierr;
4065:   PetscBool         flg;
4066:   PetscInt          grid;
4067:   Vec               xcreated = NULL;
4068:   DM                dm;


4077:   /* High level operations using the nonlinear solver */
4078:   {
4079:     PetscViewer       viewer;
4080:     PetscViewerFormat format;
4081:     PetscInt          num;
4082:     PetscBool         flg;
4083:     static PetscBool  incall = PETSC_FALSE;

4085:     if (!incall) {
4086:       /* Estimate the convergence rate of the discretization */
4087:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes), ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4088:       if (flg) {
4089:         PetscConvEst conv;
4090:         PetscReal    alpha; /* Convergence rate of the solution error in the L_2 norm */

4092:         incall = PETSC_TRUE;
4093:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4094:         PetscConvEstSetSolver(conv, snes);
4095:         PetscConvEstSetFromOptions(conv);
4096:         PetscConvEstSetUp(conv);
4097:         PetscConvEstGetConvRate(conv, &alpha);
4098:         PetscViewerPushFormat(viewer, format);
4099:         PetscConvEstRateView(conv, alpha, viewer);
4100:         PetscViewerPopFormat(viewer);
4101:         PetscViewerDestroy(&viewer);
4102:         PetscConvEstDestroy(&conv);
4103:         incall = PETSC_FALSE;
4104:       }
4105:       /* Adaptively refine the initial grid */
4106:       flg  = PETSC_FALSE;
4107:       PetscOptionsGetBool(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_initial", &flg, NULL);
4108:       if (flg) {
4109:         DMAdaptor adaptor;

4111:         incall = PETSC_TRUE;
4112:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4113:         DMAdaptorSetSolver(adaptor, snes);
4114:         DMAdaptorSetFromOptions(adaptor);
4115:         DMAdaptorSetUp(adaptor);
4116:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_INITIAL, &dm, &x);
4117:         DMAdaptorDestroy(&adaptor);
4118:         incall = PETSC_FALSE;
4119:       }
4120:       /* Use grid sequencing to adapt */
4121:       num  = 0;
4122:       PetscOptionsGetInt(NULL, ((PetscObject) snes)->prefix, "-snes_adapt_sequence", &num, NULL);
4123:       if (num) {
4124:         DMAdaptor adaptor;

4126:         incall = PETSC_TRUE;
4127:         DMAdaptorCreate(PETSC_COMM_WORLD, &adaptor);
4128:         DMAdaptorSetSolver(adaptor, snes);
4129:         DMAdaptorSetSequenceLength(adaptor, num);
4130:         DMAdaptorSetFromOptions(adaptor);
4131:         DMAdaptorSetUp(adaptor);
4132:         DMAdaptorAdapt(adaptor, x, DM_ADAPTATION_SEQUENTIAL, &dm, &x);
4133:         DMAdaptorDestroy(&adaptor);
4134:         incall = PETSC_FALSE;
4135:       }
4136:     }
4137:   }
4138:   if (!x) {
4139:     SNESGetDM(snes,&dm);
4140:     DMCreateGlobalVector(dm,&xcreated);
4141:     x    = xcreated;
4142:   }
4143:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4148:     /* set solution vector */
4149:     if (!grid) {PetscObjectReference((PetscObject)x);}
4150:     VecDestroy(&snes->vec_sol);
4151:     snes->vec_sol = x;
4152:     SNESGetDM(snes,&dm);

4154:     /* set affine vector if provided */
4155:     if (b) { PetscObjectReference((PetscObject)b); }
4156:     VecDestroy(&snes->vec_rhs);
4157:     snes->vec_rhs = b;

4159:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4160:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4161:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4162:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4163:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4164:     }
4165:     DMShellSetGlobalVector(dm,snes->vec_sol);
4166:     SNESSetUp(snes);

4168:     if (!grid) {
4169:       if (snes->ops->computeinitialguess) {
4170:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4171:       }
4172:     }

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

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

4183:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4184:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4190:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4191:     if (snes->reason < 0) break;
4192:     if (grid <  snes->gridsequence) {
4193:       DM  fine;
4194:       Vec xnew;
4195:       Mat interp;

4197:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4198:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4199:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4200:       DMCreateGlobalVector(fine,&xnew);
4201:       MatInterpolate(interp,x,xnew);
4202:       DMInterpolate(snes->dm,interp,fine);
4203:       MatDestroy(&interp);
4204:       x    = xnew;

4206:       SNESReset(snes);
4207:       SNESSetDM(snes,fine);
4208:       DMDestroy(&fine);
4209:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4210:     }
4211:   }
4212:   SNESViewFromOptions(snes,NULL,"-snes_view");
4213:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4215:   VecDestroy(&xcreated);
4216:   PetscObjectSAWsBlock((PetscObject)snes);
4217:   return(0);
4218: }

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

4222: /*@C
4223:    SNESSetType - Sets the method for the nonlinear solver.

4225:    Collective on SNES

4227:    Input Parameters:
4228: +  snes - the SNES context
4229: -  type - a known method

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

4235:    Notes:
4236:    See "petsc/include/petscsnes.h" for available methods (for instance)
4237: +    SNESNEWTONLS - Newton's method with line search
4238:      (systems of nonlinear equations)
4239: .    SNESNEWTONTR - Newton's method with trust region
4240:      (systems of nonlinear equations)

4242:   Normally, it is best to use the SNESSetFromOptions() command and then
4243:   set the SNES solver type from the options database rather than by using
4244:   this routine.  Using the options database provides the user with
4245:   maximum flexibility in evaluating the many nonlinear solvers.
4246:   The SNESSetType() routine is provided for those situations where it
4247:   is necessary to set the nonlinear solver independently of the command
4248:   line or options database.  This might be the case, for example, when
4249:   the choice of solver changes during the execution of the program,
4250:   and the user's application is taking responsibility for choosing the
4251:   appropriate method.

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

4256:   Level: intermediate

4258: .keywords: SNES, set, type

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

4262: @*/
4263: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4264: {
4265:   PetscErrorCode ierr,(*r)(SNES);
4266:   PetscBool      match;


4272:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4273:   if (match) return(0);

4275:    PetscFunctionListFind(SNESList,type,&r);
4276:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4277:   /* Destroy the previous private SNES context */
4278:   if (snes->ops->destroy) {
4279:     (*(snes)->ops->destroy)(snes);
4280:     snes->ops->destroy = NULL;
4281:   }
4282:   /* Reinitialize function pointers in SNESOps structure */
4283:   snes->ops->setup          = 0;
4284:   snes->ops->solve          = 0;
4285:   snes->ops->view           = 0;
4286:   snes->ops->setfromoptions = 0;
4287:   snes->ops->destroy        = 0;
4288:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4289:   snes->setupcalled = PETSC_FALSE;

4291:   PetscObjectChangeTypeName((PetscObject)snes,type);
4292:   (*r)(snes);
4293:   return(0);
4294: }

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

4299:    Not Collective

4301:    Input Parameter:
4302: .  snes - nonlinear solver context

4304:    Output Parameter:
4305: .  type - SNES method (a character string)

4307:    Level: intermediate

4309: .keywords: SNES, nonlinear, get, type, name
4310: @*/
4311: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4312: {
4316:   *type = ((PetscObject)snes)->type_name;
4317:   return(0);
4318: }

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

4323:   Logically Collective on SNES and Vec

4325:   Input Parameters:
4326: + snes - the SNES context obtained from SNESCreate()
4327: - u    - the solution vector

4329:   Level: beginner

4331: .keywords: SNES, set, solution
4332: @*/
4333: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4334: {
4335:   DM             dm;

4341:   PetscObjectReference((PetscObject) u);
4342:   VecDestroy(&snes->vec_sol);

4344:   snes->vec_sol = u;

4346:   SNESGetDM(snes, &dm);
4347:   DMShellSetGlobalVector(dm, u);
4348:   return(0);
4349: }

4351: /*@
4352:    SNESGetSolution - Returns the vector where the approximate solution is
4353:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4357:    Input Parameter:
4358: .  snes - the SNES context

4360:    Output Parameter:
4361: .  x - the solution

4363:    Level: intermediate

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

4367: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4368: @*/
4369: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4370: {
4374:   *x = snes->vec_sol;
4375:   return(0);
4376: }

4378: /*@
4379:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4380:    stored.

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

4384:    Input Parameter:
4385: .  snes - the SNES context

4387:    Output Parameter:
4388: .  x - the solution update

4390:    Level: advanced

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

4394: .seealso: SNESGetSolution(), SNESGetFunction()
4395: @*/
4396: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4397: {
4401:   *x = snes->vec_sol_update;
4402:   return(0);
4403: }

4405: /*@C
4406:    SNESGetFunction - Returns the vector where the function is stored.

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

4410:    Input Parameter:
4411: .  snes - the SNES context

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

4418:    Level: advanced

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

4422: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4423: @*/
4424: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4425: {
4427:   DM             dm;

4431:   if (r) {
4432:     if (!snes->vec_func) {
4433:       if (snes->vec_rhs) {
4434:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4435:       } else if (snes->vec_sol) {
4436:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4437:       } else if (snes->dm) {
4438:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4439:       }
4440:     }
4441:     *r = snes->vec_func;
4442:   }
4443:   SNESGetDM(snes,&dm);
4444:   DMSNESGetFunction(dm,f,ctx);
4445:   return(0);
4446: }

4448: /*@C
4449:    SNESGetNGS - Returns the NGS function and context.

4451:    Input Parameter:
4452: .  snes - the SNES context

4454:    Output Parameter:
4455: +  f - the function (or NULL) see SNESNGSFunction for details
4456: -  ctx    - the function context (or NULL)

4458:    Level: advanced

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

4462: .seealso: SNESSetNGS(), SNESGetFunction()
4463: @*/

4465: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4466: {
4468:   DM             dm;

4472:   SNESGetDM(snes,&dm);
4473:   DMSNESGetNGS(dm,f,ctx);
4474:   return(0);
4475: }

4477: /*@C
4478:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4479:    SNES options in the database.

4481:    Logically Collective on SNES

4483:    Input Parameter:
4484: +  snes - the SNES context
4485: -  prefix - the prefix to prepend to all option names

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

4491:    Level: advanced

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

4495: .seealso: SNESSetFromOptions()
4496: @*/
4497: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4498: {

4503:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4504:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4505:   if (snes->linesearch) {
4506:     SNESGetLineSearch(snes,&snes->linesearch);
4507:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4508:   }
4509:   KSPSetOptionsPrefix(snes->ksp,prefix);
4510:   return(0);
4511: }

4513: /*@C
4514:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4515:    SNES options in the database.

4517:    Logically Collective on SNES

4519:    Input Parameters:
4520: +  snes - the SNES context
4521: -  prefix - the prefix to prepend to all option names

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

4527:    Level: advanced

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

4531: .seealso: SNESGetOptionsPrefix()
4532: @*/
4533: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4534: {

4539:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4540:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4541:   if (snes->linesearch) {
4542:     SNESGetLineSearch(snes,&snes->linesearch);
4543:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4544:   }
4545:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4546:   return(0);
4547: }

4549: /*@C
4550:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4551:    SNES options in the database.

4553:    Not Collective

4555:    Input Parameter:
4556: .  snes - the SNES context

4558:    Output Parameter:
4559: .  prefix - pointer to the prefix string used

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

4564:    Level: advanced

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

4568: .seealso: SNESAppendOptionsPrefix()
4569: @*/
4570: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4571: {

4576:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4577:   return(0);
4578: }


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

4584:    Not collective

4586:    Input Parameters:
4587: +  name_solver - name of a new user-defined solver
4588: -  routine_create - routine to create method context

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

4593:    Sample usage:
4594: .vb
4595:    SNESRegister("my_solver",MySolverCreate);
4596: .ve

4598:    Then, your solver can be chosen with the procedural interface via
4599: $     SNESSetType(snes,"my_solver")
4600:    or at runtime via the option
4601: $     -snes_type my_solver

4603:    Level: advanced

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

4607: .keywords: SNES, nonlinear, register

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

4611:   Level: advanced
4612: @*/
4613: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4614: {

4618:   PetscFunctionListAdd(&SNESList,sname,function);
4619:   return(0);
4620: }

4622: PetscErrorCode  SNESTestLocalMin(SNES snes)
4623: {
4625:   PetscInt       N,i,j;
4626:   Vec            u,uh,fh;
4627:   PetscScalar    value;
4628:   PetscReal      norm;

4631:   SNESGetSolution(snes,&u);
4632:   VecDuplicate(u,&uh);
4633:   VecDuplicate(u,&fh);

4635:   /* currently only works for sequential */
4636:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4637:   VecGetSize(u,&N);
4638:   for (i=0; i<N; i++) {
4639:     VecCopy(u,uh);
4640:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4641:     for (j=-10; j<11; j++) {
4642:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4643:       VecSetValue(uh,i,value,ADD_VALUES);
4644:       SNESComputeFunction(snes,uh,fh);
4645:       VecNorm(fh,NORM_2,&norm);
4646:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4647:       value = -value;
4648:       VecSetValue(uh,i,value,ADD_VALUES);
4649:     }
4650:   }
4651:   VecDestroy(&uh);
4652:   VecDestroy(&fh);
4653:   return(0);
4654: }

4656: /*@
4657:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4658:    computing relative tolerance for linear solvers within an inexact
4659:    Newton method.

4661:    Logically Collective on SNES

4663:    Input Parameters:
4664: +  snes - SNES context
4665: -  flag - PETSC_TRUE or PETSC_FALSE

4667:     Options Database:
4668: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4669: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4670: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4671: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4672: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4673: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4674: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4675: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4677:    Notes:
4678:    Currently, the default is to use a constant relative tolerance for
4679:    the inner linear solvers.  Alternatively, one can use the
4680:    Eisenstat-Walker method, where the relative convergence tolerance
4681:    is reset at each Newton iteration according progress of the nonlinear
4682:    solver.

4684:    Level: advanced

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

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

4692: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4693: @*/
4694: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4695: {
4699:   snes->ksp_ewconv = flag;
4700:   return(0);
4701: }

4703: /*@
4704:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4705:    for computing relative tolerance for linear solvers within an
4706:    inexact Newton method.

4708:    Not Collective

4710:    Input Parameter:
4711: .  snes - SNES context

4713:    Output Parameter:
4714: .  flag - PETSC_TRUE or PETSC_FALSE

4716:    Notes:
4717:    Currently, the default is to use a constant relative tolerance for
4718:    the inner linear solvers.  Alternatively, one can use the
4719:    Eisenstat-Walker method, where the relative convergence tolerance
4720:    is reset at each Newton iteration according progress of the nonlinear
4721:    solver.

4723:    Level: advanced

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

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

4731: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4732: @*/
4733: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4734: {
4738:   *flag = snes->ksp_ewconv;
4739:   return(0);
4740: }

4742: /*@
4743:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4744:    convergence criteria for the linear solvers within an inexact
4745:    Newton method.

4747:    Logically Collective on SNES

4749:    Input Parameters:
4750: +    snes - SNES context
4751: .    version - version 1, 2 (default is 2) or 3
4752: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4753: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4754: .    gamma - multiplicative factor for version 2 rtol computation
4755:              (0 <= gamma2 <= 1)
4756: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4757: .    alpha2 - power for safeguard
4758: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4760:    Note:
4761:    Version 3 was contributed by Luis Chacon, June 2006.

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

4765:    Level: advanced

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

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

4774: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4775: @*/
4776: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4777: {
4778:   SNESKSPEW *kctx;

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

4792:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4793:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4794:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4795:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4796:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4797:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4798:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4800:   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);
4801:   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);
4802:   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);
4803:   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);
4804:   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);
4805:   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);
4806:   return(0);
4807: }

4809: /*@
4810:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4811:    convergence criteria for the linear solvers within an inexact
4812:    Newton method.

4814:    Not Collective

4816:    Input Parameters:
4817:      snes - SNES context

4819:    Output Parameters:
4820: +    version - version 1, 2 (default is 2) or 3
4821: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4822: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4823: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
4824: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4825: .    alpha2 - power for safeguard
4826: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4828:    Level: advanced

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

4832: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
4833: @*/
4834: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
4835: {
4836:   SNESKSPEW *kctx;

4840:   kctx = (SNESKSPEW*)snes->kspconvctx;
4841:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
4842:   if (version)   *version   = kctx->version;
4843:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
4844:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
4845:   if (gamma)     *gamma     = kctx->gamma;
4846:   if (alpha)     *alpha     = kctx->alpha;
4847:   if (alpha2)    *alpha2    = kctx->alpha2;
4848:   if (threshold) *threshold = kctx->threshold;
4849:   return(0);
4850: }

4852:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4853: {
4855:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4856:   PetscReal      rtol  = PETSC_DEFAULT,stol;

4859:   if (!snes->ksp_ewconv) return(0);
4860:   if (!snes->iter) {
4861:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
4862:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
4863:   }
4864:   else {
4865:     if (kctx->version == 1) {
4866:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
4867:       if (rtol < 0.0) rtol = -rtol;
4868:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
4869:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4870:     } else if (kctx->version == 2) {
4871:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4872:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
4873:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4874:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
4875:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4876:       /* safeguard: avoid sharp decrease of rtol */
4877:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
4878:       stol = PetscMax(rtol,stol);
4879:       rtol = PetscMin(kctx->rtol_0,stol);
4880:       /* safeguard: avoid oversolving */
4881:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
4882:       stol = PetscMax(rtol,stol);
4883:       rtol = PetscMin(kctx->rtol_0,stol);
4884:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
4885:   }
4886:   /* safeguard: avoid rtol greater than one */
4887:   rtol = PetscMin(rtol,kctx->rtol_max);
4888:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
4889:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
4890:   return(0);
4891: }

4893: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4894: {
4896:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4897:   PCSide         pcside;
4898:   Vec            lres;

4901:   if (!snes->ksp_ewconv) return(0);
4902:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
4903:   kctx->norm_last = snes->norm;
4904:   if (kctx->version == 1) {
4905:     PC        pc;
4906:     PetscBool isNone;

4908:     KSPGetPC(ksp, &pc);
4909:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
4910:     KSPGetPCSide(ksp,&pcside);
4911:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
4912:       /* KSP residual is true linear residual */
4913:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
4914:     } else {
4915:       /* KSP residual is preconditioned residual */
4916:       /* compute true linear residual norm */
4917:       VecDuplicate(b,&lres);
4918:       MatMult(snes->jacobian,x,lres);
4919:       VecAYPX(lres,-1.0,b);
4920:       VecNorm(lres,NORM_2,&kctx->lresid_last);
4921:       VecDestroy(&lres);
4922:     }
4923:   }
4924:   return(0);
4925: }

4927: /*@
4928:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

4932:    Input Parameter:
4933: .  snes - the SNES context

4935:    Output Parameter:
4936: .  ksp - the KSP context

4938:    Notes:
4939:    The user can then directly manipulate the KSP context to set various
4940:    options, etc.  Likewise, the user can then extract and manipulate the
4941:    PC contexts as well.

4943:    Level: beginner

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

4947: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
4948: @*/
4949: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
4950: {


4957:   if (!snes->ksp) {
4958:     PetscBool monitor = PETSC_FALSE;

4960:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
4961:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
4962:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

4967:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
4968:     if (monitor) {
4969:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
4970:     }
4971:     monitor = PETSC_FALSE;
4972:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
4973:     if (monitor) {
4974:       PetscObject *objs;
4975:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
4976:       objs[0] = (PetscObject) snes;
4977:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
4978:     }
4979:   }
4980:   *ksp = snes->ksp;
4981:   return(0);
4982: }


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

4989:    Logically Collective on SNES

4991:    Input Parameters:
4992: +  snes - the nonlinear solver context
4993: -  dm - the dm, cannot be NULL

4995:    Level: intermediate

4997: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
4998: @*/
4999: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
5000: {
5002:   KSP            ksp;
5003:   DMSNES         sdm;

5008:   PetscObjectReference((PetscObject)dm);
5009:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
5010:     if (snes->dm->dmsnes && !dm->dmsnes) {
5011:       DMCopyDMSNES(snes->dm,dm);
5012:       DMGetDMSNES(snes->dm,&sdm);
5013:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
5014:     }
5015:     DMCoarsenHookRemove(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
5016:     DMDestroy(&snes->dm);
5017:   }
5018:   snes->dm     = dm;
5019:   snes->dmAuto = PETSC_FALSE;

5021:   SNESGetKSP(snes,&ksp);
5022:   KSPSetDM(ksp,dm);
5023:   KSPSetDMActive(ksp,PETSC_FALSE);
5024:   if (snes->npc) {
5025:     SNESSetDM(snes->npc, snes->dm);
5026:     SNESSetNPCSide(snes,snes->npcside);
5027:   }
5028:   return(0);
5029: }

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

5034:    Not Collective but DM obtained is parallel on SNES

5036:    Input Parameter:
5037: . snes - the preconditioner context

5039:    Output Parameter:
5040: .  dm - the dm

5042:    Level: intermediate

5044: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
5045: @*/
5046: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
5047: {

5052:   if (!snes->dm) {
5053:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
5054:     snes->dmAuto = PETSC_TRUE;
5055:   }
5056:   *dm = snes->dm;
5057:   return(0);
5058: }

5060: /*@
5061:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5063:   Collective on SNES

5065:   Input Parameters:
5066: + snes - iterative context obtained from SNESCreate()
5067: - pc   - the preconditioner object

5069:   Notes:
5070:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5071:   to configure it using the API).

5073:   Level: developer

5075: .keywords: SNES, set, precondition
5076: .seealso: SNESGetNPC(), SNESHasNPC()
5077: @*/
5078: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5079: {

5086:   PetscObjectReference((PetscObject) pc);
5087:   SNESDestroy(&snes->npc);
5088:   snes->npc = pc;
5089:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5090:   return(0);
5091: }

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

5096:   Not Collective

5098:   Input Parameter:
5099: . snes - iterative context obtained from SNESCreate()

5101:   Output Parameter:
5102: . pc - preconditioner context

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

5106:   Level: developer

5108: .keywords: SNES, get, preconditioner
5109: .seealso: SNESSetNPC(), SNESHasNPC()
5110: @*/
5111: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5112: {
5114:   const char     *optionsprefix;

5119:   if (!snes->npc) {
5120:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5121:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5122:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5123:     SNESGetOptionsPrefix(snes,&optionsprefix);
5124:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5125:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5126:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5127:   }
5128:   *pc = snes->npc;
5129:   return(0);
5130: }

5132: /*@
5133:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5135:   Not Collective

5137:   Input Parameter:
5138: . snes - iterative context obtained from SNESCreate()

5140:   Output Parameter:
5141: . has_npc - whether the SNES has an NPC or not

5143:   Level: developer

5145: .keywords: SNES, has, preconditioner
5146: .seealso: SNESSetNPC(), SNESGetNPC()
5147: @*/
5148: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5149: {
5152:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5153:   return(0);
5154: }

5156: /*@
5157:     SNESSetNPCSide - Sets the preconditioning side.

5159:     Logically Collective on SNES

5161:     Input Parameter:
5162: .   snes - iterative context obtained from SNESCreate()

5164:     Output Parameter:
5165: .   side - the preconditioning side, where side is one of
5166: .vb
5167:       PC_LEFT - left preconditioning
5168:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5169: .ve

5171:     Options Database Keys:
5172: .   -snes_pc_side <right,left>

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

5176:     Level: intermediate

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

5180: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5181: @*/
5182: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5183: {
5187:   snes->npcside= side;
5188:   return(0);
5189: }

5191: /*@
5192:     SNESGetNPCSide - Gets the preconditioning side.

5194:     Not Collective

5196:     Input Parameter:
5197: .   snes - iterative context obtained from SNESCreate()

5199:     Output Parameter:
5200: .   side - the preconditioning side, where side is one of
5201: .vb
5202:       PC_LEFT - left preconditioning
5203:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5204: .ve

5206:     Level: intermediate

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

5210: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5211: @*/
5212: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5213: {
5217:   *side = snes->npcside;
5218:   return(0);
5219: }

5221: /*@
5222:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5224:   Collective on SNES

5226:   Input Parameters:
5227: + snes - iterative context obtained from SNESCreate()
5228: - linesearch   - the linesearch object

5230:   Notes:
5231:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5232:   to configure it using the API).

5234:   Level: developer

5236: .keywords: SNES, set, linesearch
5237: .seealso: SNESGetLineSearch()
5238: @*/
5239: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5240: {

5247:   PetscObjectReference((PetscObject) linesearch);
5248:   SNESLineSearchDestroy(&snes->linesearch);

5250:   snes->linesearch = linesearch;

5252:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5253:   return(0);
5254: }

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

5260:   Not Collective

5262:   Input Parameter:
5263: . snes - iterative context obtained from SNESCreate()

5265:   Output Parameter:
5266: . linesearch - linesearch context

5268:   Level: beginner

5270: .keywords: SNES, get, linesearch
5271: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5272: @*/
5273: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5274: {
5276:   const char     *optionsprefix;

5281:   if (!snes->linesearch) {
5282:     SNESGetOptionsPrefix(snes, &optionsprefix);
5283:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5284:     SNESLineSearchSetSNES(snes->linesearch, snes);
5285:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5286:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5287:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5288:   }
5289:   *linesearch = snes->linesearch;
5290:   return(0);
5291: }

5293: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5294: #include <mex.h>

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

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

5301:    Collective on SNES

5303:    Input Parameters:
5304: +  snes - the SNES context
5305: -  x - input vector

5307:    Output Parameter:
5308: .  y - function vector, as set by SNESSetFunction()

5310:    Notes:
5311:    SNESComputeFunction() is typically used within nonlinear solvers
5312:    implementations, so most users would not generally call this routine
5313:    themselves.

5315:    Level: developer

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

5319: .seealso: SNESSetFunction(), SNESGetFunction()
5320: */
5321: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5322: {
5323:   PetscErrorCode    ierr;
5324:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5325:   int               nlhs  = 1,nrhs = 5;
5326:   mxArray           *plhs[1],*prhs[5];
5327:   long long int     lx = 0,ly = 0,ls = 0;


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

5338:   PetscMemcpy(&ls,&snes,sizeof(snes));
5339:   PetscMemcpy(&lx,&x,sizeof(x));
5340:   PetscMemcpy(&ly,&y,sizeof(x));
5341:   prhs[0] = mxCreateDoubleScalar((double)ls);
5342:   prhs[1] = mxCreateDoubleScalar((double)lx);
5343:   prhs[2] = mxCreateDoubleScalar((double)ly);
5344:   prhs[3] = mxCreateString(sctx->funcname);
5345:   prhs[4] = sctx->ctx;
5346:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");
5347:   mxGetScalar(plhs[0]);
5348:   mxDestroyArray(prhs[0]);
5349:   mxDestroyArray(prhs[1]);
5350:   mxDestroyArray(prhs[2]);
5351:   mxDestroyArray(prhs[3]);
5352:   mxDestroyArray(plhs[0]);
5353:   return(0);
5354: }

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

5361:    Logically Collective on SNES

5363:    Input Parameters:
5364: +  snes - the SNES context
5365: .  r - vector to store function value
5366: -  f - function evaluation routine

5368:    Notes:
5369:    The Newton-like methods typically solve linear systems of the form
5370: $      f'(x) x = -f(x),
5371:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5373:    Level: beginner

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

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

5379: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5380: */
5381: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5382: {
5383:   PetscErrorCode    ierr;
5384:   SNESMatlabContext *sctx;

5387:   /* currently sctx is memory bleed */
5388:   PetscNew(&sctx);
5389:   PetscStrallocpy(f,&sctx->funcname);
5390:   /*
5391:      This should work, but it doesn't
5392:   sctx->ctx = ctx;
5393:   mexMakeArrayPersistent(sctx->ctx);
5394:   */
5395:   sctx->ctx = mxDuplicateArray(ctx);
5396:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5397:   return(0);
5398: }

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

5403:    Collective on SNES

5405:    Input Parameters:
5406: +  snes - the SNES context
5407: .  x - input vector
5408: .  A, B - the matrices
5409: -  ctx - user context

5411:    Level: developer

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

5415: .seealso: SNESSetFunction(), SNESGetFunction()
5416: @*/
5417: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5418: {
5419:   PetscErrorCode    ierr;
5420:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5421:   int               nlhs  = 2,nrhs = 6;
5422:   mxArray           *plhs[2],*prhs[6];
5423:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


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

5431:   PetscMemcpy(&ls,&snes,sizeof(snes));
5432:   PetscMemcpy(&lx,&x,sizeof(x));
5433:   PetscMemcpy(&lA,A,sizeof(x));
5434:   PetscMemcpy(&lB,B,sizeof(x));
5435:   prhs[0] = mxCreateDoubleScalar((double)ls);
5436:   prhs[1] = mxCreateDoubleScalar((double)lx);
5437:   prhs[2] = mxCreateDoubleScalar((double)lA);
5438:   prhs[3] = mxCreateDoubleScalar((double)lB);
5439:   prhs[4] = mxCreateString(sctx->funcname);
5440:   prhs[5] = sctx->ctx;
5441:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5442:   mxGetScalar(plhs[0]);
5443:   mxDestroyArray(prhs[0]);
5444:   mxDestroyArray(prhs[1]);
5445:   mxDestroyArray(prhs[2]);
5446:   mxDestroyArray(prhs[3]);
5447:   mxDestroyArray(prhs[4]);
5448:   mxDestroyArray(plhs[0]);
5449:   mxDestroyArray(plhs[1]);
5450:   return(0);
5451: }

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

5458:    Logically Collective on SNES

5460:    Input Parameters:
5461: +  snes - the SNES context
5462: .  A,B - Jacobian matrices
5463: .  J - function evaluation routine
5464: -  ctx - user context

5466:    Level: developer

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

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

5472: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5473: */
5474: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5475: {
5476:   PetscErrorCode    ierr;
5477:   SNESMatlabContext *sctx;

5480:   /* currently sctx is memory bleed */
5481:   PetscNew(&sctx);
5482:   PetscStrallocpy(J,&sctx->funcname);
5483:   /*
5484:      This should work, but it doesn't
5485:   sctx->ctx = ctx;
5486:   mexMakeArrayPersistent(sctx->ctx);
5487:   */
5488:   sctx->ctx = mxDuplicateArray(ctx);
5489:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5490:   return(0);
5491: }

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

5496:    Collective on SNES

5498: .seealso: SNESSetFunction(), SNESGetFunction()
5499: @*/
5500: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5501: {
5502:   PetscErrorCode    ierr;
5503:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5504:   int               nlhs  = 1,nrhs = 6;
5505:   mxArray           *plhs[1],*prhs[6];
5506:   long long int     lx = 0,ls = 0;
5507:   Vec               x  = snes->vec_sol;


5512:   PetscMemcpy(&ls,&snes,sizeof(snes));
5513:   PetscMemcpy(&lx,&x,sizeof(x));
5514:   prhs[0] = mxCreateDoubleScalar((double)ls);
5515:   prhs[1] = mxCreateDoubleScalar((double)it);
5516:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5517:   prhs[3] = mxCreateDoubleScalar((double)lx);
5518:   prhs[4] = mxCreateString(sctx->funcname);
5519:   prhs[5] = sctx->ctx;
5520:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5521:   mxGetScalar(plhs[0]);
5522:   mxDestroyArray(prhs[0]);
5523:   mxDestroyArray(prhs[1]);
5524:   mxDestroyArray(prhs[2]);
5525:   mxDestroyArray(prhs[3]);
5526:   mxDestroyArray(prhs[4]);
5527:   mxDestroyArray(plhs[0]);
5528:   return(0);
5529: }

5531: /*
5532:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5534:    Level: developer

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

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

5540: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5541: */
5542: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5543: {
5544:   PetscErrorCode    ierr;
5545:   SNESMatlabContext *sctx;

5548:   /* currently sctx is memory bleed */
5549:   PetscNew(&sctx);
5550:   PetscStrallocpy(f,&sctx->funcname);
5551:   /*
5552:      This should work, but it doesn't
5553:   sctx->ctx = ctx;
5554:   mexMakeArrayPersistent(sctx->ctx);
5555:   */
5556:   sctx->ctx = mxDuplicateArray(ctx);
5557:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5558:   return(0);
5559: }

5561: #endif