Actual source code: snes.c

petsc-master 2017-09-24
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_force_iteration <force> - force SNESSolve() to take at least one iteration
710: .  -snes_max_it <max_it> - maximum number of iterations
711: .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
712: .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
713: .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
714: .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
715: .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
716: .  -snes_trtol <trtol> - trust region tolerance
717: .  -snes_no_convergence_test - skip convergence test in nonlinear
718:                                solver; hence iterations will continue until max_it
719:                                or some other criterion is reached. Saves expense
720:                                of convergence test
721: .  -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
722: .  -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
723: .  -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
724: .  -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
725: .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
726: .  -snes_monitor_lg_range - plots residual norm at each iteration
727: .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
728: .  -snes_fd_color - use finite differences with coloring to compute Jacobian
729: .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
730: -  -snes_converged_reason - print the reason for convergence/divergence after each solve

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

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

746:    Level: beginner

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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



880:   flg  = PETSC_FALSE;
881:   PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);
882:   if (flg) {
883:     void    *functx;
884:     DM      dm;
885:     DMSNES  sdm;
886:     SNESGetDM(snes,&dm);
887:     DMGetDMSNES(dm,&sdm);
888:     sdm->jacobianctx = NULL;
889:     SNESGetFunction(snes,NULL,NULL,&functx);
890:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);
891:     PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");
892:   }

894:   flg  = PETSC_FALSE;
895:   PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);
896:   if (flg) {
897:     SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);
898:   }

900:   flg  = PETSC_FALSE;
901:   PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL);
902:   if (flg) {
903:     DM             dm;
904:     DMSNES         sdm;
905:     SNESGetDM(snes,&dm);
906:     DMGetDMSNES(dm,&sdm);
907:     sdm->jacobianctx = NULL;
908:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,0);
909:     PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n");
910:   }

912:   flg  = PETSC_FALSE;
913:   PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf_operator,&flg);
914:   if (flg && snes->mf_operator) {
915:     snes->mf_operator = PETSC_TRUE;
916:     snes->mf          = PETSC_TRUE;
917:   }
918:   flg  = PETSC_FALSE;
919:   PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","SNESSetUseMatrixFree",PETSC_FALSE,&snes->mf,&flg);
920:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
921:   PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,0);

923:   flg  = PETSC_FALSE;
924:   SNESGetNPCSide(snes,&pcside);
925:   PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);
926:   if (flg) {SNESSetNPCSide(snes,pcside);}

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

951:   for (i = 0; i < numberofsetfromoptions; i++) {
952:     (*othersetfromoptions[i])(snes);
953:   }

955:   if (snes->ops->setfromoptions) {
956:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
957:   }

959:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
960:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
961:   PetscOptionsEnd();

963:   if (!snes->linesearch) {
964:     SNESGetLineSearch(snes, &snes->linesearch);
965:   }
966:   SNESLineSearchSetFromOptions(snes->linesearch);

968:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
969:   KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
970:   KSPSetFromOptions(snes->ksp);

972:   /* if someone has set the SNES NPC type, create it. */
973:   SNESGetOptionsPrefix(snes, &optionsprefix);
974:   PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset);
975:   if (pcset && (!snes->npc)) {
976:     SNESGetNPC(snes, &snes->npc);
977:   }
978:   return(0);
979: }

981: /*@C
982:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
983:    the nonlinear solvers.

985:    Logically Collective on SNES

987:    Input Parameters:
988: +  snes - the SNES context
989: .  compute - function to compute the context
990: -  destroy - function to destroy the context

992:    Level: intermediate

994:    Notes:
995:    This function is currently not available from Fortran.

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

999: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
1000: @*/
1001: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
1002: {
1005:   snes->ops->usercompute = compute;
1006:   snes->ops->userdestroy = destroy;
1007:   return(0);
1008: }

1010: /*@
1011:    SNESSetApplicationContext - Sets the optional user-defined context for
1012:    the nonlinear solvers.

1014:    Logically Collective on SNES

1016:    Input Parameters:
1017: +  snes - the SNES context
1018: -  usrP - optional user context

1020:    Level: intermediate

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

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

1027: .seealso: SNESGetApplicationContext()
1028: @*/
1029: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
1030: {
1032:   KSP            ksp;

1036:   SNESGetKSP(snes,&ksp);
1037:   KSPSetApplicationContext(ksp,usrP);
1038:   snes->user = usrP;
1039:   return(0);
1040: }

1042: /*@
1043:    SNESGetApplicationContext - Gets the user-defined context for the
1044:    nonlinear solvers.

1046:    Not Collective

1048:    Input Parameter:
1049: .  snes - SNES context

1051:    Output Parameter:
1052: .  usrP - user context

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

1057:    Level: intermediate

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

1061: .seealso: SNESSetApplicationContext()
1062: @*/
1063: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1064: {
1067:   *(void**)usrP = snes->user;
1068:   return(0);
1069: }

1071: /*@
1072:    SNESSetUseMatrixFree - indicates that SNES should use matrix free finite difference matrix vector products internally to apply
1073:                           the Jacobian.

1075:    Collective on SNES

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

1082:    Options Database:
1083: + -snes_mf - use matrix free for both the mat and pmat operator
1084: - -snes_mf_operator - use matrix free only for the mat operator

1086:    Level: intermediate

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

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

1102: /*@
1103:    SNESGetUseMatrixFree - indicates if the SNES uses matrix free finite difference matrix vector products to apply
1104:                           the Jacobian.

1106:    Collective on SNES

1108:    Input Parameter:
1109: .  snes - SNES context

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

1115:    Options Database:
1116: + -snes_mf - use matrix free for both the mat and pmat operator
1117: - -snes_mf_operator - use matrix free only for the mat operator

1119:    Level: intermediate

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

1123: .seealso:   SNESSetUseMatrixFree(), MatCreateSNESMF()
1124: @*/
1125: PetscErrorCode  SNESGetUseMatrixFree(SNES snes,PetscBool *mf_operator,PetscBool *mf)
1126: {
1129:   if (mf)          *mf          = snes->mf;
1130:   if (mf_operator) *mf_operator = snes->mf_operator;
1131:   return(0);
1132: }

1134: /*@
1135:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1136:    at this time.

1138:    Not Collective

1140:    Input Parameter:
1141: .  snes - SNES context

1143:    Output Parameter:
1144: .  iter - iteration number

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

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

1160:    Level: intermediate

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

1164: .seealso:   SNESGetLinearSolveIterations()
1165: @*/
1166: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1167: {
1171:   *iter = snes->iter;
1172:   return(0);
1173: }

1175: /*@
1176:    SNESSetIterationNumber - Sets the current iteration number.

1178:    Not Collective

1180:    Input Parameter:
1181: .  snes - SNES context
1182: .  iter - iteration number

1184:    Level: developer

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

1188: .seealso:   SNESGetLinearSolveIterations()
1189: @*/
1190: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1191: {

1196:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1197:   snes->iter = iter;
1198:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1199:   return(0);
1200: }

1202: /*@
1203:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1204:    attempted by the nonlinear solver.

1206:    Not Collective

1208:    Input Parameter:
1209: .  snes - SNES context

1211:    Output Parameter:
1212: .  nfails - number of unsuccessful steps attempted

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

1217:    Level: intermediate

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

1221: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1222:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1223: @*/
1224: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1225: {
1229:   *nfails = snes->numFailures;
1230:   return(0);
1231: }

1233: /*@
1234:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1235:    attempted by the nonlinear solver before it gives up.

1237:    Not Collective

1239:    Input Parameters:
1240: +  snes     - SNES context
1241: -  maxFails - maximum of unsuccessful steps

1243:    Level: intermediate

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

1247: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1248:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1249: @*/
1250: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1251: {
1254:   snes->maxFailures = maxFails;
1255:   return(0);
1256: }

1258: /*@
1259:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1260:    attempted by the nonlinear solver before it gives up.

1262:    Not Collective

1264:    Input Parameter:
1265: .  snes     - SNES context

1267:    Output Parameter:
1268: .  maxFails - maximum of unsuccessful steps

1270:    Level: intermediate

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

1274: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1275:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1277: @*/
1278: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1279: {
1283:   *maxFails = snes->maxFailures;
1284:   return(0);
1285: }

1287: /*@
1288:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1289:      done by SNES.

1291:    Not Collective

1293:    Input Parameter:
1294: .  snes     - SNES context

1296:    Output Parameter:
1297: .  nfuncs - number of evaluations

1299:    Level: intermediate

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

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

1305: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1306: @*/
1307: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1308: {
1312:   *nfuncs = snes->nfuncs;
1313:   return(0);
1314: }

1316: /*@
1317:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1318:    linear solvers.

1320:    Not Collective

1322:    Input Parameter:
1323: .  snes - SNES context

1325:    Output Parameter:
1326: .  nfails - number of failed solves

1328:    Level: intermediate

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

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

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

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

1349: /*@
1350:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1351:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1353:    Logically Collective on SNES

1355:    Input Parameters:
1356: +  snes     - SNES context
1357: -  maxFails - maximum allowed linear solve failures

1359:    Level: intermediate

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

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

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

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

1379: /*@
1380:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1381:      are allowed before SNES terminates

1383:    Not Collective

1385:    Input Parameter:
1386: .  snes     - SNES context

1388:    Output Parameter:
1389: .  maxFails - maximum of unsuccessful solves allowed

1391:    Level: intermediate

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

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

1397: .seealso: SNESGetLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(),
1398: @*/
1399: PetscErrorCode  SNESGetMaxLinearSolveFailures(SNES snes, PetscInt *maxFails)
1400: {
1404:   *maxFails = snes->maxLinearSolveFailures;
1405:   return(0);
1406: }

1408: /*@
1409:    SNESGetLinearSolveIterations - Gets the total number of linear iterations
1410:    used by the nonlinear solver.

1412:    Not Collective

1414:    Input Parameter:
1415: .  snes - SNES context

1417:    Output Parameter:
1418: .  lits - number of linear iterations

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

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

1426:    Level: intermediate

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

1430: .seealso:  SNESGetIterationNumber(), SNESGetLinearSolveFailures(), SNESGetMaxLinearSolveFailures(), SNESSetCountersReset()
1431: @*/
1432: PetscErrorCode  SNESGetLinearSolveIterations(SNES snes,PetscInt *lits)
1433: {
1437:   *lits = snes->linear_its;
1438:   return(0);
1439: }

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

1445:    Logically Collective on SNES

1447:    Input Parameter:
1448: +  snes - SNES context
1449: -  reset - whether to reset the counters or not

1451:    Notes:
1452:    This defaults to PETSC_TRUE

1454:    Level: developer

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

1458: .seealso:  SNESGetNumberFunctionEvals(), SNESGetLinearSolveIterations(), SNESGetNPC()
1459: @*/
1460: PetscErrorCode  SNESSetCountersReset(SNES snes,PetscBool reset)
1461: {
1465:   snes->counters_reset = reset;
1466:   return(0);
1467: }


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

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

1475:    Input Parameters:
1476: +  snes - the SNES context
1477: -  ksp - the KSP context

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

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

1486:    Level: developer

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

1490: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1491: @*/
1492: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1493: {

1500:   PetscObjectReference((PetscObject)ksp);
1501:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1502:   snes->ksp = ksp;
1503:   return(0);
1504: }

1506: /* -----------------------------------------------------------*/
1507: /*@
1508:    SNESCreate - Creates a nonlinear solver context.

1510:    Collective on MPI_Comm

1512:    Input Parameters:
1513: .  comm - MPI communicator

1515:    Output Parameter:
1516: .  outsnes - the new SNES context

1518:    Options Database Keys:
1519: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1520:                and no preconditioning matrix
1521: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1522:                products, and a user-provided preconditioning matrix
1523:                as set by SNESSetJacobian()
1524: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1526:    Level: beginner

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

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

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

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

1541: @*/
1542: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1543: {
1545:   SNES           snes;
1546:   SNESKSPEW      *kctx;

1550:   *outsnes = NULL;
1551:   SNESInitializePackage();

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

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

1614:   snes->mf          = PETSC_FALSE;
1615:   snes->mf_operator = PETSC_FALSE;
1616:   snes->mf_version  = 1;

1618:   snes->numLinearSolveFailures = 0;
1619:   snes->maxLinearSolveFailures = 1;

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

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

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

1629:   snes->kspconvctx  = (void*)kctx;
1630:   kctx->version     = 2;
1631:   kctx->rtol_0      = .3; /* Eisenstat and Walker suggest rtol_0=.5, but
1632:                              this was too large for some test cases */
1633:   kctx->rtol_last   = 0.0;
1634:   kctx->rtol_max    = .9;
1635:   kctx->gamma       = 1.0;
1636:   kctx->alpha       = .5*(1.0 + PetscSqrtReal(5.0));
1637:   kctx->alpha2      = kctx->alpha;
1638:   kctx->threshold   = .1;
1639:   kctx->lresid_last = 0.0;
1640:   kctx->norm_last   = 0.0;

1642:   *outsnes = snes;
1643:   return(0);
1644: }

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

1649:      Synopsis:
1650:      #include "petscsnes.h"
1651:      PetscErrorCode SNESFunction(SNES snes,Vec x,Vec f,void *ctx);

1653:      Input Parameters:
1654: +     snes - the SNES context
1655: .     x    - state at which to evaluate residual
1656: -     ctx     - optional user-defined function context, passed in with SNESSetFunction()

1658:      Output Parameter:
1659: .     f  - vector to put residual (function value)

1661:    Level: intermediate

1663: .seealso:   SNESSetFunction(), SNESGetFunction()
1664: M*/

1666: /*@C
1667:    SNESSetFunction - Sets the function evaluation routine and function
1668:    vector for use by the SNES routines in solving systems of nonlinear
1669:    equations.

1671:    Logically Collective on SNES

1673:    Input Parameters:
1674: +  snes - the SNES context
1675: .  r - vector to store function value
1676: .  f - function evaluation routine; see SNESFunction for calling sequence details
1677: -  ctx - [optional] user-defined context for private data for the
1678:          function evaluation routine (may be NULL)

1680:    Notes:
1681:    The Newton-like methods typically solve linear systems of the form
1682: $      f'(x) x = -f(x),
1683:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

1685:    Level: beginner

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

1689: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetPicard(), SNESFunction
1690: @*/
1691: PetscErrorCode  SNESSetFunction(SNES snes,Vec r,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1692: {
1694:   DM             dm;

1698:   if (r) {
1701:     PetscObjectReference((PetscObject)r);
1702:     VecDestroy(&snes->vec_func);

1704:     snes->vec_func = r;
1705:   }
1706:   SNESGetDM(snes,&dm);
1707:   DMSNESSetFunction(dm,f,ctx);
1708:   return(0);
1709: }


1712: /*@C
1713:    SNESSetInitialFunction - Sets the function vector to be used as the
1714:    function norm at the initialization of the method.  In some
1715:    instances, the user has precomputed the function before calling
1716:    SNESSolve.  This function allows one to avoid a redundant call
1717:    to SNESComputeFunction in that case.

1719:    Logically Collective on SNES

1721:    Input Parameters:
1722: +  snes - the SNES context
1723: -  f - vector to store function value

1725:    Notes:
1726:    This should not be modified during the solution procedure.

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

1730:    Level: developer

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

1734: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1735: @*/
1736: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1737: {
1739:   Vec            vec_func;

1745:   if (snes->npcside== PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1746:     snes->vec_func_init_set = PETSC_FALSE;
1747:     return(0);
1748:   }
1749:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1750:   VecCopy(f, vec_func);

1752:   snes->vec_func_init_set = PETSC_TRUE;
1753:   return(0);
1754: }

1756: /*@
1757:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1758:    of the SNES method.

1760:    Logically Collective on SNES

1762:    Input Parameters:
1763: +  snes - the SNES context
1764: -  normschedule - the frequency of norm computation

1766:    Options Database Key:
1767: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1778:    Level: developer

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

1782: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1783: @*/
1784: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1785: {
1788:   snes->normschedule = normschedule;
1789:   return(0);
1790: }


1793: /*@
1794:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1795:    of the SNES method.

1797:    Logically Collective on SNES

1799:    Input Parameters:
1800: +  snes - the SNES context
1801: -  normschedule - the type of the norm used

1803:    Level: advanced

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

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


1818: /*@
1819:   SNESSetFunctionNorm - Sets the last computed residual norm.

1821:   Logically Collective on SNES

1823:   Input Parameters:
1824: + snes - the SNES context

1826: - normschedule - the frequency of norm computation

1828:   Level: developer

1830: .keywords: SNES, nonlinear, set, function, norm, type
1831: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1832: @*/
1833: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1834: {
1837:   snes->norm = norm;
1838:   return(0);
1839: }

1841: /*@
1842:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1844:   Not Collective

1846:   Input Parameter:
1847: . snes - the SNES context

1849:   Output Parameter:
1850: . norm - the last computed residual norm

1852:   Level: developer

1854: .keywords: SNES, nonlinear, set, function, norm, type
1855: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1856: @*/
1857: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1858: {
1862:   *norm = snes->norm;
1863:   return(0);
1864: }

1866: /*@C
1867:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1868:    of the SNES method.

1870:    Logically Collective on SNES

1872:    Input Parameters:
1873: +  snes - the SNES context
1874: -  normschedule - the frequency of norm computation

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

1885:    Level: developer

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

1889: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1890: @*/
1891: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1892: {
1895:   snes->functype = type;
1896:   return(0);
1897: }


1900: /*@C
1901:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1902:    of the SNES method.

1904:    Logically Collective on SNES

1906:    Input Parameters:
1907: +  snes - the SNES context
1908: -  normschedule - the type of the norm used

1910:    Level: advanced

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

1914: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1915: @*/
1916: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
1917: {
1920:   *type = snes->functype;
1921:   return(0);
1922: }

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

1927:      Synopsis:
1928:      #include <petscsnes.h>
1929: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1931: +  X   - solution vector
1932: .  B   - RHS vector
1933: -  ctx - optional user-defined Gauss-Seidel context

1935:    Level: intermediate

1937: .seealso:   SNESSetNGS(), SNESGetNGS()
1938: M*/

1940: /*@C
1941:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1942:    use with composed nonlinear solvers.

1944:    Input Parameters:
1945: +  snes   - the SNES context
1946: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
1947: -  ctx    - [optional] user-defined context for private data for the
1948:             smoother evaluation routine (may be NULL)

1950:    Notes:
1951:    The NGS routines are used by the composed nonlinear solver to generate
1952:     a problem appropriate update to the solution, particularly FAS.

1954:    Level: intermediate

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

1958: .seealso: SNESGetFunction(), SNESComputeNGS()
1959: @*/
1960: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1961: {
1963:   DM             dm;

1967:   SNESGetDM(snes,&dm);
1968:   DMSNESSetNGS(dm,f,ctx);
1969:   return(0);
1970: }

1972: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1973: {
1975:   DM             dm;
1976:   DMSNES         sdm;

1979:   SNESGetDM(snes,&dm);
1980:   DMGetDMSNES(dm,&sdm);
1981:   /*  A(x)*x - b(x) */
1982:   if (sdm->ops->computepfunction) {
1983:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
1984:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");

1986:   if (sdm->ops->computepjacobian) {
1987:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
1988:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard matrix.");
1989:   VecScale(f,-1.0);
1990:   MatMultAdd(snes->jacobian,x,f,f);
1991:   return(0);
1992: }

1994: PETSC_EXTERN PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
1995: {
1997:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
1998:   return(0);
1999: }

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

2004:    Logically Collective on SNES

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

2016:    Notes:
2017:     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
2018:     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.

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

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

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

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

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

2034:    Level: intermediate

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

2038: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
2039: @*/
2040: 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)
2041: {
2043:   DM             dm;

2047:   SNESGetDM(snes, &dm);
2048:   DMSNESSetPicard(dm,b,J,ctx);
2049:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
2050:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
2051:   return(0);
2052: }

2054: /*@C
2055:    SNESGetPicard - Returns the context for the Picard iteration

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

2059:    Input Parameter:
2060: .  snes - the SNES context

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

2070:    Level: advanced

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

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

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

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

2093:    Logically Collective on SNES

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

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

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

2107:    Level: intermediate

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

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

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

2127:    Logically Collective on SNES

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

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

2135:    Level: intermediate

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

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

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

2153:    Collective on SNES

2155:    Input Parameters:
2156: +  snes - the SNES context
2157: -  x - input vector

2159:    Output Parameter:
2160: .  y - function vector, as set by SNESSetFunction()

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

2167:    Level: developer

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

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

2185:   VecValidValues(x,2,PETSC_TRUE);

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

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

2221:    Collective on SNES

2223:    Input Parameters:
2224: +  snes - the SNES context
2225: .  x - input vector
2226: -  b - rhs vector

2228:    Output Parameter:
2229: .  x - new solution vector

2231:    Notes:
2232:    SNESComputeNGS() is typically used within composed nonlinear solver
2233:    implementations, so most users would not generally call this routine
2234:    themselves.

2236:    Level: developer

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

2240: .seealso: SNESSetNGS(), SNESComputeFunction()
2241: @*/
2242: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2243: {
2245:   DM             dm;
2246:   DMSNES         sdm;

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

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

2272:    Collective on SNES and Mat

2274:    Input Parameters:
2275: +  snes - the SNES context
2276: -  x - input vector

2278:    Output Parameters:
2279: +  A - Jacobian matrix
2280: -  B - optional preconditioning matrix

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


2298:    Notes:
2299:    Most users should not need to explicitly call this routine, as it
2300:    is used internally within the nonlinear solvers.

2302:    Level: developer

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

2306: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2307: @*/
2308: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2309: {
2311:   PetscBool      flag;
2312:   DM             dm;
2313:   DMSNES         sdm;
2314:   KSP            ksp;

2320:   VecValidValues(X,2,PETSC_TRUE);
2321:   SNESGetDM(snes,&dm);
2322:   DMGetDMSNES(dm,&sdm);

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

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

2328:   if (snes->lagjacobian == -2) {
2329:     snes->lagjacobian = -1;

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

2355:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2356:   VecLockPush(X);
2357:   PetscStackPush("SNES user Jacobian function");
2358:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2359:   PetscStackPop;
2360:   VecLockPop(X);
2361:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

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

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

2455:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2456:       MatColoringCreate(Bfd,&coloring);
2457:       MatColoringSetType(coloring,MATCOLORINGSL);
2458:       MatColoringSetFromOptions(coloring);
2459:       MatColoringApply(coloring,&iscoloring);
2460:       MatColoringDestroy(&coloring);
2461:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2462:       MatFDColoringSetFromOptions(matfdcoloring);
2463:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2464:       ISColoringDestroy(&iscoloring);

2466:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2467:       SNESGetFunction(snes,NULL,&func,&funcctx);
2468:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2469:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2470:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2471:       MatFDColoringSetFromOptions(matfdcoloring);
2472:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2473:       MatFDColoringDestroy(&matfdcoloring);

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

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

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

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

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

2560:    Level: intermediate

2562: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2563: M*/

2565: /*@C
2566:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2567:    location to store the matrix.

2569:    Logically Collective on SNES and Mat

2571:    Input Parameters:
2572: +  snes - the SNES context
2573: .  Amat - the matrix that defines the (approximate) Jacobian
2574: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2575: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2576: -  ctx - [optional] user-defined context for private data for the
2577:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2579:    Notes:
2580:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2581:    each matrix.

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

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

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

2592:    Level: beginner

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

2596: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J, 
2597:           SNESSetPicard(), SNESJacobianFunction
2598: @*/
2599: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2600: {
2602:   DM             dm;

2610:   SNESGetDM(snes,&dm);
2611:   DMSNESSetJacobian(dm,J,ctx);
2612:   if (Amat) {
2613:     PetscObjectReference((PetscObject)Amat);
2614:     MatDestroy(&snes->jacobian);

2616:     snes->jacobian = Amat;
2617:   }
2618:   if (Pmat) {
2619:     PetscObjectReference((PetscObject)Pmat);
2620:     MatDestroy(&snes->jacobian_pre);

2622:     snes->jacobian_pre = Pmat;
2623:   }
2624:   return(0);
2625: }

2627: /*@C
2628:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2629:    provided context for evaluating the Jacobian.

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

2633:    Input Parameter:
2634: .  snes - the nonlinear solver context

2636:    Output Parameters:
2637: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2638: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2639: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2640: -  ctx - location to stash Jacobian ctx (or NULL)

2642:    Level: advanced

2644: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2645: @*/
2646: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2647: {
2649:   DM             dm;
2650:   DMSNES         sdm;

2654:   if (Amat) *Amat = snes->jacobian;
2655:   if (Pmat) *Pmat = snes->jacobian_pre;
2656:   SNESGetDM(snes,&dm);
2657:   DMGetDMSNES(dm,&sdm);
2658:   if (J) *J = sdm->ops->computejacobian;
2659:   if (ctx) *ctx = sdm->jacobianctx;
2660:   return(0);
2661: }

2663: /*@
2664:    SNESSetUp - Sets up the internal data structures for the later use
2665:    of a nonlinear solver.

2667:    Collective on SNES

2669:    Input Parameters:
2670: .  snes - the SNES context

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

2679:    Level: advanced

2681: .keywords: SNES, nonlinear, setup

2683: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2684: @*/
2685: PetscErrorCode  SNESSetUp(SNES snes)
2686: {
2688:   DM             dm;
2689:   DMSNES         sdm;
2690:   SNESLineSearch linesearch, pclinesearch;
2691:   void           *lsprectx,*lspostctx;
2692:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2693:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2694:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2695:   Vec            f,fpc;
2696:   void           *funcctx;
2697:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2698:   void           *jacctx,*appctx;
2699:   Mat            j,jpre;

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

2705:   if (!((PetscObject)snes)->type_name) {
2706:     SNESSetType(snes,SNESNEWTONLS);
2707:   }

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

2711:   SNESGetDM(snes,&dm);
2712:   DMGetDMSNES(dm,&sdm);
2713:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2714:   if (!sdm->ops->computejacobian) {
2715:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2716:   }
2717:   if (!snes->vec_func) {
2718:     DMCreateGlobalVector(dm,&snes->vec_func);
2719:   }

2721:   if (!snes->ksp) {
2722:     SNESGetKSP(snes, &snes->ksp);
2723:   }

2725:   if (!snes->linesearch) {
2726:     SNESGetLineSearch(snes, &snes->linesearch);
2727:   }
2728:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2730:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2731:     snes->mf          = PETSC_TRUE;
2732:     snes->mf_operator = PETSC_FALSE;
2733:   }

2735:   if (snes->npc) {
2736:     /* copy the DM over */
2737:     SNESGetDM(snes,&dm);
2738:     SNESSetDM(snes->npc,dm);

2740:     SNESGetFunction(snes,&f,&func,&funcctx);
2741:     VecDuplicate(f,&fpc);
2742:     SNESSetFunction(snes->npc,fpc,func,funcctx);
2743:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2744:     SNESSetJacobian(snes->npc,j,jpre,jac,jacctx);
2745:     SNESGetApplicationContext(snes,&appctx);
2746:     SNESSetApplicationContext(snes->npc,appctx);
2747:     VecDestroy(&fpc);

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

2752:     /* default to 1 iteration */
2753:     SNESSetTolerances(snes->npc,0.0,0.0,0.0,1,snes->npc->max_funcs);
2754:     if (snes->npcside==PC_RIGHT) {
2755:       SNESSetNormSchedule(snes->npc,SNES_NORM_FINAL_ONLY);
2756:     } else {
2757:       SNESSetNormSchedule(snes->npc,SNES_NORM_NONE);
2758:     }
2759:     SNESSetFromOptions(snes->npc);

2761:     /* copy the line search context over */
2762:     SNESGetLineSearch(snes,&linesearch);
2763:     SNESGetLineSearch(snes->npc,&pclinesearch);
2764:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2765:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2766:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2767:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2768:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2769:   }
2770:   if (snes->mf) {
2771:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2772:   }
2773:   if (snes->ops->usercompute && !snes->user) {
2774:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2775:   }

2777:   snes->jac_iter = 0;
2778:   snes->pre_iter = 0;

2780:   if (snes->ops->setup) {
2781:     (*snes->ops->setup)(snes);
2782:   }

2784:   if (snes->npc && (snes->npcside== PC_LEFT)) {
2785:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2786:       SNESGetLineSearch(snes,&linesearch);
2787:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2788:     }
2789:   }

2791:   snes->setupcalled = PETSC_TRUE;
2792:   return(0);
2793: }

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

2798:    Collective on SNES

2800:    Input Parameter:
2801: .  snes - iterative context obtained from SNESCreate()

2803:    Level: intermediate

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

2807: .keywords: SNES, destroy

2809: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
2810: @*/
2811: PetscErrorCode  SNESReset(SNES snes)
2812: {

2817:   if (snes->ops->userdestroy && snes->user) {
2818:     (*snes->ops->userdestroy)((void**)&snes->user);
2819:     snes->user = NULL;
2820:   }
2821:   if (snes->npc) {
2822:     SNESReset(snes->npc);
2823:   }

2825:   if (snes->ops->reset) {
2826:     (*snes->ops->reset)(snes);
2827:   }
2828:   if (snes->ksp) {
2829:     KSPReset(snes->ksp);
2830:   }

2832:   if (snes->linesearch) {
2833:     SNESLineSearchReset(snes->linesearch);
2834:   }

2836:   VecDestroy(&snes->vec_rhs);
2837:   VecDestroy(&snes->vec_sol);
2838:   VecDestroy(&snes->vec_sol_update);
2839:   VecDestroy(&snes->vec_func);
2840:   MatDestroy(&snes->jacobian);
2841:   MatDestroy(&snes->jacobian_pre);
2842:   VecDestroyVecs(snes->nwork,&snes->work);
2843:   VecDestroyVecs(snes->nvwork,&snes->vwork);

2845:   snes->alwayscomputesfinalresidual = PETSC_FALSE;

2847:   snes->nwork       = snes->nvwork = 0;
2848:   snes->setupcalled = PETSC_FALSE;
2849:   return(0);
2850: }

2852: /*@
2853:    SNESDestroy - Destroys the nonlinear solver context that was created
2854:    with SNESCreate().

2856:    Collective on SNES

2858:    Input Parameter:
2859: .  snes - the SNES context

2861:    Level: beginner

2863: .keywords: SNES, nonlinear, destroy

2865: .seealso: SNESCreate(), SNESSolve()
2866: @*/
2867: PetscErrorCode  SNESDestroy(SNES *snes)
2868: {

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

2876:   SNESReset((*snes));
2877:   SNESDestroy(&(*snes)->npc);

2879:   /* if memory was published with SAWs then destroy it */
2880:   PetscObjectSAWsViewOff((PetscObject)*snes);
2881:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

2883:   DMDestroy(&(*snes)->dm);
2884:   KSPDestroy(&(*snes)->ksp);
2885:   SNESLineSearchDestroy(&(*snes)->linesearch);

2887:   PetscFree((*snes)->kspconvctx);
2888:   if ((*snes)->ops->convergeddestroy) {
2889:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
2890:   }
2891:   if ((*snes)->conv_malloc) {
2892:     PetscFree((*snes)->conv_hist);
2893:     PetscFree((*snes)->conv_hist_its);
2894:   }
2895:   SNESMonitorCancel((*snes));
2896:   PetscHeaderDestroy(snes);
2897:   return(0);
2898: }

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

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

2905:    Logically Collective on SNES

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

2912:    Options Database Keys:
2913: .    -snes_lag_preconditioner <lag>

2915:    Notes:
2916:    The default is 1
2917:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
2918:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

2920:    Level: intermediate

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

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

2926: @*/
2927: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
2928: {
2931:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
2932:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
2934:   snes->lagpreconditioner = lag;
2935:   return(0);
2936: }

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

2941:    Logically Collective on SNES

2943:    Input Parameters:
2944: +  snes - the SNES context
2945: -  steps - the number of refinements to do, defaults to 0

2947:    Options Database Keys:
2948: .    -snes_grid_sequence <steps>

2950:    Level: intermediate

2952:    Notes:
2953:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2959: @*/
2960: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
2961: {
2965:   snes->gridsequence = steps;
2966:   return(0);
2967: }

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

2972:    Logically Collective on SNES

2974:    Input Parameter:
2975: .  snes - the SNES context

2977:    Output Parameter:
2978: .  steps - the number of refinements to do, defaults to 0

2980:    Options Database Keys:
2981: .    -snes_grid_sequence <steps>

2983:    Level: intermediate

2985:    Notes:
2986:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2992: @*/
2993: PetscErrorCode  SNESGetGridSequence(SNES snes,PetscInt *steps)
2994: {
2997:   *steps = snes->gridsequence;
2998:   return(0);
2999: }

3001: /*@
3002:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

3004:    Not Collective

3006:    Input Parameter:
3007: .  snes - the SNES context

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

3013:    Options Database Keys:
3014: .    -snes_lag_preconditioner <lag>

3016:    Notes:
3017:    The default is 1
3018:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3020:    Level: intermediate

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

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

3026: @*/
3027: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
3028: {
3031:   *lag = snes->lagpreconditioner;
3032:   return(0);
3033: }

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

3039:    Logically Collective on SNES

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

3046:    Options Database Keys:
3047: .    -snes_lag_jacobian <lag>

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

3055:    Level: intermediate

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

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

3061: @*/
3062: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3063: {
3066:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3067:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3069:   snes->lagjacobian = lag;
3070:   return(0);
3071: }

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

3076:    Not Collective

3078:    Input Parameter:
3079: .  snes - the SNES context

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

3085:    Options Database Keys:
3086: .    -snes_lag_jacobian <lag>

3088:    Notes:
3089:    The default is 1
3090:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3092:    Level: intermediate

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

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

3098: @*/
3099: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3100: {
3103:   *lag = snes->lagjacobian;
3104:   return(0);
3105: }

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

3110:    Logically collective on SNES

3112:    Input Parameter:
3113: +  snes - the SNES context
3114: -   flg - jacobian lagging persists if true

3116:    Options Database Keys:
3117: .    -snes_lag_jacobian_persists <flg>

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

3123:    Level: developer

3125: .keywords: SNES, nonlinear, lag

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

3129: @*/
3130: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3131: {
3135:   snes->lagjac_persist = flg;
3136:   return(0);
3137: }

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

3142:    Logically Collective on SNES

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

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

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

3155:    Level: developer

3157: .keywords: SNES, nonlinear, lag

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

3161: @*/
3162: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3163: {
3167:   snes->lagpre_persist = flg;
3168:   return(0);
3169: }

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

3174:    Logically Collective on SNES

3176:    Input Parameters:
3177: +  snes - the SNES context
3178: -  force - PETSC_TRUE require at least one iteration

3180:    Options Database Keys:
3181: .    -snes_force_iteration <force> - Sets forcing an iteration

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

3186:    Level: intermediate

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

3190: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance()
3191: @*/
3192: PetscErrorCode  SNESSetForceIteration(SNES snes,PetscBool force)
3193: {
3196:   snes->forceiteration = force;
3197:   return(0);
3198: }


3201: /*@
3202:    SNESSetTolerances - Sets various parameters used in convergence tests.

3204:    Logically Collective on SNES

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

3214:    Options Database Keys:
3215: +    -snes_atol <abstol> - Sets abstol
3216: .    -snes_rtol <rtol> - Sets rtol
3217: .    -snes_stol <stol> - Sets stol
3218: .    -snes_max_it <maxit> - Sets maxit
3219: -    -snes_max_funcs <maxf> - Sets maxf

3221:    Notes:
3222:    The default maximum number of iterations is 50.
3223:    The default maximum number of function evaluations is 1000.

3225:    Level: intermediate

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

3229: .seealso: SNESSetTrustRegionTolerance(), SNESSetDivergenceTolerance(), SNESSetForceIteration()
3230: @*/
3231: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3232: {

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

3265: /*@
3266:    SNESSetDivergenceTolerance - Sets the divergence tolerance used for the SNES divergence test.

3268:    Logically Collective on SNES

3270:    Input Parameters:
3271: +  snes - the SNES context
3272: -  divtol - the divergence tolerance. Use -1 to deactivate the test.

3274:    Options Database Keys:
3275: +    -snes_divergence_tolerance <divtol> - Sets divtol

3277:    Notes:
3278:    The default divergence tolerance is 1e4.

3280:    Level: intermediate

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

3284: .seealso: SNESSetTolerances(), SNESGetDivergenceTolerance
3285: @*/
3286: PetscErrorCode  SNESSetDivergenceTolerance(SNES snes,PetscReal divtol)
3287: {

3292:   if (divtol != PETSC_DEFAULT) {
3293:     snes->divtol = divtol;
3294:   }
3295:   else {
3296:     snes->divtol = 1.0e4;
3297:   }
3298:   return(0);
3299: }

3301: /*@
3302:    SNESGetTolerances - Gets various parameters used in convergence tests.

3304:    Not Collective

3306:    Input Parameters:
3307: +  snes - the SNES context
3308: .  atol - absolute convergence tolerance
3309: .  rtol - relative convergence tolerance
3310: .  stol -  convergence tolerance in terms of the norm
3311:            of the change in the solution between steps
3312: .  maxit - maximum number of iterations
3313: -  maxf - maximum number of function evaluations

3315:    Notes:
3316:    The user can specify NULL for any parameter that is not needed.

3318:    Level: intermediate

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

3322: .seealso: SNESSetTolerances()
3323: @*/
3324: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3325: {
3328:   if (atol)  *atol  = snes->abstol;
3329:   if (rtol)  *rtol  = snes->rtol;
3330:   if (stol)  *stol  = snes->stol;
3331:   if (maxit) *maxit = snes->max_its;
3332:   if (maxf)  *maxf  = snes->max_funcs;
3333:   return(0);
3334: }

3336: /*@
3337:    SNESGetDivergenceTolerance - Gets divergence tolerance used in divergence test.

3339:    Not Collective

3341:    Input Parameters:
3342: +  snes - the SNES context
3343: -  divtol - divergence tolerance

3345:    Level: intermediate

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

3349: .seealso: SNESSetDivergenceTolerance()
3350: @*/
3351: PetscErrorCode  SNESGetDivergenceTolerance(SNES snes,PetscReal *divtol)
3352: {
3355:   if (divtol) *divtol = snes->divtol;
3356:   return(0);
3357: }

3359: /*@
3360:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3362:    Logically Collective on SNES

3364:    Input Parameters:
3365: +  snes - the SNES context
3366: -  tol - tolerance

3368:    Options Database Key:
3369: .  -snes_trtol <tol> - Sets tol

3371:    Level: intermediate

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

3375: .seealso: SNESSetTolerances()
3376: @*/
3377: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3378: {
3382:   snes->deltatol = tol;
3383:   return(0);
3384: }

3386: /*
3387:    Duplicate the lg monitors for SNES from KSP; for some reason with
3388:    dynamic libraries things don't work under Sun4 if we just use
3389:    macros instead of functions
3390: */
3391: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3392: {

3397:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3398:   return(0);
3399: }

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

3406:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3407:   return(0);
3408: }

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

3412: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3413: {
3414:   PetscDrawLG      lg;
3415:   PetscErrorCode   ierr;
3416:   PetscReal        x,y,per;
3417:   PetscViewer      v = (PetscViewer)monctx;
3418:   static PetscReal prev; /* should be in the context */
3419:   PetscDraw        draw;

3423:   PetscViewerDrawGetDrawLG(v,0,&lg);
3424:   if (!n) {PetscDrawLGReset(lg);}
3425:   PetscDrawLGGetDraw(lg,&draw);
3426:   PetscDrawSetTitle(draw,"Residual norm");
3427:   x    = (PetscReal)n;
3428:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3429:   else y = -15.0;
3430:   PetscDrawLGAddPoint(lg,&x,&y);
3431:   if (n < 20 || !(n % 5) || snes->reason) {
3432:     PetscDrawLGDraw(lg);
3433:     PetscDrawLGSave(lg);
3434:   }

3436:   PetscViewerDrawGetDrawLG(v,1,&lg);
3437:   if (!n) {PetscDrawLGReset(lg);}
3438:   PetscDrawLGGetDraw(lg,&draw);
3439:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3440:    SNESMonitorRange_Private(snes,n,&per);
3441:   x    = (PetscReal)n;
3442:   y    = 100.0*per;
3443:   PetscDrawLGAddPoint(lg,&x,&y);
3444:   if (n < 20 || !(n % 5) || snes->reason) {
3445:     PetscDrawLGDraw(lg);
3446:     PetscDrawLGSave(lg);
3447:   }

3449:   PetscViewerDrawGetDrawLG(v,2,&lg);
3450:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3451:   PetscDrawLGGetDraw(lg,&draw);
3452:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3453:   x    = (PetscReal)n;
3454:   y    = (prev - rnorm)/prev;
3455:   PetscDrawLGAddPoint(lg,&x,&y);
3456:   if (n < 20 || !(n % 5) || snes->reason) {
3457:     PetscDrawLGDraw(lg);
3458:     PetscDrawLGSave(lg);
3459:   }

3461:   PetscViewerDrawGetDrawLG(v,3,&lg);
3462:   if (!n) {PetscDrawLGReset(lg);}
3463:   PetscDrawLGGetDraw(lg,&draw);
3464:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3465:   x    = (PetscReal)n;
3466:   y    = (prev - rnorm)/(prev*per);
3467:   if (n > 2) { /*skip initial crazy value */
3468:     PetscDrawLGAddPoint(lg,&x,&y);
3469:   }
3470:   if (n < 20 || !(n % 5) || snes->reason) {
3471:     PetscDrawLGDraw(lg);
3472:     PetscDrawLGSave(lg);
3473:   }
3474:   prev = rnorm;
3475:   return(0);
3476: }

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

3481:    Collective on SNES

3483:    Input Parameters:
3484: +  snes - nonlinear solver context obtained from SNESCreate()
3485: .  iter - iteration number
3486: -  rnorm - relative norm of the residual

3488:    Notes:
3489:    This routine is called by the SNES implementations.
3490:    It does not typically need to be called by the user.

3492:    Level: developer

3494: .seealso: SNESMonitorSet()
3495: @*/
3496: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3497: {
3499:   PetscInt       i,n = snes->numbermonitors;

3502:   VecLockPush(snes->vec_sol);
3503:   for (i=0; i<n; i++) {
3504:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3505:   }
3506:   VecLockPop(snes->vec_sol);
3507:   return(0);
3508: }

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

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

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

3519: +    snes - the SNES context
3520: .    its - iteration number
3521: .    norm - 2-norm function value (may be estimated)
3522: -    mctx - [optional] monitoring context

3524:    Level: advanced

3526: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3527: M*/

3529: /*@C
3530:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3531:    iteration of the nonlinear solver to display the iteration's
3532:    progress.

3534:    Logically Collective on SNES

3536:    Input Parameters:
3537: +  snes - the SNES context
3538: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3539: .  mctx - [optional] user-defined context for private data for the
3540:           monitor routine (use NULL if no context is desired)
3541: -  monitordestroy - [optional] routine that frees monitor context
3542:           (may be NULL)

3544:    Options Database Keys:
3545: +    -snes_monitor        - sets SNESMonitorDefault()
3546: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3547:                             uses SNESMonitorLGCreate()
3548: -    -snes_monitor_cancel - cancels all monitors that have
3549:                             been hardwired into a code by
3550:                             calls to SNESMonitorSet(), but
3551:                             does not cancel those set via
3552:                             the options database.

3554:    Notes:
3555:    Several different monitoring routines may be set by calling
3556:    SNESMonitorSet() multiple times; all will be called in the
3557:    order in which they were set.

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

3561:    Level: intermediate

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

3565: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3566: @*/
3567: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3568: {
3569:   PetscInt       i;
3571:   PetscBool      identical;

3575:   for (i=0; i<snes->numbermonitors;i++) {
3576:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3577:     if (identical) return(0);
3578:   }
3579:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3580:   snes->monitor[snes->numbermonitors]          = f;
3581:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3582:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3583:   return(0);
3584: }

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

3589:    Logically Collective on SNES

3591:    Input Parameters:
3592: .  snes - the SNES context

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

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

3602:    Level: intermediate

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

3606: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3607: @*/
3608: PetscErrorCode  SNESMonitorCancel(SNES snes)
3609: {
3611:   PetscInt       i;

3615:   for (i=0; i<snes->numbermonitors; i++) {
3616:     if (snes->monitordestroy[i]) {
3617:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3618:     }
3619:   }
3620:   snes->numbermonitors = 0;
3621:   return(0);
3622: }

3624: /*MC
3625:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3631: +    snes - the SNES context
3632: .    it - current iteration (0 is the first and is before any Newton step)
3633: .    cctx - [optional] convergence context
3634: .    reason - reason for convergence/divergence
3635: .    xnorm - 2-norm of current iterate
3636: .    gnorm - 2-norm of current step
3637: -    f - 2-norm of function

3639:    Level: intermediate

3641: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3642: M*/

3644: /*@C
3645:    SNESSetConvergenceTest - Sets the function that is to be used
3646:    to test for convergence of the nonlinear iterative solution.

3648:    Logically Collective on SNES

3650:    Input Parameters:
3651: +  snes - the SNES context
3652: .  SNESConvergenceTestFunction - routine to test for convergence
3653: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3654: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3656:    Level: advanced

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

3660: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3661: @*/
3662: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3663: {

3668:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3669:   if (snes->ops->convergeddestroy) {
3670:     (*snes->ops->convergeddestroy)(snes->cnvP);
3671:   }
3672:   snes->ops->converged        = SNESConvergenceTestFunction;
3673:   snes->ops->convergeddestroy = destroy;
3674:   snes->cnvP                  = cctx;
3675:   return(0);
3676: }

3678: /*@
3679:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3681:    Not Collective

3683:    Input Parameter:
3684: .  snes - the SNES context

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

3690:    Options Database:
3691: .   -snes_converged_reason - prints the reason to standard out

3693:    Level: intermediate

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

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

3699: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
3700: @*/
3701: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3702: {
3706:   *reason = snes->reason;
3707:   return(0);
3708: }

3710: /*@
3711:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3713:    Not Collective

3715:    Input Parameters:
3716: +  snes - the SNES context
3717: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
3718:             manual pages for the individual convergence tests for complete lists

3720:    Level: intermediate

3722: .keywords: SNES, nonlinear, set, convergence, test
3723: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
3724: @*/
3725: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
3726: {
3729:   snes->reason = reason;
3730:   return(0);
3731: }

3733: /*@
3734:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3736:    Logically Collective on SNES

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

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

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

3754:    Level: intermediate

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

3758: .seealso: SNESGetConvergenceHistory()

3760: @*/
3761: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3762: {

3769:   if (!a) {
3770:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3771:     PetscCalloc1(na,&a);
3772:     PetscCalloc1(na,&its);

3774:     snes->conv_malloc = PETSC_TRUE;
3775:   }
3776:   snes->conv_hist       = a;
3777:   snes->conv_hist_its   = its;
3778:   snes->conv_hist_max   = na;
3779:   snes->conv_hist_len   = 0;
3780:   snes->conv_hist_reset = reset;
3781:   return(0);
3782: }

3784: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3785: #include <engine.h>   /* MATLAB include file */
3786: #include <mex.h>      /* MATLAB include file */

3788: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3789: {
3790:   mxArray   *mat;
3791:   PetscInt  i;
3792:   PetscReal *ar;

3795:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3796:   ar  = (PetscReal*) mxGetData(mat);
3797:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3798:   PetscFunctionReturn(mat);
3799: }
3800: #endif

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

3805:    Not Collective

3807:    Input Parameter:
3808: .  snes - iterative context obtained from SNESCreate()

3810:    Output Parameters:
3811: .  a   - array to hold history
3812: .  its - integer array holds the number of linear iterations (or
3813:          negative if not converged) for each solve.
3814: -  na  - size of a and its

3816:    Notes:
3817:     The calling sequence for this routine in Fortran is
3818: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

3824:    Level: intermediate

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

3828: .seealso: SNESSetConvergencHistory()

3830: @*/
3831: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
3832: {
3835:   if (a)   *a   = snes->conv_hist;
3836:   if (its) *its = snes->conv_hist_its;
3837:   if (na)  *na  = snes->conv_hist_len;
3838:   return(0);
3839: }

3841: /*@C
3842:   SNESSetUpdate - Sets the general-purpose update function called
3843:   at the beginning of every iteration of the nonlinear solve. Specifically
3844:   it is called just before the Jacobian is "evaluated".

3846:   Logically Collective on SNES

3848:   Input Parameters:
3849: . snes - The nonlinear solver context
3850: . func - The function

3852:   Calling sequence of func:
3853: . func (SNES snes, PetscInt step);

3855: . step - The current step of the iteration

3857:   Level: advanced

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

3862: .keywords: SNES, update

3864: .seealso SNESSetJacobian(), SNESSolve()
3865: @*/
3866: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
3867: {
3870:   snes->ops->update = func;
3871:   return(0);
3872: }

3874: /*
3875:    SNESScaleStep_Private - Scales a step so that its length is less than the
3876:    positive parameter delta.

3878:     Input Parameters:
3879: +   snes - the SNES context
3880: .   y - approximate solution of linear system
3881: .   fnorm - 2-norm of current function
3882: -   delta - trust region size

3884:     Output Parameters:
3885: +   gpnorm - predicted function norm at the new point, assuming local
3886:     linearization.  The value is zero if the step lies within the trust
3887:     region, and exceeds zero otherwise.
3888: -   ynorm - 2-norm of the step

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

3894: .keywords: SNES, nonlinear, scale, step
3895: */
3896: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
3897: {
3898:   PetscReal      nrm;
3899:   PetscScalar    cnorm;


3907:   VecNorm(y,NORM_2,&nrm);
3908:   if (nrm > *delta) {
3909:     nrm     = *delta/nrm;
3910:     *gpnorm = (1.0 - nrm)*(*fnorm);
3911:     cnorm   = nrm;
3912:     VecScale(y,cnorm);
3913:     *ynorm  = *delta;
3914:   } else {
3915:     *gpnorm = 0.0;
3916:     *ynorm  = nrm;
3917:   }
3918:   return(0);
3919: }

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

3924:    Collective on SNES

3926:    Parameter:
3927: +  snes - iterative context obtained from SNESCreate()
3928: -  viewer - the viewer to display the reason


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

3934:    Level: beginner

3936: .keywords: SNES, solve, linear system

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

3940: @*/
3941: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
3942: {
3944:   PetscBool      isAscii;

3947:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
3948:   if (isAscii) {
3949:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
3950:     if (snes->reason > 0) {
3951:       if (((PetscObject) snes)->prefix) {
3952:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3953:       } else {
3954:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3955:       }
3956:     } else {
3957:       if (((PetscObject) snes)->prefix) {
3958:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3959:       } else {
3960:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3961:       }
3962:     }
3963:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
3964:   }
3965:   return(0);
3966: }

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

3971:   Collective on SNES

3973:   Input Parameters:
3974: . snes   - the SNES object

3976:   Level: intermediate

3978: @*/
3979: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
3980: {
3981:   PetscErrorCode    ierr;
3982:   PetscViewer       viewer;
3983:   PetscBool         flg;
3984:   static PetscBool  incall = PETSC_FALSE;
3985:   PetscViewerFormat format;

3988:   if (incall) return(0);
3989:   incall = PETSC_TRUE;
3990:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
3991:   if (flg) {
3992:     PetscViewerPushFormat(viewer,format);
3993:     SNESReasonView(snes,viewer);
3994:     PetscViewerPopFormat(viewer);
3995:     PetscViewerDestroy(&viewer);
3996:   }
3997:   incall = PETSC_FALSE;
3998:   return(0);
3999: }

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

4005:    Collective on SNES

4007:    Input Parameters:
4008: +  snes - the SNES context
4009: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
4010: -  x - the solution vector.

4012:    Notes:
4013:    The user should initialize the vector,x, with the initial guess
4014:    for the nonlinear solve prior to calling SNESSolve.  In particular,
4015:    to employ an initial guess of zero, the user should explicitly set
4016:    this vector to zero by calling VecSet().

4018:    Level: beginner

4020: .keywords: SNES, nonlinear, solve

4022: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
4023: @*/
4024: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
4025: {
4026:   PetscErrorCode    ierr;
4027:   PetscBool         flg;
4028:   PetscInt          grid;
4029:   Vec               xcreated = NULL;
4030:   DM                dm;


4039:   {
4040:     PetscViewer       viewer;
4041:     PetscViewerFormat format;
4042:     PetscBool         flg;
4043:     static PetscBool  incall = PETSC_FALSE;

4045:     if (!incall) {
4046:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) snes), ((PetscObject) snes)->prefix, "-snes_convergence_estimate", &viewer, &format, &flg);
4047:       if (flg) {
4048:         PetscConvEst conv;
4049:         PetscReal    alpha; /* Convergence rate of the solution error in the L_2 norm */

4051:         incall = PETSC_TRUE;
4052:         PetscConvEstCreate(PetscObjectComm((PetscObject) snes), &conv);
4053:         PetscConvEstSetSolver(conv, snes);
4054:         PetscConvEstSetFromOptions(conv);
4055:         PetscConvEstSetUp(conv);
4056:         PetscConvEstGetConvRate(conv, &alpha);
4057:         PetscViewerPushFormat(viewer, format);
4058:         PetscConvEstRateView(conv, alpha, viewer);
4059:         PetscViewerPopFormat(viewer);
4060:         PetscViewerDestroy(&viewer);
4061:         PetscConvEstDestroy(&conv);
4062:         incall = PETSC_FALSE;
4063:       }
4064:     }
4065:   }
4066:   if (!x) {
4067:     SNESGetDM(snes,&dm);
4068:     DMCreateGlobalVector(dm,&xcreated);
4069:     x    = xcreated;
4070:   }
4071:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

4076:     /* set solution vector */
4077:     if (!grid) {PetscObjectReference((PetscObject)x);}
4078:     VecDestroy(&snes->vec_sol);
4079:     snes->vec_sol = x;
4080:     SNESGetDM(snes,&dm);

4082:     /* set affine vector if provided */
4083:     if (b) { PetscObjectReference((PetscObject)b); }
4084:     VecDestroy(&snes->vec_rhs);
4085:     snes->vec_rhs = b;

4087:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
4088:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
4089:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
4090:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
4091:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
4092:     }
4093:     DMShellSetGlobalVector(dm,snes->vec_sol);
4094:     SNESSetUp(snes);

4096:     if (!grid) {
4097:       if (snes->ops->computeinitialguess) {
4098:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
4099:       }
4100:     }

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

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

4111:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4112:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4118:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4119:     if (snes->reason < 0) break;
4120:     if (grid <  snes->gridsequence) {
4121:       DM  fine;
4122:       Vec xnew;
4123:       Mat interp;

4125:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4126:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4127:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4128:       DMCreateGlobalVector(fine,&xnew);
4129:       MatInterpolate(interp,x,xnew);
4130:       DMInterpolate(snes->dm,interp,fine);
4131:       MatDestroy(&interp);
4132:       x    = xnew;

4134:       SNESReset(snes);
4135:       SNESSetDM(snes,fine);
4136:       DMDestroy(&fine);
4137:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4138:     }
4139:   }
4140:   SNESViewFromOptions(snes,NULL,"-snes_view");
4141:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4143:   VecDestroy(&xcreated);
4144:   PetscObjectSAWsBlock((PetscObject)snes);
4145:   return(0);
4146: }

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

4150: /*@C
4151:    SNESSetType - Sets the method for the nonlinear solver.

4153:    Collective on SNES

4155:    Input Parameters:
4156: +  snes - the SNES context
4157: -  type - a known method

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

4163:    Notes:
4164:    See "petsc/include/petscsnes.h" for available methods (for instance)
4165: +    SNESNEWTONLS - Newton's method with line search
4166:      (systems of nonlinear equations)
4167: .    SNESNEWTONTR - Newton's method with trust region
4168:      (systems of nonlinear equations)

4170:   Normally, it is best to use the SNESSetFromOptions() command and then
4171:   set the SNES solver type from the options database rather than by using
4172:   this routine.  Using the options database provides the user with
4173:   maximum flexibility in evaluating the many nonlinear solvers.
4174:   The SNESSetType() routine is provided for those situations where it
4175:   is necessary to set the nonlinear solver independently of the command
4176:   line or options database.  This might be the case, for example, when
4177:   the choice of solver changes during the execution of the program,
4178:   and the user's application is taking responsibility for choosing the
4179:   appropriate method.

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

4184:   Level: intermediate

4186: .keywords: SNES, set, type

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

4190: @*/
4191: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4192: {
4193:   PetscErrorCode ierr,(*r)(SNES);
4194:   PetscBool      match;


4200:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4201:   if (match) return(0);

4203:    PetscFunctionListFind(SNESList,type,&r);
4204:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4205:   /* Destroy the previous private SNES context */
4206:   if (snes->ops->destroy) {
4207:     (*(snes)->ops->destroy)(snes);
4208:     snes->ops->destroy = NULL;
4209:   }
4210:   /* Reinitialize function pointers in SNESOps structure */
4211:   snes->ops->setup          = 0;
4212:   snes->ops->solve          = 0;
4213:   snes->ops->view           = 0;
4214:   snes->ops->setfromoptions = 0;
4215:   snes->ops->destroy        = 0;
4216:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4217:   snes->setupcalled = PETSC_FALSE;

4219:   PetscObjectChangeTypeName((PetscObject)snes,type);
4220:   (*r)(snes);
4221:   return(0);
4222: }

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

4227:    Not Collective

4229:    Input Parameter:
4230: .  snes - nonlinear solver context

4232:    Output Parameter:
4233: .  type - SNES method (a character string)

4235:    Level: intermediate

4237: .keywords: SNES, nonlinear, get, type, name
4238: @*/
4239: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4240: {
4244:   *type = ((PetscObject)snes)->type_name;
4245:   return(0);
4246: }

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

4251:   Logically Collective on SNES and Vec

4253:   Input Parameters:
4254: + snes - the SNES context obtained from SNESCreate()
4255: - u    - the solution vector

4257:   Level: beginner

4259: .keywords: SNES, set, solution
4260: @*/
4261: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4262: {
4263:   DM             dm;

4269:   PetscObjectReference((PetscObject) u);
4270:   VecDestroy(&snes->vec_sol);

4272:   snes->vec_sol = u;

4274:   SNESGetDM(snes, &dm);
4275:   DMShellSetGlobalVector(dm, u);
4276:   return(0);
4277: }

4279: /*@
4280:    SNESGetSolution - Returns the vector where the approximate solution is
4281:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4285:    Input Parameter:
4286: .  snes - the SNES context

4288:    Output Parameter:
4289: .  x - the solution

4291:    Level: intermediate

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

4295: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4296: @*/
4297: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4298: {
4302:   *x = snes->vec_sol;
4303:   return(0);
4304: }

4306: /*@
4307:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4308:    stored.

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

4312:    Input Parameter:
4313: .  snes - the SNES context

4315:    Output Parameter:
4316: .  x - the solution update

4318:    Level: advanced

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

4322: .seealso: SNESGetSolution(), SNESGetFunction()
4323: @*/
4324: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4325: {
4329:   *x = snes->vec_sol_update;
4330:   return(0);
4331: }

4333: /*@C
4334:    SNESGetFunction - Returns the vector where the function is stored.

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

4338:    Input Parameter:
4339: .  snes - the SNES context

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

4346:    Level: advanced

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

4350: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4351: @*/
4352: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4353: {
4355:   DM             dm;

4359:   if (r) {
4360:     if (!snes->vec_func) {
4361:       if (snes->vec_rhs) {
4362:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4363:       } else if (snes->vec_sol) {
4364:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4365:       } else if (snes->dm) {
4366:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4367:       }
4368:     }
4369:     *r = snes->vec_func;
4370:   }
4371:   SNESGetDM(snes,&dm);
4372:   DMSNESGetFunction(dm,f,ctx);
4373:   return(0);
4374: }

4376: /*@C
4377:    SNESGetNGS - Returns the NGS function and context.

4379:    Input Parameter:
4380: .  snes - the SNES context

4382:    Output Parameter:
4383: +  f - the function (or NULL) see SNESNGSFunction for details
4384: -  ctx    - the function context (or NULL)

4386:    Level: advanced

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

4390: .seealso: SNESSetNGS(), SNESGetFunction()
4391: @*/

4393: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4394: {
4396:   DM             dm;

4400:   SNESGetDM(snes,&dm);
4401:   DMSNESGetNGS(dm,f,ctx);
4402:   return(0);
4403: }

4405: /*@C
4406:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4407:    SNES options in the database.

4409:    Logically Collective on SNES

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

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

4419:    Level: advanced

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

4423: .seealso: SNESSetFromOptions()
4424: @*/
4425: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4426: {

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

4441: /*@C
4442:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4443:    SNES options in the database.

4445:    Logically Collective on SNES

4447:    Input Parameters:
4448: +  snes - the SNES context
4449: -  prefix - the prefix to prepend to all option names

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

4455:    Level: advanced

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

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

4467:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4468:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4469:   if (snes->linesearch) {
4470:     SNESGetLineSearch(snes,&snes->linesearch);
4471:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4472:   }
4473:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4474:   return(0);
4475: }

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

4481:    Not Collective

4483:    Input Parameter:
4484: .  snes - the SNES context

4486:    Output Parameter:
4487: .  prefix - pointer to the prefix string used

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

4492:    Level: advanced

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

4496: .seealso: SNESAppendOptionsPrefix()
4497: @*/
4498: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4499: {

4504:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4505:   return(0);
4506: }


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

4512:    Not collective

4514:    Input Parameters:
4515: +  name_solver - name of a new user-defined solver
4516: -  routine_create - routine to create method context

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

4521:    Sample usage:
4522: .vb
4523:    SNESRegister("my_solver",MySolverCreate);
4524: .ve

4526:    Then, your solver can be chosen with the procedural interface via
4527: $     SNESSetType(snes,"my_solver")
4528:    or at runtime via the option
4529: $     -snes_type my_solver

4531:    Level: advanced

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

4535: .keywords: SNES, nonlinear, register

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

4539:   Level: advanced
4540: @*/
4541: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4542: {

4546:   PetscFunctionListAdd(&SNESList,sname,function);
4547:   return(0);
4548: }

4550: PetscErrorCode  SNESTestLocalMin(SNES snes)
4551: {
4553:   PetscInt       N,i,j;
4554:   Vec            u,uh,fh;
4555:   PetscScalar    value;
4556:   PetscReal      norm;

4559:   SNESGetSolution(snes,&u);
4560:   VecDuplicate(u,&uh);
4561:   VecDuplicate(u,&fh);

4563:   /* currently only works for sequential */
4564:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4565:   VecGetSize(u,&N);
4566:   for (i=0; i<N; i++) {
4567:     VecCopy(u,uh);
4568:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4569:     for (j=-10; j<11; j++) {
4570:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4571:       VecSetValue(uh,i,value,ADD_VALUES);
4572:       SNESComputeFunction(snes,uh,fh);
4573:       VecNorm(fh,NORM_2,&norm);
4574:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4575:       value = -value;
4576:       VecSetValue(uh,i,value,ADD_VALUES);
4577:     }
4578:   }
4579:   VecDestroy(&uh);
4580:   VecDestroy(&fh);
4581:   return(0);
4582: }

4584: /*@
4585:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4586:    computing relative tolerance for linear solvers within an inexact
4587:    Newton method.

4589:    Logically Collective on SNES

4591:    Input Parameters:
4592: +  snes - SNES context
4593: -  flag - PETSC_TRUE or PETSC_FALSE

4595:     Options Database:
4596: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4597: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4598: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4599: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4600: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4601: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4602: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4603: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

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

4612:    Level: advanced

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

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

4620: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4621: @*/
4622: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4623: {
4627:   snes->ksp_ewconv = flag;
4628:   return(0);
4629: }

4631: /*@
4632:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4633:    for computing relative tolerance for linear solvers within an
4634:    inexact Newton method.

4636:    Not Collective

4638:    Input Parameter:
4639: .  snes - SNES context

4641:    Output Parameter:
4642: .  flag - PETSC_TRUE or PETSC_FALSE

4644:    Notes:
4645:    Currently, the default is to use a constant relative tolerance for
4646:    the inner linear solvers.  Alternatively, one can use the
4647:    Eisenstat-Walker method, where the relative convergence tolerance
4648:    is reset at each Newton iteration according progress of the nonlinear
4649:    solver.

4651:    Level: advanced

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

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

4659: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4660: @*/
4661: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4662: {
4666:   *flag = snes->ksp_ewconv;
4667:   return(0);
4668: }

4670: /*@
4671:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4672:    convergence criteria for the linear solvers within an inexact
4673:    Newton method.

4675:    Logically Collective on SNES

4677:    Input Parameters:
4678: +    snes - SNES context
4679: .    version - version 1, 2 (default is 2) or 3
4680: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4681: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4682: .    gamma - multiplicative factor for version 2 rtol computation
4683:              (0 <= gamma2 <= 1)
4684: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4685: .    alpha2 - power for safeguard
4686: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4688:    Note:
4689:    Version 3 was contributed by Luis Chacon, June 2006.

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

4693:    Level: advanced

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

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

4702: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4703: @*/
4704: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4705: {
4706:   SNESKSPEW *kctx;

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

4720:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4721:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4722:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4723:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4724:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4725:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4726:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4728:   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);
4729:   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);
4730:   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);
4731:   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);
4732:   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);
4733:   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);
4734:   return(0);
4735: }

4737: /*@
4738:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4739:    convergence criteria for the linear solvers within an inexact
4740:    Newton method.

4742:    Not Collective

4744:    Input Parameters:
4745:      snes - SNES context

4747:    Output Parameters:
4748: +    version - version 1, 2 (default is 2) or 3
4749: .    rtol_0 - initial relative tolerance (0 <= rtol_0 < 1)
4750: .    rtol_max - maximum relative tolerance (0 <= rtol_max < 1)
4751: .    gamma - multiplicative factor for version 2 rtol computation (0 <= gamma2 <= 1)
4752: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4753: .    alpha2 - power for safeguard
4754: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4756:    Level: advanced

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

4760: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
4761: @*/
4762: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
4763: {
4764:   SNESKSPEW *kctx;

4768:   kctx = (SNESKSPEW*)snes->kspconvctx;
4769:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
4770:   if (version)   *version   = kctx->version;
4771:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
4772:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
4773:   if (gamma)     *gamma     = kctx->gamma;
4774:   if (alpha)     *alpha     = kctx->alpha;
4775:   if (alpha2)    *alpha2    = kctx->alpha2;
4776:   if (threshold) *threshold = kctx->threshold;
4777:   return(0);
4778: }

4780:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4781: {
4783:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4784:   PetscReal      rtol  = PETSC_DEFAULT,stol;

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

4821: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4822: {
4824:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4825:   PCSide         pcside;
4826:   Vec            lres;

4829:   if (!snes->ksp_ewconv) return(0);
4830:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
4831:   kctx->norm_last = snes->norm;
4832:   if (kctx->version == 1) {
4833:     PC        pc;
4834:     PetscBool isNone;

4836:     KSPGetPC(ksp, &pc);
4837:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
4838:     KSPGetPCSide(ksp,&pcside);
4839:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
4840:       /* KSP residual is true linear residual */
4841:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
4842:     } else {
4843:       /* KSP residual is preconditioned residual */
4844:       /* compute true linear residual norm */
4845:       VecDuplicate(b,&lres);
4846:       MatMult(snes->jacobian,x,lres);
4847:       VecAYPX(lres,-1.0,b);
4848:       VecNorm(lres,NORM_2,&kctx->lresid_last);
4849:       VecDestroy(&lres);
4850:     }
4851:   }
4852:   return(0);
4853: }

4855: /*@
4856:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

4860:    Input Parameter:
4861: .  snes - the SNES context

4863:    Output Parameter:
4864: .  ksp - the KSP context

4866:    Notes:
4867:    The user can then directly manipulate the KSP context to set various
4868:    options, etc.  Likewise, the user can then extract and manipulate the
4869:    PC contexts as well.

4871:    Level: beginner

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

4875: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
4876: @*/
4877: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
4878: {


4885:   if (!snes->ksp) {
4886:     PetscBool monitor = PETSC_FALSE;

4888:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
4889:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
4890:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

4895:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
4896:     if (monitor) {
4897:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
4898:     }
4899:     monitor = PETSC_FALSE;
4900:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
4901:     if (monitor) {
4902:       PetscObject *objs;
4903:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
4904:       objs[0] = (PetscObject) snes;
4905:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
4906:     }
4907:   }
4908:   *ksp = snes->ksp;
4909:   return(0);
4910: }


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

4917:    Logically Collective on SNES

4919:    Input Parameters:
4920: +  snes - the nonlinear solver context
4921: -  dm - the dm, cannot be NULL

4923:    Level: intermediate

4925: .seealso: SNESGetDM(), SNESHasDM(), KSPSetDM(), KSPGetDM()
4926: @*/
4927: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
4928: {
4930:   KSP            ksp;
4931:   DMSNES         sdm;

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

4948:   SNESGetKSP(snes,&ksp);
4949:   KSPSetDM(ksp,dm);
4950:   KSPSetDMActive(ksp,PETSC_FALSE);
4951:   if (snes->npc) {
4952:     SNESSetDM(snes->npc, snes->dm);
4953:     SNESSetNPCSide(snes,snes->npcside);
4954:   }
4955:   return(0);
4956: }

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

4961:    Not Collective but DM obtained is parallel on SNES

4963:    Input Parameter:
4964: . snes - the preconditioner context

4966:    Output Parameter:
4967: .  dm - the dm

4969:    Level: intermediate

4971: .seealso: SNESSetDM(), SNESHasDM(), KSPSetDM(), KSPGetDM()
4972: @*/
4973: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
4974: {

4979:   if (!snes->dm) {
4980:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
4981:     snes->dmAuto = PETSC_TRUE;
4982:   }
4983:   *dm = snes->dm;
4984:   return(0);
4985: }


4988: /*@
4989:    SNESHasDM - Whether snes has dm

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

4993:    Input Parameter:
4994: . snes - the nonlinear solver object

4996:    Output Parameter:
4997: .  hasdm - a flag indicates whether there is dm in snes

4999:    Level: intermediate

5001: .seealso: SNESGetDM(), SNESSetDM(), KSPSetDM(), KSPGetDM()
5002: @*/
5003: PetscErrorCode  SNESHasDM(SNES snes,PetscBool *hasdm)
5004: {
5008:   if (snes->dm) *hasdm = PETSC_TRUE;
5009:   else *hasdm = PETSC_FALSE;
5010:   return(0);
5011: }

5013: /*@
5014:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

5016:   Collective on SNES

5018:   Input Parameters:
5019: + snes - iterative context obtained from SNESCreate()
5020: - pc   - the preconditioner object

5022:   Notes:
5023:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
5024:   to configure it using the API).

5026:   Level: developer

5028: .keywords: SNES, set, precondition
5029: .seealso: SNESGetNPC(), SNESHasNPC()
5030: @*/
5031: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
5032: {

5039:   PetscObjectReference((PetscObject) pc);
5040:   SNESDestroy(&snes->npc);
5041:   snes->npc = pc;
5042:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->npc);
5043:   return(0);
5044: }

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

5049:   Not Collective

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

5054:   Output Parameter:
5055: . pc - preconditioner context

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

5059:   Level: developer

5061: .keywords: SNES, get, preconditioner
5062: .seealso: SNESSetNPC(), SNESHasNPC()
5063: @*/
5064: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
5065: {
5067:   const char     *optionsprefix;

5072:   if (!snes->npc) {
5073:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->npc);
5074:     PetscObjectIncrementTabLevel((PetscObject)snes->npc,(PetscObject)snes,1);
5075:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->npc);
5076:     SNESGetOptionsPrefix(snes,&optionsprefix);
5077:     SNESSetOptionsPrefix(snes->npc,optionsprefix);
5078:     SNESAppendOptionsPrefix(snes->npc,"npc_");
5079:     SNESSetCountersReset(snes->npc,PETSC_FALSE);
5080:   }
5081:   *pc = snes->npc;
5082:   return(0);
5083: }

5085: /*@
5086:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5088:   Not Collective

5090:   Input Parameter:
5091: . snes - iterative context obtained from SNESCreate()

5093:   Output Parameter:
5094: . has_npc - whether the SNES has an NPC or not

5096:   Level: developer

5098: .keywords: SNES, has, preconditioner
5099: .seealso: SNESSetNPC(), SNESGetNPC()
5100: @*/
5101: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5102: {
5105:   *has_npc = (PetscBool) (snes->npc ? PETSC_TRUE : PETSC_FALSE);
5106:   return(0);
5107: }

5109: /*@
5110:     SNESSetNPCSide - Sets the preconditioning side.

5112:     Logically Collective on SNES

5114:     Input Parameter:
5115: .   snes - iterative context obtained from SNESCreate()

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

5124:     Options Database Keys:
5125: .   -snes_pc_side <right,left>

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

5129:     Level: intermediate

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

5133: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5134: @*/
5135: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5136: {
5140:   snes->npcside= side;
5141:   return(0);
5142: }

5144: /*@
5145:     SNESGetNPCSide - Gets the preconditioning side.

5147:     Not Collective

5149:     Input Parameter:
5150: .   snes - iterative context obtained from SNESCreate()

5152:     Output Parameter:
5153: .   side - the preconditioning side, where side is one of
5154: .vb
5155:       PC_LEFT - left preconditioning
5156:       PC_RIGHT - right preconditioning (default for most nonlinear solvers)
5157: .ve

5159:     Level: intermediate

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

5163: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5164: @*/
5165: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5166: {
5170:   *side = snes->npcside;
5171:   return(0);
5172: }

5174: /*@
5175:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5177:   Collective on SNES

5179:   Input Parameters:
5180: + snes - iterative context obtained from SNESCreate()
5181: - linesearch   - the linesearch object

5183:   Notes:
5184:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5185:   to configure it using the API).

5187:   Level: developer

5189: .keywords: SNES, set, linesearch
5190: .seealso: SNESGetLineSearch()
5191: @*/
5192: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5193: {

5200:   PetscObjectReference((PetscObject) linesearch);
5201:   SNESLineSearchDestroy(&snes->linesearch);

5203:   snes->linesearch = linesearch;

5205:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5206:   return(0);
5207: }

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

5213:   Not Collective

5215:   Input Parameter:
5216: . snes - iterative context obtained from SNESCreate()

5218:   Output Parameter:
5219: . linesearch - linesearch context

5221:   Level: beginner

5223: .keywords: SNES, get, linesearch
5224: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5225: @*/
5226: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5227: {
5229:   const char     *optionsprefix;

5234:   if (!snes->linesearch) {
5235:     SNESGetOptionsPrefix(snes, &optionsprefix);
5236:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5237:     SNESLineSearchSetSNES(snes->linesearch, snes);
5238:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5239:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5240:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5241:   }
5242:   *linesearch = snes->linesearch;
5243:   return(0);
5244: }

5246: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5247: #include <mex.h>

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

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

5254:    Collective on SNES

5256:    Input Parameters:
5257: +  snes - the SNES context
5258: -  x - input vector

5260:    Output Parameter:
5261: .  y - function vector, as set by SNESSetFunction()

5263:    Notes:
5264:    SNESComputeFunction() is typically used within nonlinear solvers
5265:    implementations, so most users would not generally call this routine
5266:    themselves.

5268:    Level: developer

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

5272: .seealso: SNESSetFunction(), SNESGetFunction()
5273: */
5274: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5275: {
5276:   PetscErrorCode    ierr;
5277:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5278:   int               nlhs  = 1,nrhs = 5;
5279:   mxArray           *plhs[1],*prhs[5];
5280:   long long int     lx = 0,ly = 0,ls = 0;


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

5291:   PetscMemcpy(&ls,&snes,sizeof(snes));
5292:   PetscMemcpy(&lx,&x,sizeof(x));
5293:   PetscMemcpy(&ly,&y,sizeof(x));
5294:   prhs[0] = mxCreateDoubleScalar((double)ls);
5295:   prhs[1] = mxCreateDoubleScalar((double)lx);
5296:   prhs[2] = mxCreateDoubleScalar((double)ly);
5297:   prhs[3] = mxCreateString(sctx->funcname);
5298:   prhs[4] = sctx->ctx;
5299:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeFunctionInternal");
5300:   mxGetScalar(plhs[0]);
5301:   mxDestroyArray(prhs[0]);
5302:   mxDestroyArray(prhs[1]);
5303:   mxDestroyArray(prhs[2]);
5304:   mxDestroyArray(prhs[3]);
5305:   mxDestroyArray(plhs[0]);
5306:   return(0);
5307: }

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

5314:    Logically Collective on SNES

5316:    Input Parameters:
5317: +  snes - the SNES context
5318: .  r - vector to store function value
5319: -  f - function evaluation routine

5321:    Notes:
5322:    The Newton-like methods typically solve linear systems of the form
5323: $      f'(x) x = -f(x),
5324:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5326:    Level: beginner

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

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

5332: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5333: */
5334: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5335: {
5336:   PetscErrorCode    ierr;
5337:   SNESMatlabContext *sctx;

5340:   /* currently sctx is memory bleed */
5341:   PetscNew(&sctx);
5342:   PetscStrallocpy(f,&sctx->funcname);
5343:   /*
5344:      This should work, but it doesn't
5345:   sctx->ctx = ctx;
5346:   mexMakeArrayPersistent(sctx->ctx);
5347:   */
5348:   sctx->ctx = mxDuplicateArray(ctx);
5349:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5350:   return(0);
5351: }

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

5356:    Collective on SNES

5358:    Input Parameters:
5359: +  snes - the SNES context
5360: .  x - input vector
5361: .  A, B - the matrices
5362: -  ctx - user context

5364:    Level: developer

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

5368: .seealso: SNESSetFunction(), SNESGetFunction()
5369: @*/
5370: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5371: {
5372:   PetscErrorCode    ierr;
5373:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5374:   int               nlhs  = 2,nrhs = 6;
5375:   mxArray           *plhs[2],*prhs[6];
5376:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


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

5384:   PetscMemcpy(&ls,&snes,sizeof(snes));
5385:   PetscMemcpy(&lx,&x,sizeof(x));
5386:   PetscMemcpy(&lA,A,sizeof(x));
5387:   PetscMemcpy(&lB,B,sizeof(x));
5388:   prhs[0] = mxCreateDoubleScalar((double)ls);
5389:   prhs[1] = mxCreateDoubleScalar((double)lx);
5390:   prhs[2] = mxCreateDoubleScalar((double)lA);
5391:   prhs[3] = mxCreateDoubleScalar((double)lB);
5392:   prhs[4] = mxCreateString(sctx->funcname);
5393:   prhs[5] = sctx->ctx;
5394:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5395:   mxGetScalar(plhs[0]);
5396:   mxDestroyArray(prhs[0]);
5397:   mxDestroyArray(prhs[1]);
5398:   mxDestroyArray(prhs[2]);
5399:   mxDestroyArray(prhs[3]);
5400:   mxDestroyArray(prhs[4]);
5401:   mxDestroyArray(plhs[0]);
5402:   mxDestroyArray(plhs[1]);
5403:   return(0);
5404: }

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

5411:    Logically Collective on SNES

5413:    Input Parameters:
5414: +  snes - the SNES context
5415: .  A,B - Jacobian matrices
5416: .  J - function evaluation routine
5417: -  ctx - user context

5419:    Level: developer

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

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

5425: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5426: */
5427: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5428: {
5429:   PetscErrorCode    ierr;
5430:   SNESMatlabContext *sctx;

5433:   /* currently sctx is memory bleed */
5434:   PetscNew(&sctx);
5435:   PetscStrallocpy(J,&sctx->funcname);
5436:   /*
5437:      This should work, but it doesn't
5438:   sctx->ctx = ctx;
5439:   mexMakeArrayPersistent(sctx->ctx);
5440:   */
5441:   sctx->ctx = mxDuplicateArray(ctx);
5442:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5443:   return(0);
5444: }

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

5449:    Collective on SNES

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


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

5484: /*
5485:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5487:    Level: developer

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

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

5493: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5494: */
5495: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5496: {
5497:   PetscErrorCode    ierr;
5498:   SNESMatlabContext *sctx;

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

5514: #endif