Actual source code: snes.c

petsc-master 2017-07-18
Report Typos and Errors

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

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

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

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

 18:    Logically Collective on SNES

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

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

 27:    Level: intermediate

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

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

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

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

 49:    Not Collective

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

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

 57:    Level: intermediate

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

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

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

 75:    Logically Collective on SNES

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

 81:    Level: advanced

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

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

 96:    Logically Collective on SNES

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

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

104:    Level: advanced

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

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

120:    Logically Collective on SNES

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

125:    Level: advanced

127: .keywords: SNES, view

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

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

143:    Logically Collective on SNES

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

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

151:    Level: advanced

153: .keywords: SNES, view

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

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

169:   Collective on PetscViewer

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

176:    Level: intermediate

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

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

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

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

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

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

230:    Collective on SNES

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

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

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

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

250:    Level: beginner

252: .keywords: SNES, view

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

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

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

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

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

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

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

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

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

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

420:   Not Collective

422:   Input Parameter:
423: . snescheck - function that checks for options

425:   Level: developer

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

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

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


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

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

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

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

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

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

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

536: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
537: {

541:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
542:   return(0);
543: }

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

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

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

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

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

588:    Collective

590:    Input Arguments:
591: .  snes - snes to configure

593:    Level: developer

595: .seealso: SNESSetUp()
596: @*/
597: PetscErrorCode SNESSetUpMatrices(SNES snes)
598: {
600:   DM             dm;
601:   DMSNES         sdm;

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

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

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

653:    Collective on SNES

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

663:    Level: developer

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

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

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

697:    Collective on SNES

699:    Input Parameter:
700: .  snes - the SNES context

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

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

741:    Notes:
742:    To see all options, run your program with the -help option or consult
743:    Users-Manual: ch_snes

745:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

839:   flg  = PETSC_FALSE;
840:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
841:   if (set && flg) {SNESMonitorCancel(snes);}

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

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

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


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

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

872:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
873:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
874:   }



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

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

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

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

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

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

944:   for (i = 0; i < numberofsetfromoptions; i++) {
945:     (*othersetfromoptions[i])(snes);
946:   }

948:   if (snes->ops->setfromoptions) {
949:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
950:   }

952:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
953:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
954:   PetscOptionsEnd();

956:   if (!snes->linesearch) {
957:     SNESGetLineSearch(snes, &snes->linesearch);
958:   }
959:   SNESLineSearchSetFromOptions(snes->linesearch);

961:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
962:   KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
963:   KSPSetFromOptions(snes->ksp);

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

974: /*@C
975:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
976:    the nonlinear solvers.

978:    Logically Collective on SNES

980:    Input Parameters:
981: +  snes - the SNES context
982: .  compute - function to compute the context
983: -  destroy - function to destroy the context

985:    Level: intermediate

987:    Notes:
988:    This function is currently not available from Fortran.

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

992: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
993: @*/
994: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
995: {
998:   snes->ops->usercompute = compute;
999:   snes->ops->userdestroy = destroy;
1000:   return(0);
1001: }

1003: /*@
1004:    SNESSetApplicationContext - Sets the optional user-defined context for
1005:    the nonlinear solvers.

1007:    Logically Collective on SNES

1009:    Input Parameters:
1010: +  snes - the SNES context
1011: -  usrP - optional user context

1013:    Level: intermediate

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

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

1020: .seealso: SNESGetApplicationContext()
1021: @*/
1022: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1023: {
1025:   KSP            ksp;

1029:   SNESGetKSP(snes,&ksp);
1030:   KSPSetApplicationContext(ksp,usrP);
1031:   snes->user = usrP;
1032:   return(0);
1033: }

1035: /*@
1036:    SNESGetApplicationContext - Gets the user-defined context for the
1037:    nonlinear solvers.

1039:    Not Collective

1041:    Input Parameter:
1042: .  snes - SNES context

1044:    Output Parameter:
1045: .  usrP - user context

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

1050:    Level: intermediate

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

1054: .seealso: SNESSetApplicationContext()
1055: @*/
1056: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1057: {
1060:   *(void**)usrP = snes->user;
1061:   return(0);
1062: }

1064: /*@
1065:    SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply
1066:                           the Jacobian.

1068:    Collective on SNES

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

1075:    Options Database:
1076: + -snes_mf - use matrix free for both the mat and pmat operator
1077: - -snes_mf_operator - use matrix free only for the mat operator

1079:    Level: intermediate

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

1083: .seealso:   SNESGetUseMatrixFree(), MatCreateSNESMF()
1084: @*/
1085: PetscErrorCode  SNESSetUseMatrixFree(SNES snes,PetscBool mf_operator,PetscBool mf)
1086: {
1089:   if (mf && !mf_operator) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"If using mf must also use mf_operator");
1090:   snes->mf          = mf;
1091:   snes->mf_operator = mf_operator;
1092:   return(0);
1093: }

1095: /*@
1096:    SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply
1097:                           the Jacobian.

1099:    Collective on SNES

1101:    Input Parameter:
1102: .  snes - SNES context

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

1108:    Options Database:
1109: + -snes_mf - use matrix free for both the mat and pmat operator
1110: - -snes_mf_operator - use matrix free only for the mat operator

1112:    Level: intermediate

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

1116: .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
1117: @*/
1118: PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1119: {
1122:   if (mf)          *mf          = snes->mf;
1123:   if (mf_operator) *mf_operator = snes->mf_operator;
1124:   return(0);
1125: }

1127: /*@
1128:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1129:    at this time.

1131:    Not Collective

1133:    Input Parameter:
1134: .  snes - SNES context

1136:    Output Parameter:
1137: .  iter - iteration number

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

1142:    This is useful for using lagged Jacobians (where one does not recompute the
1143:    Jacobian at each SNES iteration). For example, the code
1144: .vb
1145:       SNESGetIterationNumber(snes,&it);
1146:       if (!(it % 2)) {
1147:         [compute Jacobian here]
1148:       }
1149: .ve
1150:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1151:    recomputed every second SNES iteration.

1153:    Level: intermediate

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

1157: .seealso:   SNESGetLinearSolveIterations()
1158: @*/
1159: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1160: {
1164:   *iter = snes->iter;
1165:   return(0);
1166: }

1168: /*@
1169:    SNESSetIterationNumber - Sets the current iteration number.

1171:    Not Collective

1173:    Input Parameter:
1174: .  snes - SNES context
1175: .  iter - iteration number

1177:    Level: developer

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

1181: .seealso:   SNESGetLinearSolveIterations()
1182: @*/
1183: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1184: {

1189:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1190:   snes->iter = iter;
1191:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1192:   return(0);
1193: }

1195: /*@
1196:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1197:    attempted by the nonlinear solver.

1199:    Not Collective

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

1204:    Output Parameter:
1205: .  nfails - number of unsuccessful steps attempted

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

1210:    Level: intermediate

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

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

1226: /*@
1227:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1228:    attempted by the nonlinear solver before it gives up.

1230:    Not Collective

1232:    Input Parameters:
1233: +  snes     - SNES context
1234: -  maxFails - maximum of unsuccessful steps

1236:    Level: intermediate

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

1240: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1241:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1242: @*/
1243: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1244: {
1247:   snes->maxFailures = maxFails;
1248:   return(0);
1249: }

1251: /*@
1252:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1253:    attempted by the nonlinear solver before it gives up.

1255:    Not Collective

1257:    Input Parameter:
1258: .  snes     - SNES context

1260:    Output Parameter:
1261: .  maxFails - maximum of unsuccessful steps

1263:    Level: intermediate

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

1267: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1268:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1270: @*/
1271: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1272: {
1276:   *maxFails = snes->maxFailures;
1277:   return(0);
1278: }

1280: /*@
1281:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1282:      done by SNES.

1284:    Not Collective

1286:    Input Parameter:
1287: .  snes     - SNES context

1289:    Output Parameter:
1290: .  nfuncs - number of evaluations

1292:    Level: intermediate

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

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

1298: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1299: @*/
1300: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1301: {
1305:   *nfuncs = snes->nfuncs;
1306:   return(0);
1307: }

1309: /*@
1310:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1311:    linear solvers.

1313:    Not Collective

1315:    Input Parameter:
1316: .  snes - SNES context

1318:    Output Parameter:
1319: .  nfails - number of failed solves

1321:    Level: intermediate

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

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

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

1331: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1332: @*/
1333: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1334: {
1338:   *nfails = snes->numLinearSolveFailures;
1339:   return(0);
1340: }

1342: /*@
1343:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1344:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1346:    Logically Collective on SNES

1348:    Input Parameters:
1349: +  snes     - SNES context
1350: -  maxFails - maximum allowed linear solve failures

1352:    Level: intermediate

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

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

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

1361: .seealso: SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations()
1362: @*/
1363: PetscErrorCode  SNESSetMaxLinearSolveFailures(SNES snes, PetscInt maxFails)
1364: {
1368:   snes->maxLinearSolveFailures = maxFails;
1369:   return(0);
1370: }

1372: /*@
1373:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1374:      are allowed before SNES terminates

1376:    Not Collective

1378:    Input Parameter:
1379: .  snes     - SNES context

1381:    Output Parameter:
1382: .  maxFails - maximum of unsuccessful solves allowed

1384:    Level: intermediate

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

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

1390: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1391: @*/
1392: PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1393: {
1397:   *maxFails = snes->maxLinearSolveFailures;
1398:   return(0);
1399: }

1401: /*@
1402:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1403:    used by the nonlinear solver.

1405:    Not Collective

1407:    Input Parameter:
1408: .  snes - SNES context

1410:    Output Parameter:
1411: .  lits - number of linear iterations

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

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

1419:    Level: intermediate

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

1423: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1424: @*/
1425: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1426: {
1430:   *lits = snes->linear_its;
1431:   return(0);
1432: }

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

1438:    Logically Collective on SNES

1440:    Input Parameter:
1441: +  snes - SNES context
1442: -  reset - whether to reset the counters or not

1444:    Notes:
1445:    This defaults to PETSC_TRUE

1447:    Level: developer

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

1451: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1452: @*/
1453: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1454: {
1458:   snes->counters_reset = reset;
1459:   return(0);
1460: }


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

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

1468:    Input Parameters:
1469: +  snes - the SNES context
1470: -  ksp - the KSP context

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

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

1479:    Level: developer

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

1483: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1484: @*/
1485: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1486: {

1493:   PetscObjectReference((PetscObject)ksp);
1494:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1495:   snes->ksp = ksp;
1496:   return(0);
1497: }

1499: /* -----------------------------------------------------------*/
1500: /*@
1501:    SNESCreate - Creates a nonlinear solver context.

1503:    Collective on MPI_Comm

1505:    Input Parameters:
1506: .  comm - MPI communicator

1508:    Output Parameter:
1509: .  outsnes - the new SNES context

1511:    Options Database Keys:
1512: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1513:                and no preconditioning matrix
1514: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1515:                products, and a user-provided preconditioning matrix
1516:                as set by SNESSetJacobian()
1517: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1519:    Level: beginner

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

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

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

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

1534: @*/
1535: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1536: {
1538:   SNES           snes;
1539:   SNESKSPEW      *kctx;

1543:   *outsnes = NULL;
1544:   SNESInitializePackage();

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

1548:   snes->ops->converged    = SNESConvergedDefault;
1549:   snes->usesksp           = PETSC_TRUE;
1550:   snes->tolerancesset     = PETSC_FALSE;
1551:   snes->max_its           = 50;
1552:   snes->max_funcs         = 10000;
1553:   snes->norm              = 0.0;
1554:   snes->normschedule      = SNES_NORM_ALWAYS;
1555:   snes->functype          = SNES_FUNCTION_DEFAULT;
1556: #if defined(PETSC_USE_REAL_SINGLE)
1557:   snes->rtol              = 1.e-5;
1558: #else
1559:   snes->rtol              = 1.e-8;
1560: #endif
1561:   snes->ttol              = 0.0;
1562: #if defined(PETSC_USE_REAL_SINGLE)
1563:   snes->abstol            = 1.e-25;
1564: #else
1565:   snes->abstol            = 1.e-50;
1566: #endif
1567: #if defined(PETSC_USE_REAL_SINGLE)
1568:   snes->stol              = 1.e-5;
1569: #else
1570:   snes->stol              = 1.e-8;
1571: #endif
1572: #if defined(PETSC_USE_REAL_SINGLE)
1573:   snes->deltatol          = 1.e-6;
1574: #else
1575:   snes->deltatol          = 1.e-12;
1576: #endif
1577:   snes->divtol            = 1.e4;
1578:   snes->rnorm0            = 0;
1579:   snes->nfuncs            = 0;
1580:   snes->numFailures       = 0;
1581:   snes->maxFailures       = 1;
1582:   snes->linear_its        = 0;
1583:   snes->lagjacobian       = 1;
1584:   snes->jac_iter          = 0;
1585:   snes->lagjac_persist    = PETSC_FALSE;
1586:   snes->lagpreconditioner = 1;
1587:   snes->pre_iter          = 0;
1588:   snes->lagpre_persist    = PETSC_FALSE;
1589:   snes->numbermonitors    = 0;
1590:   snes->data              = 0;
1591:   snes->setupcalled       = PETSC_FALSE;
1592:   snes->ksp_ewconv        = PETSC_FALSE;
1593:   snes->nwork             = 0;
1594:   snes->work              = 0;
1595:   snes->nvwork            = 0;
1596:   snes->vwork             = 0;
1597:   snes->conv_hist_len     = 0;
1598:   snes->conv_hist_max     = 0;
1599:   snes->conv_hist         = NULL;
1600:   snes->conv_hist_its     = NULL;
1601:   snes->conv_hist_reset   = PETSC_TRUE;
1602:   snes->counters_reset    = PETSC_TRUE;
1603:   snes->vec_func_init_set = PETSC_FALSE;
1604:   snes->reason            = SNES_CONVERGED_ITERATING;
1605:   snes->npcside           = PC_RIGHT;

1607:   snes->mf          = PETSC_FALSE;
1608:   snes->mf_operator = PETSC_FALSE;
1609:   snes->mf_version  = 1;

1611:   snes->numLinearSolveFailures = 0;
1612:   snes->maxLinearSolveFailures = 1;

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

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

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

1622:   snes->kspconvctx  = (void*)kctx;
1623:   kctx->version     = 2;
1624:   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1625:                              this was too large for some test cases */
1626:   kctx->rtol_last   = 0.0;
1627:   kctx->rtol_max    = .9;
1628:   kctx->gamma       = 1.0;
1629:   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
1630:   kctx->alpha2      = kctx->alpha;
1631:   kctx->threshold   = .1;
1632:   kctx->lresid_last = 0.0;
1633:   kctx->norm_last   = 0.0;

1635:   *outsnes = snes;
1636:   return(0);
1637: }

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

1642:      Synopsis:
1643:      #include "petscsnes.h"
1644:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1646:      Input Parameters:
1647: +     snes - the SNES context
1648: .     x    - state at which to evaluate residual
1649: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1651:      Output Parameter:
1652: .     f  - vector to put residual (function value)

1654:    Level: intermediate

1656: .seealso:   SNESSetFunction(), SNESGetFunction()
1657: M*/

1659: /*@C
1660:    SNESSetFunction - Sets the function evaluation routine and function
1661:    vector for use by the SNES routines in solving systems of nonlinear
1662:    equations.

1664:    Logically Collective on SNES

1666:    Input Parameters:
1667: +  snes - the SNES context
1668: .  r - vector to store function value
1669: .  f - function evaluation routine; see SNESFunction for calling sequence details
1670: -  ctx - [optional] user-defined context for private data for the
1671:          function evaluation routine (may be NULL)

1673:    Notes:
1674:    The Newton-like methods typically solve linear systems of the form
1675: $      f'(x) x = -f(x),
1676:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1678:    Level: beginner

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

1682: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1683: @*/
1684: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1685: {
1687:   DM             dm;

1691:   if (r) {
1694:     PetscObjectReference((PetscObject)r);
1695:     VecDestroy(&snes->vec_func);

1697:     snes->vec_func = r;
1698:   }
1699:   SNESGetDM(snes,&dm);
1700:   DMSNESSetFunction(dm,f,ctx);
1701:   return(0);
1702: }


1705: /*@C
1706:    SNESSetInitialFunction - Sets the function vector to be used as the
1707:    function norm at the initialization of the method.  In some
1708:    instances, the user has precomputed the function before calling
1709:    SNESSolve.  This function allows one to avoid a redundant call
1710:    to SNESComputeFunction in that case.

1712:    Logically Collective on SNES

1714:    Input Parameters:
1715: +  snes - the SNES context
1716: -  f - vector to store function value

1718:    Notes:
1719:    This should not be modified during the solution procedure.

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

1723:    Level: developer

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

1727: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1728: @*/
1729: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1730: {
1732:   Vec            vec_func;

1738:   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1739:     snes->vec_func_init_set = PETSC_FALSE;
1740:     return(0);
1741:   }
1742:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1743:   VecCopy(f, vec_func);

1745:   snes->vec_func_init_set = PETSC_TRUE;
1746:   return(0);
1747: }

1749: /*@
1750:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1751:    of the SNES method.

1753:    Logically Collective on SNES

1755:    Input Parameters:
1756: +  snes - the SNES context
1757: -  normschedule - the frequency of norm computation

1759:    Options Database Key:
1760: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1771:    Level: developer

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

1775: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1776: @*/
1777: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1778: {
1781:   snes->normschedule = normschedule;
1782:   return(0);
1783: }


1786: /*@
1787:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1788:    of the SNES method.

1790:    Logically Collective on SNES

1792:    Input Parameters:
1793: +  snes - the SNES context
1794: -  normschedule - the type of the norm used

1796:    Level: advanced

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

1800: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1801: @*/
1802: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1803: {
1806:   *normschedule = snes->normschedule;
1807:   return(0);
1808: }


1811: /*@
1812:   SNESSetFunctionNorm - Sets the last computed residual norm.

1814:   Logically Collective on SNES

1816:   Input Parameters:
1817: + snes - the SNES context

1819: - normschedule - the frequency of norm computation

1821:   Level: developer

1823: .keywords: SNES, nonlinear, set, function, norm, type
1824: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1825: @*/
1826: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1827: {
1830:   snes->norm = norm;
1831:   return(0);
1832: }

1834: /*@
1835:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1837:   Not Collective

1839:   Input Parameter:
1840: . snes - the SNES context

1842:   Output Parameter:
1843: . norm - the last computed residual norm

1845:   Level: developer

1847: .keywords: SNES, nonlinear, set, function, norm, type
1848: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1849: @*/
1850: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1851: {
1855:   *norm = snes->norm;
1856:   return(0);
1857: }

1859: /*@C
1860:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1861:    of the SNES method.

1863:    Logically Collective on SNES

1865:    Input Parameters:
1866: +  snes - the SNES context
1867: -  normschedule - the frequency of norm computation

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

1878:    Level: developer

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

1882: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1883: @*/
1884: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1885: {
1888:   snes->functype = type;
1889:   return(0);
1890: }


1893: /*@C
1894:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1895:    of the SNES method.

1897:    Logically Collective on SNES

1899:    Input Parameters:
1900: +  snes - the SNES context
1901: -  normschedule - the type of the norm used

1903:    Level: advanced

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

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

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

1920:      Synopsis:
1921:      #include <petscsnes.h>
1922: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1924: +  X   - solution vector
1925: .  B   - RHS vector
1926: -  ctx - optional user-defined Gauss-Seidel context

1928:    Level: intermediate

1930: .seealso:   SNESSetNGS(), SNESGetNGS()
1931: M*/

1933: /*@C
1934:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1935:    use with composed nonlinear solvers.

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

1943:    Notes:
1944:    The NGS routines are used by the composed nonlinear solver to generate
1945:     a problem appropriate update to the solution, particularly FAS.

1947:    Level: intermediate

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

1951: .seealso: SNESGetFunction(), SNESComputeNGS()
1952: @*/
1953: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1954: {
1956:   DM             dm;

1960:   SNESGetDM(snes,&dm);
1961:   DMSNESSetNGS(dm,f,ctx);
1962:   return(0);
1963: }

1965: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1966: {
1968:   DM             dm;
1969:   DMSNES         sdm;

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

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

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

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

1997:    Logically Collective on SNES

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

2009:    Notes:
2010:     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
2011:     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.

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

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

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

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

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

2027:    Level: intermediate

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

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

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

2047: /*@C
2048:    SNESGetPicard - Returns the context for the Picard iteration

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

2052:    Input Parameter:
2053: .  snes - the SNES context

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

2063:    Level: advanced

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

2067: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2068: @*/
2069: 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)
2070: {
2072:   DM             dm;

2076:   SNESGetFunction(snes,r,NULL,NULL);
2077:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2078:   SNESGetDM(snes,&dm);
2079:   DMSNESGetPicard(dm,f,J,ctx);
2080:   return(0);
2081: }

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

2086:    Logically Collective on SNES

2088:    Input Parameters:
2089: +  snes - the SNES context
2090: .  func - function evaluation routine
2091: -  ctx - [optional] user-defined context for private data for the
2092:          function evaluation routine (may be NULL)

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

2097: .  f - function vector
2098: -  ctx - optional user-defined function context

2100:    Level: intermediate

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

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

2115: /* --------------------------------------------------------------- */
2116: /*@C
2117:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2118:    it assumes a zero right hand side.

2120:    Logically Collective on SNES

2122:    Input Parameter:
2123: .  snes - the SNES context

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

2128:    Level: intermediate

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

2132: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2133: @*/
2134: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2135: {
2139:   *rhs = snes->vec_rhs;
2140:   return(0);
2141: }

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

2146:    Collective on SNES

2148:    Input Parameters:
2149: +  snes - the SNES context
2150: -  x - input vector

2152:    Output Parameter:
2153: .  y - function vector, as set by SNESSetFunction()

2155:    Notes:
2156:    SNESComputeFunction() is typically used within nonlinear solvers
2157:    implementations, so most users would not generally call this routine
2158:    themselves.

2160:    Level: developer

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

2164: .seealso: SNESSetFunction(), SNESGetFunction()
2165: @*/
2166: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2167: {
2169:   DM             dm;
2170:   DMSNES         sdm;

2178:   VecValidValues(x,2,PETSC_TRUE);

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

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

2214:    Collective on SNES

2216:    Input Parameters:
2217: +  snes - the SNES context
2218: .  x - input vector
2219: -  b - rhs vector

2221:    Output Parameter:
2222: .  x - new solution vector

2224:    Notes:
2225:    SNESComputeNGS() is typically used within composed nonlinear solver
2226:    implementations, so most users would not generally call this routine
2227:    themselves.

2229:    Level: developer

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

2233: .seealso: SNESSetNGS(), SNESComputeFunction()
2234: @*/
2235: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2236: {
2238:   DM             dm;
2239:   DMSNES         sdm;

2247:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2248:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2249:   SNESGetDM(snes,&dm);
2250:   DMGetDMSNES(dm,&sdm);
2251:   if (sdm->ops->computegs) {
2252:     if (b) {VecLockPush(b);}
2253:     PetscStackPush("SNES user NGS");
2254:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2255:     PetscStackPop;
2256:     if (b) {VecLockPop(b);}
2257:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2258:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2259:   return(0);
2260: }

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

2265:    Collective on SNES and Mat

2267:    Input Parameters:
2268: +  snes - the SNES context
2269: -  x - input vector

2271:    Output Parameters:
2272: +  A - Jacobian matrix
2273: -  B - optional preconditioning matrix

2275:   Options Database Keys:
2276: +    -snes_lag_preconditioner <lag>
2277: .    -snes_lag_jacobian <lag>
2278: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2279: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2280: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2281: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2282: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2283: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2284: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2285: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2286: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2287: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2288: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2291:    Notes:
2292:    Most users should not need to explicitly call this routine, as it
2293:    is used internally within the nonlinear solvers.

2295:    Level: developer

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

2299: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2300: @*/
2301: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2302: {
2304:   PetscBool      flag;
2305:   DM             dm;
2306:   DMSNES         sdm;
2307:   KSP            ksp;

2313:   VecValidValues(X,2,PETSC_TRUE);
2314:   SNESGetDM(snes,&dm);
2315:   DMGetDMSNES(dm,&sdm);

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

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

2321:   if (snes->lagjacobian == -2) {
2322:     snes->lagjacobian = -1;

2324:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2325:   } else if (snes->lagjacobian == -1) {
2326:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2327:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2328:     if (flag) {
2329:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2330:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2331:     }
2332:     return(0);
2333:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2334:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2335:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2336:     if (flag) {
2337:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2338:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2339:     }
2340:     return(0);
2341:   }
2342:   if (snes->npc && snes->npcside== PC_LEFT) {
2343:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2344:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2345:       return(0);
2346:   }

2348:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2349:   VecLockPush(X);
2350:   PetscStackPush("SNES user Jacobian function");
2351:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2352:   PetscStackPop;
2353:   VecLockPop(X);
2354:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2356:   /* the next line ensures that snes->ksp exists */
2357:   SNESGetKSP(snes,&ksp);
2358:   if (snes->lagpreconditioner == -2) {
2359:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2360:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2361:     snes->lagpreconditioner = -1;
2362:   } else if (snes->lagpreconditioner == -1) {
2363:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2364:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2365:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2366:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2367:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2368:   } else {
2369:     PetscInfo(snes,"Rebuilding preconditioner\n");
2370:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2371:   }

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

2448:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2449:       MatColoringCreate(Bfd,&coloring);
2450:       MatColoringSetType(coloring,MATCOLORINGSL);
2451:       MatColoringSetFromOptions(coloring);
2452:       MatColoringApply(coloring,&iscoloring);
2453:       MatColoringDestroy(&coloring);
2454:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2455:       MatFDColoringSetFromOptions(matfdcoloring);
2456:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2457:       ISColoringDestroy(&iscoloring);

2459:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2460:       SNESGetFunction(snes,NULL,&func,&funcctx);
2461:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2462:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2463:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2464:       MatFDColoringSetFromOptions(matfdcoloring);
2465:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2466:       MatFDColoringDestroy(&matfdcoloring);

2468:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2469:       if (flag_draw || flag_contour) {
2470:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2471:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2472:       } else vdraw = NULL;
2473:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2474:       if (flag_display) {MatView(B,vstdout);}
2475:       if (vdraw) {MatView(B,vdraw);}
2476:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2477:       if (flag_display) {MatView(Bfd,vstdout);}
2478:       if (vdraw) {MatView(Bfd,vdraw);}
2479:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2480:       MatNorm(Bfd,NORM_1,&norm1);
2481:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2482:       MatNorm(Bfd,NORM_MAX,&normmax);
2483:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2484:       if (flag_display) {MatView(Bfd,vstdout);}
2485:       if (vdraw) {              /* Always use contour for the difference */
2486:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2487:         MatView(Bfd,vdraw);
2488:         PetscViewerPopFormat(vdraw);
2489:       }
2490:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

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

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

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

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

2553:    Level: intermediate

2555: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2556: M*/

2558: /*@C
2559:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2560:    location to store the matrix.

2562:    Logically Collective on SNES and Mat

2564:    Input Parameters:
2565: +  snes - the SNES context
2566: .  Amat - the matrix that defines the (approximate) Jacobian
2567: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2568: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2569: -  ctx - [optional] user-defined context for private data for the
2570:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2572:    Notes:
2573:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2574:    each matrix.

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

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

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

2585:    Level: beginner

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

2589: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J, 
2590:           SNESSetPicard(), SNESJacobianFunction
2591: @*/
2592: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2593: {
2595:   DM             dm;

2603:   SNESGetDM(snes,&dm);
2604:   DMSNESSetJacobian(dm,J,ctx);
2605:   if (Amat) {
2606:     PetscObjectReference((PetscObject)Amat);
2607:     MatDestroy(&snes->jacobian);

2609:     snes->jacobian = Amat;
2610:   }
2611:   if (Pmat) {
2612:     PetscObjectReference((PetscObject)Pmat);
2613:     MatDestroy(&snes->jacobian_pre);

2615:     snes->jacobian_pre = Pmat;
2616:   }
2617:   return(0);
2618: }

2620: /*@C
2621:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2622:    provided context for evaluating the Jacobian.

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

2626:    Input Parameter:
2627: .  snes - the nonlinear solver context

2629:    Output Parameters:
2630: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2631: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2632: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2633: -  ctx - location to stash Jacobian ctx (or NULL)

2635:    Level: advanced

2637: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2638: @*/
2639: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2640: {
2642:   DM             dm;
2643:   DMSNES         sdm;

2647:   if (Amat) *Amat = snes->jacobian;
2648:   if (Pmat) *Pmat = snes->jacobian_pre;
2649:   SNESGetDM(snes,&dm);
2650:   DMGetDMSNES(dm,&sdm);
2651:   if (J) *J = sdm->ops->computejacobian;
2652:   if (ctx) *ctx = sdm->jacobianctx;
2653:   return(0);
2654: }

2656: /*@
2657:    SNESSetUp - Sets up the internal data structures for the later use
2658:    of a nonlinear solver.

2660:    Collective on SNES

2662:    Input Parameters:
2663: .  snes - the SNES context

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

2672:    Level: advanced

2674: .keywords: SNES, nonlinear, setup

2676: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2677: @*/
2678: PetscErrorCode  SNESSetUp(SNES snes)
2679: {
2681:   DM             dm;
2682:   DMSNES         sdm;
2683:   SNESLineSearch linesearch, pclinesearch;
2684:   void           *lsprectx,*lspostctx;
2685:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2686:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2687:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2688:   Vec            f,fpc;
2689:   void           *funcctx;
2690:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2691:   void           *jacctx,*appctx;
2692:   Mat            j,jpre;

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

2698:   if (!((PetscObject)snes)->type_name) {
2699:     SNESSetType(snes,SNESNEWTONLS);
2700:   }

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

2704:   SNESGetDM(snes,&dm);
2705:   DMGetDMSNES(dm,&sdm);
2706:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2707:   if (!sdm->ops->computejacobian) {
2708:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2709:   }
2710:   if (!snes->vec_func) {
2711:     DMCreateGlobalVector(dm,&snes->vec_func);
2712:   }

2714:   if (!snes->ksp) {
2715:     SNESGetKSP(snes, &snes->ksp);
2716:   }

2718:   if (!snes->linesearch) {
2719:     SNESGetLineSearch(snes, &snes->linesearch);
2720:   }
2721:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2723:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2724:     snes->mf          = PETSC_TRUE;
2725:     snes->mf_operator = PETSC_FALSE;
2726:   }

2728:   if (snes->npc) {
2729:     /* copy the DM over */
2730:     SNESGetDM(snes,&dm);
2731:     SNESSetDM(snes->npc,dm);

2733:     SNESGetFunction(snes,&f,&func,&funcctx);
2734:     VecDuplicate(f,&fpc);
2735:     SNESSetFunction(snes->npc,fpc,func,funcctx);
2736:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2737:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
2738:     SNESGetApplicationContext(snes,&appctx);
2739:     SNESSetApplicationContext(snes->npc,appctx);
2740:     VecDestroy(&fpc);

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

2745:     /* default to 1 iteration */
2746:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
2747:     if (snes->npcside==PC_RIGHT) {
2748:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
2749:     } else {
2750:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
2751:     }
2752:     SNESSetFromOptions(snes->npc);

2754:     /* copy the line search context over */
2755:     SNESGetLineSearch(snes,&linesearch);
2756:     SNESGetLineSearch(snes->npc,&pclinesearch);
2757:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2758:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2759:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2760:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2761:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2762:   }
2763:   if (snes->mf) {
2764:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2765:   }
2766:   if (snes->ops->usercompute && !snes->user) {
2767:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2768:   }

2770:   snes->jac_iter = 0;
2771:   snes->pre_iter = 0;

2773:   if (snes->ops->setup) {
2774:     (*snes->ops->setup)(snes);
2775:   }

2777:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2778:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2779:       SNESGetLineSearch(snes,&linesearch);
2780:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2781:     }
2782:   }

2784:   snes->setupcalled = PETSC_TRUE;
2785:   return(0);
2786: }

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

2791:    Collective on SNES

2793:    Input Parameter:
2794: .  snes - iterative context obtained from SNESCreate()

2796:    Level: intermediate

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

2800: .keywords: SNES, destroy

2802: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
2803: @*/
2804: PetscErrorCode  SNESReset(SNES snes)
2805: {

2810:   if (snes->ops->userdestroy && snes->user) {
2811:     (*snes->ops->userdestroy)((void**)&snes->user);
2812:     snes->user = NULL;
2813:   }
2814:   if (snes->npc) {
2815:     SNESReset(snes->npc);
2816:   }

2818:   if (snes->ops->reset) {
2819:     (*snes->ops->reset)(snes);
2820:   }
2821:   if (snes->ksp) {
2822:     KSPReset(snes->ksp);
2823:   }

2825:   if (snes->linesearch) {
2826:     SNESLineSearchReset(snes->linesearch);
2827:   }

2829:   VecDestroy(&snes->vec_rhs);
2830:   VecDestroy(&snes->vec_sol);
2831:   VecDestroy(&snes->vec_sol_update);
2832:   VecDestroy(&snes->vec_func);
2833:   MatDestroy(&snes->jacobian);
2834:   MatDestroy(&snes->jacobian_pre);
2835:   VecDestroyVecs(snes->nwork,&snes->work);
2836:   VecDestroyVecs(snes->nvwork,&snes->vwork);

2838:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

2840:   snes->nwork       = snes->nvwork = 0;
2841:   snes->setupcalled = PETSC_FALSE;
2842:   return(0);
2843: }

2845: /*@
2846:    SNESDestroy - Destroys the nonlinear solver context that was created
2847:    with SNESCreate().

2849:    Collective on SNES

2851:    Input Parameter:
2852: .  snes - the SNES context

2854:    Level: beginner

2856: .keywords: SNES, nonlinear, destroy

2858: .seealso: SNESCreate(), SNESSolve()
2859: @*/
2860: PetscErrorCode  SNESDestroy(SNES *snes)
2861: {

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

2869:   SNESReset((*snes));
2870:   SNESDestroy(&(*snes)->npc);

2872:   /* if memory was published with SAWs then destroy it */
2873:   PetscObjectSAWsViewOff((PetscObject)*snes);
2874:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

2876:   DMDestroy(&(*snes)->dm);
2877:   KSPDestroy(&(*snes)->ksp);
2878:   SNESLineSearchDestroy(&(*snes)->linesearch);

2880:   PetscFree((*snes)->kspconvctx);
2881:   if ((*snes)->ops->convergeddestroy) {
2882:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
2883:   }
2884:   if ((*snes)->conv_malloc) {
2885:     PetscFree((*snes)->conv_hist);
2886:     PetscFree((*snes)->conv_hist_its);
2887:   }
2888:   SNESMonitorCancel((*snes));
2889:   PetscHeaderDestroy(snes);
2890:   return(0);
2891: }

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

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

2898:    Logically Collective on SNES

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

2905:    Options Database Keys:
2906: .    -snes_lag_preconditioner <lag>

2908:    Notes:
2909:    The default is 1
2910:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
2911:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

2913:    Level: intermediate

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

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

2919: @*/
2920: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
2921: {
2924:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
2925:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
2927:   snes->lagpreconditioner = lag;
2928:   return(0);
2929: }

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

2934:    Logically Collective on SNES

2936:    Input Parameters:
2937: +  snes - the SNES context
2938: -  steps - the number of refinements to do, defaults to 0

2940:    Options Database Keys:
2941: .    -snes_grid_sequence <steps>

2943:    Level: intermediate

2945:    Notes:
2946:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2952: @*/
2953: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
2954: {
2958:   snes->gridsequence = steps;
2959:   return(0);
2960: }

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

2965:    Logically Collective on SNES

2967:    Input Parameter:
2968: .  snes - the SNES context

2970:    Output Parameter:
2971: .  steps - the number of refinements to do, defaults to 0

2973:    Options Database Keys:
2974: .    -snes_grid_sequence <steps>

2976:    Level: intermediate

2978:    Notes:
2979:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2985: @*/
2986: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
2987: {
2990:   *steps = snes->gridsequence;
2991:   return(0);
2992: }

2994: /*@
2995:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

2997:    Not Collective

2999:    Input Parameter:
3000: .  snes - the SNES context

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

3006:    Options Database Keys:
3007: .    -snes_lag_preconditioner <lag>

3009:    Notes:
3010:    The default is 1
3011:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3013:    Level: intermediate

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

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

3019: @*/
3020: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3021: {
3024:   *lag = snes->lagpreconditioner;
3025:   return(0);
3026: }

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

3032:    Logically Collective on SNES

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

3039:    Options Database Keys:
3040: .    -snes_lag_jacobian <lag>

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

3048:    Level: intermediate

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

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

3054: @*/
3055: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3056: {
3059:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3060:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3062:   snes->lagjacobian = lag;
3063:   return(0);
3064: }

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

3069:    Not Collective

3071:    Input Parameter:
3072: .  snes - the SNES context

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

3078:    Options Database Keys:
3079: .    -snes_lag_jacobian <lag>

3081:    Notes:
3082:    The default is 1
3083:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3085:    Level: intermediate

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

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

3091: @*/
3092: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3093: {
3096:   *lag = snes->lagjacobian;
3097:   return(0);
3098: }

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

3103:    Logically collective on SNES

3105:    Input Parameter:
3106: +  snes - the SNES context
3107: -   flg - jacobian lagging persists if true

3109:    Options Database Keys:
3110: .    -snes_lag_jacobian_persists <flg>

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

3116:    Level: developer

3118: .keywords: SNES, nonlinear, lag

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

3122: @*/
3123: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3124: {
3128:   snes->lagjac_persist = flg;
3129:   return(0);
3130: }

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

3135:    Logically Collective on SNES

3137:    Input Parameter:
3138: +  snes - the SNES context
3139: -   flg - preconditioner lagging persists if true

3141:    Options Database Keys:
3142: .    -snes_lag_jacobian_persists <flg>

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

3148:    Level: developer

3150: .keywords: SNES, nonlinear, lag

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

3154: @*/
3155: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3156: {
3160:   snes->lagpre_persist = flg;
3161:   return(0);
3162: }

3164: /*@
3165:    SNESSetTolerances - Sets various parameters used in convergence tests.

3167:    Logically Collective on SNES

3169:    Input Parameters:
3170: +  snes - the SNES context
3171: .  abstol - absolute convergence tolerance
3172: .  rtol - relative convergence tolerance
3173: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3174: .  maxit - maximum number of iterations
3175: -  maxf - maximum number of function evaluations

3177:    Options Database Keys:
3178: +    -snes_atol <abstol> - Sets abstol
3179: .    -snes_rtol <rtol> - Sets rtol
3180: .    -snes_stol <stol> - Sets stol
3181: .    -snes_max_it <maxit> - Sets maxit
3182: -    -snes_max_funcs <maxf> - Sets maxf

3184:    Notes:
3185:    The default maximum number of iterations is 50.
3186:    The default maximum number of function evaluations is 1000.

3188:    Level: intermediate

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

3192: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3193: @*/
3194: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3195: {

3204:   if (abstol != PETSC_DEFAULT) {
3205:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3206:     snes->abstol = abstol;
3207:   }
3208:   if (rtol != PETSC_DEFAULT) {
3209:     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);
3210:     snes->rtol = rtol;
3211:   }
3212:   if (stol != PETSC_DEFAULT) {
3213:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3214:     snes->stol = stol;
3215:   }
3216:   if (maxit != PETSC_DEFAULT) {
3217:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3218:     snes->max_its = maxit;
3219:   }
3220:   if (maxf != PETSC_DEFAULT) {
3221:     if (maxf < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be non-negative",maxf);
3222:     snes->max_funcs = maxf;
3223:   }
3224:   snes->tolerancesset = PETSC_TRUE;
3225:   return(0);
3226: }

3228: /*@
3229:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3231:    Logically Collective on SNES

3233:    Input Parameters:
3234: +  snes - the SNES context
3235: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3237:    Options Database Keys:
3238: +    -snes_divergence_tolerance <divtol> - Sets divtol

3240:    Notes:
3241:    The default divergence tolerance is 1e4.

3243:    Level: intermediate

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

3247: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3248: @*/
3249: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3250: {

3255:   if (divtol != PETSC_DEFAULT) {
3256:     snes->divtol = divtol;
3257:   }
3258:   else {
3259:     snes->divtol = 1.0e4;
3260:   }
3261:   return(0);
3262: }

3264: /*@
3265:    SNESGetTolerances - Gets various parameters used in convergence tests.

3267:    Not Collective

3269:    Input Parameters:
3270: +  snes - the SNES context
3271: .  atol - absolute convergence tolerance
3272: .  rtol - relative convergence tolerance
3273: .  stol -  convergence tolerance in terms of the norm
3274:            of the change in the solution between steps
3275: .  maxit - maximum number of iterations
3276: -  maxf - maximum number of function evaluations

3278:    Notes:
3279:    The user can specify NULL for any parameter that is not needed.

3281:    Level: intermediate

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

3285: .seealso: SNESSetTolerances()
3286: @*/
3287: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3288: {
3291:   if (atol)  *atol  = snes->abstol;
3292:   if (rtol)  *rtol  = snes->rtol;
3293:   if (stol)  *stol  = snes->stol;
3294:   if (maxit) *maxit = snes->max_its;
3295:   if (maxf)  *maxf  = snes->max_funcs;
3296:   return(0);
3297: }

3299: /*@
3300:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3302:    Not Collective

3304:    Input Parameters:
3305: +  snes - the SNES context
3306: -  divtol - divergence tolerance

3308:    Level: intermediate

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

3312: .seealso: SNESSetDivergenceTolerance()
3313: @*/
3314: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3315: {
3318:   if (divtol) *divtol = snes->divtol;
3319:   return(0);
3320: }

3322: /*@
3323:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3325:    Logically Collective on SNES

3327:    Input Parameters:
3328: +  snes - the SNES context
3329: -  tol - tolerance

3331:    Options Database Key:
3332: .  -snes_trtol <tol> - Sets tol

3334:    Level: intermediate

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

3338: .seealso: SNESSetTolerances()
3339: @*/
3340: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3341: {
3345:   snes->deltatol = tol;
3346:   return(0);
3347: }

3349: /*
3350:    Duplicate the lg monitors for SNES from KSP; for some reason with
3351:    dynamic libraries things don't work under Sun4 if we just use
3352:    macros instead of functions
3353: */
3354: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3355: {

3360:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3361:   return(0);
3362: }

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

3369:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3370:   return(0);
3371: }

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

3375: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3376: {
3377:   PetscDrawLG      lg;
3378:   PetscErrorCode   ierr;
3379:   PetscReal        x,y,per;
3380:   PetscViewer      v = (PetscViewer)monctx;
3381:   static PetscReal prev; /* should be in the context */
3382:   PetscDraw        draw;

3386:   PetscViewerDrawGetDrawLG(v,0,&lg);
3387:   if (!n) {PetscDrawLGReset(lg);}
3388:   PetscDrawLGGetDraw(lg,&draw);
3389:   PetscDrawSetTitle(draw,"Residual norm");
3390:   x    = (PetscReal)n;
3391:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3392:   else y = -15.0;
3393:   PetscDrawLGAddPoint(lg,&x,&y);
3394:   if (n < 20 || !(n % 5) || snes->reason) {
3395:     PetscDrawLGDraw(lg);
3396:     PetscDrawLGSave(lg);
3397:   }

3399:   PetscViewerDrawGetDrawLG(v,1,&lg);
3400:   if (!n) {PetscDrawLGReset(lg);}
3401:   PetscDrawLGGetDraw(lg,&draw);
3402:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3403:    SNESMonitorRange_Private(snes,n,&per);
3404:   x    = (PetscReal)n;
3405:   y    = 100.0*per;
3406:   PetscDrawLGAddPoint(lg,&x,&y);
3407:   if (n < 20 || !(n % 5) || snes->reason) {
3408:     PetscDrawLGDraw(lg);
3409:     PetscDrawLGSave(lg);
3410:   }

3412:   PetscViewerDrawGetDrawLG(v,2,&lg);
3413:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3414:   PetscDrawLGGetDraw(lg,&draw);
3415:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3416:   x    = (PetscReal)n;
3417:   y    = (prev - rnorm)/prev;
3418:   PetscDrawLGAddPoint(lg,&x,&y);
3419:   if (n < 20 || !(n % 5) || snes->reason) {
3420:     PetscDrawLGDraw(lg);
3421:     PetscDrawLGSave(lg);
3422:   }

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

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

3444:    Collective on SNES

3446:    Input Parameters:
3447: +  snes - nonlinear solver context obtained from SNESCreate()
3448: .  iter - iteration number
3449: -  rnorm - relative norm of the residual

3451:    Notes:
3452:    This routine is called by the SNES implementations.
3453:    It does not typically need to be called by the user.

3455:    Level: developer

3457: .seealso: SNESMonitorSet()
3458: @*/
3459: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3460: {
3462:   PetscInt       i,n = snes->numbermonitors;

3465:   VecLockPush(snes->vec_sol);
3466:   for (i=0; i<n; i++) {
3467:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3468:   }
3469:   VecLockPop(snes->vec_sol);
3470:   return(0);
3471: }

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

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

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

3482: +    snes - the SNES context
3483: .    its - iteration number
3484: .    norm - 2-norm function value (may be estimated)
3485: -    mctx - [optional] monitoring context

3487:    Level: advanced

3489: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3490: M*/

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

3497:    Logically Collective on SNES

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

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

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

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

3524:    Level: intermediate

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

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

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

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

3552:    Logically Collective on SNES

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

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

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

3565:    Level: intermediate

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

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

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

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

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

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

3602:    Level: intermediate

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

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

3611:    Logically Collective on SNES

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

3619:    Level: advanced

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

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

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

3641: /*@
3642:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3644:    Not Collective

3646:    Input Parameter:
3647: .  snes - the SNES context

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

3653:    Options Database:
3654: .   -snes_converged_reason - prints the reason to standard out

3656:    Level: intermediate

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

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

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

3673: /*@
3674:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3676:    Not Collective

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

3683:    Level: intermediate

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

3696: /*@
3697:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3699:    Logically Collective on SNES

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

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

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

3717:    Level: intermediate

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

3721: .seealso: SNESGetConvergenceHistory()

3723: @*/
3724: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3725: {

3732:   if (!a) {
3733:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3734:     PetscCalloc1(na,&a);
3735:     PetscCalloc1(na,&its);

3737:     snes->conv_malloc = PETSC_TRUE;
3738:   }
3739:   snes->conv_hist       = a;
3740:   snes->conv_hist_its   = its;
3741:   snes->conv_hist_max   = na;
3742:   snes->conv_hist_len   = 0;
3743:   snes->conv_hist_reset = reset;
3744:   return(0);
3745: }

3747: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3748: #include <engine.h>   /* MATLAB include file */
3749: #include <mex.h>      /* MATLAB include file */

3751: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3752: {
3753:   mxArray   *mat;
3754:   PetscInt  i;
3755:   PetscReal *ar;

3758:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3759:   ar  = (PetscReal*) mxGetData(mat);
3760:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3761:   PetscFunctionReturn(mat);
3762: }
3763: #endif

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

3768:    Not Collective

3770:    Input Parameter:
3771: .  snes - iterative context obtained from SNESCreate()

3773:    Output Parameters:
3774: .  a   - array to hold history
3775: .  its - integer array holds the number of linear iterations (or
3776:          negative if not converged) for each solve.
3777: -  na  - size of a and its

3779:    Notes:
3780:     The calling sequence for this routine in Fortran is
3781: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

3787:    Level: intermediate

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

3791: .seealso: SNESSetConvergencHistory()

3793: @*/
3794: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
3795: {
3798:   if (a)   *a   = snes->conv_hist;
3799:   if (its) *its = snes->conv_hist_its;
3800:   if (na)  *na  = snes->conv_hist_len;
3801:   return(0);
3802: }

3804: /*@C
3805:   SNESSetUpdate - Sets the general-purpose update function called
3806:   at the beginning of every iteration of the nonlinear solve. Specifically
3807:   it is called just before the Jacobian is "evaluated".

3809:   Logically Collective on SNES

3811:   Input Parameters:
3812: . snes - The nonlinear solver context
3813: . func - The function

3815:   Calling sequence of func:
3816: . func (SNES snes, PetscInt step);

3818: . step - The current step of the iteration

3820:   Level: advanced

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

3825: .keywords: SNES, update

3827: .seealso SNESSetJacobian(), SNESSolve()
3828: @*/
3829: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
3830: {
3833:   snes->ops->update = func;
3834:   return(0);
3835: }

3837: /*
3838:    SNESScaleStep_Private - Scales a step so that its length is less than the
3839:    positive parameter delta.

3841:     Input Parameters:
3842: +   snes - the SNES context
3843: .   y - approximate solution of linear system
3844: .   fnorm - 2-norm of current function
3845: -   delta - trust region size

3847:     Output Parameters:
3848: +   gpnorm - predicted function norm at the new point, assuming local
3849:     linearization.  The value is zero if the step lies within the trust
3850:     region, and exceeds zero otherwise.
3851: -   ynorm - 2-norm of the step

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

3857: .keywords: SNES, nonlinear, scale, step
3858: */
3859: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
3860: {
3861:   PetscReal      nrm;
3862:   PetscScalar    cnorm;


3870:   VecNorm(y,NORM_2,&nrm);
3871:   if (nrm > *delta) {
3872:     nrm     = *delta/nrm;
3873:     *gpnorm = (1.0 - nrm)*(*fnorm);
3874:     cnorm   = nrm;
3875:     VecScale(y,cnorm);
3876:     *ynorm  = *delta;
3877:   } else {
3878:     *gpnorm = 0.0;
3879:     *ynorm  = nrm;
3880:   }
3881:   return(0);
3882: }

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

3887:    Collective on SNES

3889:    Parameter:
3890: +  snes - iterative context obtained from SNESCreate()
3891: -  viewer - the viewer to display the reason


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

3897:    Level: beginner

3899: .keywords: SNES, solve, linear system

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

3903: @*/
3904: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
3905: {
3907:   PetscBool      isAscii;

3910:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
3911:   if (isAscii) {
3912:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
3913:     if (snes->reason > 0) {
3914:       if (((PetscObject) snes)->prefix) {
3915:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3916:       } else {
3917:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3918:       }
3919:     } else {
3920:       if (((PetscObject) snes)->prefix) {
3921:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3922:       } else {
3923:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3924:       }
3925:     }
3926:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
3927:   }
3928:   return(0);
3929: }

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

3934:   Collective on SNES

3936:   Input Parameters:
3937: . snes   - the SNES object

3939:   Level: intermediate

3941: @*/
3942: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
3943: {
3944:   PetscErrorCode    ierr;
3945:   PetscViewer       viewer;
3946:   PetscBool         flg;
3947:   static PetscBool  incall = PETSC_FALSE;
3948:   PetscViewerFormat format;

3951:   if (incall) return(0);
3952:   incall = PETSC_TRUE;
3953:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
3954:   if (flg) {
3955:     PetscViewerPushFormat(viewer,format);
3956:     SNESReasonView(snes,viewer);
3957:     PetscViewerPopFormat(viewer);
3958:     PetscViewerDestroy(&viewer);
3959:   }
3960:   incall = PETSC_FALSE;
3961:   return(0);
3962: }

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

3968:    Collective on SNES

3970:    Input Parameters:
3971: +  snes - the SNES context
3972: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
3973: -  x - the solution vector.

3975:    Notes:
3976:    The user should initialize the vector,x, with the initial guess
3977:    for the nonlinear solve prior to calling SNESSolve.  In particular,
3978:    to employ an initial guess of zero, the user should explicitly set
3979:    this vector to zero by calling VecSet().

3981:    Level: beginner

3983: .keywords: SNES, nonlinear, solve

3985: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
3986: @*/
3987: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
3988: {
3989:   PetscErrorCode    ierr;
3990:   PetscBool         flg;
3991:   PetscInt          grid;
3992:   Vec               xcreated = NULL;
3993:   DM                dm;


4002:   {
4003:     PetscViewer       viewer;
4004:     PetscViewerFormat format;
4005:     PetscBool         flg;
4006:     static PetscBool  incall = PETSC_FALSE;

4008:     if (!incall) {
4009:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes), ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4010:       if (flg) {
4011:         PetscConvEst conv;
4012:         PetscReal    alpha; /* Convergence rate of the solution error in the L_2 norm */

4014:         incall = PETSC_TRUE;
4015:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4016:         PetscConvEstSetSolver(conv, snes);
4017:         PetscConvEstSetFromOptions(conv);
4018:         PetscConvEstSetUp(conv);
4019:         PetscConvEstGetConvRate(conv, &alpha);
4020:         PetscViewerPushFormat(viewer, format);
4021:         PetscConvEstRateView(conv, alpha, viewer);
4022:         PetscViewerPopFormat(viewer);
4023:         PetscViewerDestroy(&viewer);
4024:         PetscConvEstDestroy(&conv);
4025:         incall = PETSC_FALSE;
4026:       }
4027:     }
4028:   }
4029:   if (!x) {
4030:     SNESGetDM(snes,&dm);
4031:     DMCreateGlobalVector(dm,&xcreated);
4032:     x    = xcreated;
4033:   }
4034:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4039:     /* set solution vector */
4040:     if (!grid) {PetscObjectReference((PetscObject)x);}
4041:     VecDestroy(&snes->vec_sol);
4042:     snes->vec_sol = x;
4043:     SNESGetDM(snes,&dm);

4045:     /* set affine vector if provided */
4046:     if (b) { PetscObjectReference((PetscObject)b); }
4047:     VecDestroy(&snes->vec_rhs);
4048:     snes->vec_rhs = b;

4050:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4051:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4052:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4053:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4054:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4055:     }
4056:     DMShellSetGlobalVector(dm,snes->vec_sol);
4057:     SNESSetUp(snes);

4059:     if (!grid) {
4060:       if (snes->ops->computeinitialguess) {
4061:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4062:       }
4063:     }

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

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

4074:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4075:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4081:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4082:     if (snes->reason < 0) break;
4083:     if (grid <  snes->gridsequence) {
4084:       DM  fine;
4085:       Vec xnew;
4086:       Mat interp;

4088:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4089:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4090:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4091:       DMCreateGlobalVector(fine,&xnew);
4092:       MatInterpolate(interp,x,xnew);
4093:       DMInterpolate(snes->dm,interp,fine);
4094:       MatDestroy(&interp);
4095:       x    = xnew;

4097:       SNESReset(snes);
4098:       SNESSetDM(snes,fine);
4099:       DMDestroy(&fine);
4100:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4101:     }
4102:   }
4103:   SNESViewFromOptions(snes,NULL,"-snes_view");
4104:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4106:   VecDestroy(&xcreated);
4107:   PetscObjectSAWsBlock((PetscObject)snes);
4108:   return(0);
4109: }

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

4113: /*@C
4114:    SNESSetType - Sets the method for the nonlinear solver.

4116:    Collective on SNES

4118:    Input Parameters:
4119: +  snes - the SNES context
4120: -  type - a known method

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

4126:    Notes:
4127:    See "petsc/include/petscsnes.h" for available methods (for instance)
4128: +    SNESNEWTONLS - Newton's method with line search
4129:      (systems of nonlinear equations)
4130: .    SNESNEWTONTR - Newton's method with trust region
4131:      (systems of nonlinear equations)

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

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

4147:   Level: intermediate

4149: .keywords: SNES, set, type

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

4153: @*/
4154: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4155: {
4156:   PetscErrorCode ierr,(*r)(SNES);
4157:   PetscBool      match;


4163:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4164:   if (match) return(0);

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

4182:   PetscObjectChangeTypeName((PetscObject)snes,type);
4183:   (*r)(snes);
4184:   return(0);
4185: }

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

4190:    Not Collective

4192:    Input Parameter:
4193: .  snes - nonlinear solver context

4195:    Output Parameter:
4196: .  type - SNES method (a character string)

4198:    Level: intermediate

4200: .keywords: SNES, nonlinear, get, type, name
4201: @*/
4202: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4203: {
4207:   *type = ((PetscObject)snes)->type_name;
4208:   return(0);
4209: }

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

4214:   Logically Collective on SNES and Vec

4216:   Input Parameters:
4217: + snes - the SNES context obtained from SNESCreate()
4218: - u    - the solution vector

4220:   Level: beginner

4222: .keywords: SNES, set, solution
4223: @*/
4224: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4225: {
4226:   DM             dm;

4232:   PetscObjectReference((PetscObject) u);
4233:   VecDestroy(&snes->vec_sol);

4235:   snes->vec_sol = u;

4237:   SNESGetDM(snes, &dm);
4238:   DMShellSetGlobalVector(dm, u);
4239:   return(0);
4240: }

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

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

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

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

4254:    Level: intermediate

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

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

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

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

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

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

4281:    Level: advanced

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

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

4296: /*@C
4297:    SNESGetFunction - Returns the vector where the function is stored.

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

4301:    Input Parameter:
4302: .  snes - the SNES context

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

4309:    Level: advanced

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

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

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

4339: /*@C
4340:    SNESGetNGS - Returns the NGS function and context.

4342:    Input Parameter:
4343: .  snes - the SNES context

4345:    Output Parameter:
4346: +  f - the function (or NULL) see SNESNGSFunction for details
4347: -  ctx    - the function context (or NULL)

4349:    Level: advanced

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

4353: .seealso: SNESSetNGS(), SNESGetFunction()
4354: @*/

4356: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4357: {
4359:   DM             dm;

4363:   SNESGetDM(snes,&dm);
4364:   DMSNESGetNGS(dm,f,ctx);
4365:   return(0);
4366: }

4368: /*@C
4369:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4370:    SNES options in the database.

4372:    Logically Collective on SNES

4374:    Input Parameter:
4375: +  snes - the SNES context
4376: -  prefix - the prefix to prepend to all option names

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

4382:    Level: advanced

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

4386: .seealso: SNESSetFromOptions()
4387: @*/
4388: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4389: {

4394:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4395:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4396:   if (snes->linesearch) {
4397:     SNESGetLineSearch(snes,&snes->linesearch);
4398:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4399:   }
4400:   KSPSetOptionsPrefix(snes->ksp,prefix);
4401:   return(0);
4402: }

4404: /*@C
4405:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4406:    SNES options in the database.

4408:    Logically Collective on SNES

4410:    Input Parameters:
4411: +  snes - the SNES context
4412: -  prefix - the prefix to prepend to all option names

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

4418:    Level: advanced

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

4422: .seealso: SNESGetOptionsPrefix()
4423: @*/
4424: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4425: {

4430:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4431:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4432:   if (snes->linesearch) {
4433:     SNESGetLineSearch(snes,&snes->linesearch);
4434:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4435:   }
4436:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4437:   return(0);
4438: }

4440: /*@C
4441:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4442:    SNES options in the database.

4444:    Not Collective

4446:    Input Parameter:
4447: .  snes - the SNES context

4449:    Output Parameter:
4450: .  prefix - pointer to the prefix string used

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

4455:    Level: advanced

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

4459: .seealso: SNESAppendOptionsPrefix()
4460: @*/
4461: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4462: {

4467:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4468:   return(0);
4469: }


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

4475:    Not collective

4477:    Input Parameters:
4478: +  name_solver - name of a new user-defined solver
4479: -  routine_create - routine to create method context

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

4484:    Sample usage:
4485: .vb
4486:    SNESRegister("my_solver",MySolverCreate);
4487: .ve

4489:    Then, your solver can be chosen with the procedural interface via
4490: $     SNESSetType(snes,"my_solver")
4491:    or at runtime via the option
4492: $     -snes_type my_solver

4494:    Level: advanced

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

4498: .keywords: SNES, nonlinear, register

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

4502:   Level: advanced
4503: @*/
4504: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4505: {

4509:   PetscFunctionListAdd(&SNESList,sname,function);
4510:   return(0);
4511: }

4513: PetscErrorCode  SNESTestLocalMin(SNES snes)
4514: {
4516:   PetscInt       N,i,j;
4517:   Vec            u,uh,fh;
4518:   PetscScalar    value;
4519:   PetscReal      norm;

4522:   SNESGetSolution(snes,&u);
4523:   VecDuplicate(u,&uh);
4524:   VecDuplicate(u,&fh);

4526:   /* currently only works for sequential */
4527:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4528:   VecGetSize(u,&N);
4529:   for (i=0; i<N; i++) {
4530:     VecCopy(u,uh);
4531:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4532:     for (j=-10; j<11; j++) {
4533:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4534:       VecSetValue(uh,i,value,ADD_VALUES);
4535:       SNESComputeFunction(snes,uh,fh);
4536:       VecNorm(fh,NORM_2,&norm);
4537:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4538:       value = -value;
4539:       VecSetValue(uh,i,value,ADD_VALUES);
4540:     }
4541:   }
4542:   VecDestroy(&uh);
4543:   VecDestroy(&fh);
4544:   return(0);
4545: }

4547: /*@
4548:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4549:    computing relative tolerance for linear solvers within an inexact
4550:    Newton method.

4552:    Logically Collective on SNES

4554:    Input Parameters:
4555: +  snes - SNES context
4556: -  flag - PETSC_TRUE or PETSC_FALSE

4558:     Options Database:
4559: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4560: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4561: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4562: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4563: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4564: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4565: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4566: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4568:    Notes:
4569:    Currently, the default is to use a constant relative tolerance for
4570:    the inner linear solvers.  Alternatively, one can use the
4571:    Eisenstat-Walker method, where the relative convergence tolerance
4572:    is reset at each Newton iteration according progress of the nonlinear
4573:    solver.

4575:    Level: advanced

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

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

4583: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4584: @*/
4585: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4586: {
4590:   snes->ksp_ewconv = flag;
4591:   return(0);
4592: }

4594: /*@
4595:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4596:    for computing relative tolerance for linear solvers within an
4597:    inexact Newton method.

4599:    Not Collective

4601:    Input Parameter:
4602: .  snes - SNES context

4604:    Output Parameter:
4605: .  flag - PETSC_TRUE or PETSC_FALSE

4607:    Notes:
4608:    Currently, the default is to use a constant relative tolerance for
4609:    the inner linear solvers.  Alternatively, one can use the
4610:    Eisenstat-Walker method, where the relative convergence tolerance
4611:    is reset at each Newton iteration according progress of the nonlinear
4612:    solver.

4614:    Level: advanced

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

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

4622: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4623: @*/
4624: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4625: {
4629:   *flag = snes->ksp_ewconv;
4630:   return(0);
4631: }

4633: /*@
4634:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4635:    convergence criteria for the linear solvers within an inexact
4636:    Newton method.

4638:    Logically Collective on SNES

4640:    Input Parameters:
4641: +    snes - SNES context
4642: .    version - version 1, 2 (default is 2) or 3
4643: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4644: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4645: .    gamma - multiplicative factor for version 2 rtol computation
4646:              (0 <= gamma2 <= 1)
4647: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4648: .    alpha2 - power for safeguard
4649: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4651:    Note:
4652:    Version 3 was contributed by Luis Chacon, June 2006.

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

4656:    Level: advanced

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

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

4665: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4666: @*/
4667: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4668: {
4669:   SNESKSPEW *kctx;

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

4683:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4684:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4685:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4686:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4687:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4688:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4689:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4691:   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);
4692:   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);
4693:   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);
4694:   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);
4695:   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);
4696:   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);
4697:   return(0);
4698: }

4700: /*@
4701:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4702:    convergence criteria for the linear solvers within an inexact
4703:    Newton method.

4705:    Not Collective

4707:    Input Parameters:
4708:      snes - SNES context

4710:    Output Parameters:
4711: +    version - version 1, 2 (default is 2) or 3
4712: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4713: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4714: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
4715: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4716: .    alpha2 - power for safeguard
4717: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4719:    Level: advanced

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

4723: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
4724: @*/
4725: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
4726: {
4727:   SNESKSPEW *kctx;

4731:   kctx = (SNESKSPEW*)snes->kspconvctx;
4732:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
4733:   if (version)   *version   = kctx->version;
4734:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
4735:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
4736:   if (gamma)     *gamma     = kctx->gamma;
4737:   if (alpha)     *alpha     = kctx->alpha;
4738:   if (alpha2)    *alpha2    = kctx->alpha2;
4739:   if (threshold) *threshold = kctx->threshold;
4740:   return(0);
4741: }

4743:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4744: {
4746:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4747:   PetscReal      rtol  = PETSC_DEFAULT,stol;

4750:   if (!snes->ksp_ewconv) return(0);
4751:   if (!snes->iter) {
4752:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
4753:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
4754:   }
4755:   else {
4756:     if (kctx->version == 1) {
4757:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
4758:       if (rtol < 0.0) rtol = -rtol;
4759:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
4760:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4761:     } else if (kctx->version == 2) {
4762:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4763:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
4764:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4765:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
4766:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4767:       /* safeguard: avoid sharp decrease of rtol */
4768:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
4769:       stol = PetscMax(rtol,stol);
4770:       rtol = PetscMin(kctx->rtol_0,stol);
4771:       /* safeguard: avoid oversolving */
4772:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
4773:       stol = PetscMax(rtol,stol);
4774:       rtol = PetscMin(kctx->rtol_0,stol);
4775:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
4776:   }
4777:   /* safeguard: avoid rtol greater than one */
4778:   rtol = PetscMin(rtol,kctx->rtol_max);
4779:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
4780:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
4781:   return(0);
4782: }

4784: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4785: {
4787:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4788:   PCSide         pcside;
4789:   Vec            lres;

4792:   if (!snes->ksp_ewconv) return(0);
4793:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
4794:   kctx->norm_last = snes->norm;
4795:   if (kctx->version == 1) {
4796:     PC        pc;
4797:     PetscBool isNone;

4799:     KSPGetPC(ksp, &pc);
4800:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
4801:     KSPGetPCSide(ksp,&pcside);
4802:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
4803:       /* KSP residual is true linear residual */
4804:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
4805:     } else {
4806:       /* KSP residual is preconditioned residual */
4807:       /* compute true linear residual norm */
4808:       VecDuplicate(b,&lres);
4809:       MatMult(snes->jacobian,x,lres);
4810:       VecAYPX(lres,-1.0,b);
4811:       VecNorm(lres,NORM_2,&kctx->lresid_last);
4812:       VecDestroy(&lres);
4813:     }
4814:   }
4815:   return(0);
4816: }

4818: /*@
4819:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

4823:    Input Parameter:
4824: .  snes - the SNES context

4826:    Output Parameter:
4827: .  ksp - the KSP context

4829:    Notes:
4830:    The user can then directly manipulate the KSP context to set various
4831:    options, etc.  Likewise, the user can then extract and manipulate the
4832:    PC contexts as well.

4834:    Level: beginner

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

4838: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
4839: @*/
4840: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
4841: {


4848:   if (!snes->ksp) {
4849:     PetscBool monitor = PETSC_FALSE;

4851:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
4852:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
4853:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

4858:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
4859:     if (monitor) {
4860:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
4861:     }
4862:     monitor = PETSC_FALSE;
4863:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
4864:     if (monitor) {
4865:       PetscObject *objs;
4866:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
4867:       objs[0] = (PetscObject) snes;
4868:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
4869:     }
4870:   }
4871:   *ksp = snes->ksp;
4872:   return(0);
4873: }


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

4880:    Logically Collective on SNES

4882:    Input Parameters:
4883: +  snes - the nonlinear solver context
4884: -  dm - the dm, cannot be NULL

4886:    Level: intermediate

4888: .seealso: SNESGetDM(), SNESHasDM(), KSPSetDM(), KSPGetDM()
4889: @*/
4890: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
4891: {
4893:   KSP            ksp;
4894:   DMSNES         sdm;

4899:   PetscObjectReference((PetscObject)dm);
4900:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
4901:     if (snes->dm->dmsnes && !dm->dmsnes) {
4902:       DMCopyDMSNES(snes->dm,dm);
4903:       DMGetDMSNES(snes->dm,&sdm);
4904:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
4905:     }
4906:     DMDestroy(&snes->dm);
4907:   }
4908:   snes->dm     = dm;
4909:   snes->dmAuto = PETSC_FALSE;

4911:   SNESGetKSP(snes,&ksp);
4912:   KSPSetDM(ksp,dm);
4913:   KSPSetDMActive(ksp,PETSC_FALSE);
4914:   if (snes->npc) {
4915:     SNESSetDM(snes->npc, snes->dm);
4916:     SNESSetNPCSide(snes,snes->npcside);
4917:   }
4918:   return(0);
4919: }

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

4924:    Not Collective but DM obtained is parallel on SNES

4926:    Input Parameter:
4927: . snes - the preconditioner context

4929:    Output Parameter:
4930: .  dm - the dm

4932:    Level: intermediate

4934: .seealso: SNESSetDM(), SNESHasDM(), KSPSetDM(), KSPGetDM()
4935: @*/
4936: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
4937: {

4942:   if (!snes->dm) {
4943:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
4944:     snes->dmAuto = PETSC_TRUE;
4945:   }
4946:   *dm = snes->dm;
4947:   return(0);
4948: }


4951: /*@
4952:    SNESHasDM - Whether snes has dm

4954:    Not collective but all processes must return the same value

4956:    Input Parameter:
4957: . snes - the nonlinear solver object

4959:    Output Parameter:
4960: .  hasdm - a flag indicates whether there is dm in snes

4962:    Level: intermediate

4964: .seealso: SNESGetDM(), SNESSetDM(), KSPSetDM(), KSPGetDM()
4965: @*/
4966: PetscErrorCode  SNESHasDM(SNES snes,PetscBool *hasdm)
4967: {
4971:   if (snes->dm) *hasdm = PETSC_TRUE;
4972:   else *hasdm = PETSC_FALSE;
4973:   return(0);
4974: }

4976: /*@
4977:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

4979:   Collective on SNES

4981:   Input Parameters:
4982: + snes - iterative context obtained from SNESCreate()
4983: - pc   - the preconditioner object

4985:   Notes:
4986:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
4987:   to configure it using the API).

4989:   Level: developer

4991: .keywords: SNES, set, precondition
4992: .seealso: SNESGetNPC(), SNESHasNPC()
4993: @*/
4994: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
4995: {

5002:   PetscObjectReference((PetscObject) pc);
5003:   SNESDestroy(&snes->npc);
5004:   snes->npc = pc;
5005:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5006:   return(0);
5007: }

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

5012:   Not Collective

5014:   Input Parameter:
5015: . snes - iterative context obtained from SNESCreate()

5017:   Output Parameter:
5018: . pc - preconditioner context

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

5022:   Level: developer

5024: .keywords: SNES, get, preconditioner
5025: .seealso: SNESSetNPC(), SNESHasNPC()
5026: @*/
5027: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5028: {
5030:   const char     *optionsprefix;

5035:   if (!snes->npc) {
5036:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5037:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5038:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5039:     SNESGetOptionsPrefix(snes,&optionsprefix);
5040:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5041:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5042:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5043:   }
5044:   *pc = snes->npc;
5045:   return(0);
5046: }

5048: /*@
5049:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5051:   Not Collective

5053:   Input Parameter:
5054: . snes - iterative context obtained from SNESCreate()

5056:   Output Parameter:
5057: . has_npc - whether the SNES has an NPC or not

5059:   Level: developer

5061: .keywords: SNES, has, preconditioner
5062: .seealso: SNESSetNPC(), SNESGetNPC()
5063: @*/
5064: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5065: {
5068:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5069:   return(0);
5070: }

5072: /*@
5073:     SNESSetNPCSide - Sets the preconditioning side.

5075:     Logically Collective on SNES

5077:     Input Parameter:
5078: .   snes - iterative context obtained from SNESCreate()

5080:     Output Parameter:
5081: .   side - the preconditioning side, where side is one of
5082: .vb
5083:       PC_LEFT - left preconditioning
5084:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5085: .ve

5087:     Options Database Keys:
5088: .   -snes_pc_side <right,left>

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

5092:     Level: intermediate

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

5096: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5097: @*/
5098: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5099: {
5103:   snes->npcside= side;
5104:   return(0);
5105: }

5107: /*@
5108:     SNESGetNPCSide - Gets the preconditioning side.

5110:     Not Collective

5112:     Input Parameter:
5113: .   snes - iterative context obtained from SNESCreate()

5115:     Output Parameter:
5116: .   side - the preconditioning side, where side is one of
5117: .vb
5118:       PC_LEFT - left preconditioning
5119:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5120: .ve

5122:     Level: intermediate

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

5126: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5127: @*/
5128: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5129: {
5133:   *side = snes->npcside;
5134:   return(0);
5135: }

5137: /*@
5138:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5140:   Collective on SNES

5142:   Input Parameters:
5143: + snes - iterative context obtained from SNESCreate()
5144: - linesearch   - the linesearch object

5146:   Notes:
5147:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5148:   to configure it using the API).

5150:   Level: developer

5152: .keywords: SNES, set, linesearch
5153: .seealso: SNESGetLineSearch()
5154: @*/
5155: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5156: {

5163:   PetscObjectReference((PetscObject) linesearch);
5164:   SNESLineSearchDestroy(&snes->linesearch);

5166:   snes->linesearch = linesearch;

5168:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5169:   return(0);
5170: }

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

5176:   Not Collective

5178:   Input Parameter:
5179: . snes - iterative context obtained from SNESCreate()

5181:   Output Parameter:
5182: . linesearch - linesearch context

5184:   Level: beginner

5186: .keywords: SNES, get, linesearch
5187: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5188: @*/
5189: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5190: {
5192:   const char     *optionsprefix;

5197:   if (!snes->linesearch) {
5198:     SNESGetOptionsPrefix(snes, &optionsprefix);
5199:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5200:     SNESLineSearchSetSNES(snes->linesearch, snes);
5201:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5202:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5203:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5204:   }
5205:   *linesearch = snes->linesearch;
5206:   return(0);
5207: }

5209: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5210: #include <mex.h>

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

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

5217:    Collective on SNES

5219:    Input Parameters:
5220: +  snes - the SNES context
5221: -  x - input vector

5223:    Output Parameter:
5224: .  y - function vector, as set by SNESSetFunction()

5226:    Notes:
5227:    SNESComputeFunction() is typically used within nonlinear solvers
5228:    implementations, so most users would not generally call this routine
5229:    themselves.

5231:    Level: developer

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

5235: .seealso: SNESSetFunction(), SNESGetFunction()
5236: */
5237: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5238: {
5239:   PetscErrorCode    ierr;
5240:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5241:   int               nlhs  = 1,nrhs = 5;
5242:   mxArray           *plhs[1],*prhs[5];
5243:   long long int     lx = 0,ly = 0,ls = 0;


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

5254:   PetscMemcpy(&ls,&snes,sizeof(snes));
5255:   PetscMemcpy(&lx,&x,sizeof(x));
5256:   PetscMemcpy(&ly,&y,sizeof(x));
5257:   prhs[0] = mxCreateDoubleScalar((double)ls);
5258:   prhs[1] = mxCreateDoubleScalar((double)lx);
5259:   prhs[2] = mxCreateDoubleScalar((double)ly);
5260:   prhs[3] = mxCreateString(sctx->funcname);
5261:   prhs[4] = sctx->ctx;
5262:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");
5263:   mxGetScalar(plhs[0]);
5264:   mxDestroyArray(prhs[0]);
5265:   mxDestroyArray(prhs[1]);
5266:   mxDestroyArray(prhs[2]);
5267:   mxDestroyArray(prhs[3]);
5268:   mxDestroyArray(plhs[0]);
5269:   return(0);
5270: }

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

5277:    Logically Collective on SNES

5279:    Input Parameters:
5280: +  snes - the SNES context
5281: .  r - vector to store function value
5282: -  f - function evaluation routine

5284:    Notes:
5285:    The Newton-like methods typically solve linear systems of the form
5286: $      f'(x) x = -f(x),
5287:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5289:    Level: beginner

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

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

5295: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5296: */
5297: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5298: {
5299:   PetscErrorCode    ierr;
5300:   SNESMatlabContext *sctx;

5303:   /* currently sctx is memory bleed */
5304:   PetscNew(&sctx);
5305:   PetscStrallocpy(f,&sctx->funcname);
5306:   /*
5307:      This should work, but it doesn't
5308:   sctx->ctx = ctx;
5309:   mexMakeArrayPersistent(sctx->ctx);
5310:   */
5311:   sctx->ctx = mxDuplicateArray(ctx);
5312:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5313:   return(0);
5314: }

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

5319:    Collective on SNES

5321:    Input Parameters:
5322: +  snes - the SNES context
5323: .  x - input vector
5324: .  A, B - the matrices
5325: -  ctx - user context

5327:    Level: developer

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

5331: .seealso: SNESSetFunction(), SNESGetFunction()
5332: @*/
5333: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5334: {
5335:   PetscErrorCode    ierr;
5336:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5337:   int               nlhs  = 2,nrhs = 6;
5338:   mxArray           *plhs[2],*prhs[6];
5339:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


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

5347:   PetscMemcpy(&ls,&snes,sizeof(snes));
5348:   PetscMemcpy(&lx,&x,sizeof(x));
5349:   PetscMemcpy(&lA,A,sizeof(x));
5350:   PetscMemcpy(&lB,B,sizeof(x));
5351:   prhs[0] = mxCreateDoubleScalar((double)ls);
5352:   prhs[1] = mxCreateDoubleScalar((double)lx);
5353:   prhs[2] = mxCreateDoubleScalar((double)lA);
5354:   prhs[3] = mxCreateDoubleScalar((double)lB);
5355:   prhs[4] = mxCreateString(sctx->funcname);
5356:   prhs[5] = sctx->ctx;
5357:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5358:   mxGetScalar(plhs[0]);
5359:   mxDestroyArray(prhs[0]);
5360:   mxDestroyArray(prhs[1]);
5361:   mxDestroyArray(prhs[2]);
5362:   mxDestroyArray(prhs[3]);
5363:   mxDestroyArray(prhs[4]);
5364:   mxDestroyArray(plhs[0]);
5365:   mxDestroyArray(plhs[1]);
5366:   return(0);
5367: }

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

5374:    Logically Collective on SNES

5376:    Input Parameters:
5377: +  snes - the SNES context
5378: .  A,B - Jacobian matrices
5379: .  J - function evaluation routine
5380: -  ctx - user context

5382:    Level: developer

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

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

5388: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5389: */
5390: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5391: {
5392:   PetscErrorCode    ierr;
5393:   SNESMatlabContext *sctx;

5396:   /* currently sctx is memory bleed */
5397:   PetscNew(&sctx);
5398:   PetscStrallocpy(J,&sctx->funcname);
5399:   /*
5400:      This should work, but it doesn't
5401:   sctx->ctx = ctx;
5402:   mexMakeArrayPersistent(sctx->ctx);
5403:   */
5404:   sctx->ctx = mxDuplicateArray(ctx);
5405:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5406:   return(0);
5407: }

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

5412:    Collective on SNES

5414: .seealso: SNESSetFunction(), SNESGetFunction()
5415: @*/
5416: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5417: {
5418:   PetscErrorCode    ierr;
5419:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5420:   int               nlhs  = 1,nrhs = 6;
5421:   mxArray           *plhs[1],*prhs[6];
5422:   long long int     lx = 0,ls = 0;
5423:   Vec               x  = snes->vec_sol;


5428:   PetscMemcpy(&ls,&snes,sizeof(snes));
5429:   PetscMemcpy(&lx,&x,sizeof(x));
5430:   prhs[0] = mxCreateDoubleScalar((double)ls);
5431:   prhs[1] = mxCreateDoubleScalar((double)it);
5432:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5433:   prhs[3] = mxCreateDoubleScalar((double)lx);
5434:   prhs[4] = mxCreateString(sctx->funcname);
5435:   prhs[5] = sctx->ctx;
5436:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5437:   mxGetScalar(plhs[0]);
5438:   mxDestroyArray(prhs[0]);
5439:   mxDestroyArray(prhs[1]);
5440:   mxDestroyArray(prhs[2]);
5441:   mxDestroyArray(prhs[3]);
5442:   mxDestroyArray(prhs[4]);
5443:   mxDestroyArray(plhs[0]);
5444:   return(0);
5445: }

5447: /*
5448:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5450:    Level: developer

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

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

5456: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5457: */
5458: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5459: {
5460:   PetscErrorCode    ierr;
5461:   SNESMatlabContext *sctx;

5464:   /* currently sctx is memory bleed */
5465:   PetscNew(&sctx);
5466:   PetscStrallocpy(f,&sctx->funcname);
5467:   /*
5468:      This should work, but it doesn't
5469:   sctx->ctx = ctx;
5470:   mexMakeArrayPersistent(sctx->ctx);
5471:   */
5472:   sctx->ctx = mxDuplicateArray(ctx);
5473:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5474:   return(0);
5475: }

5477: #endif