Actual source code: snes.c

petsc-3.7.3 2016-08-01
Report Typos and Errors
  2: #include <petsc/private/snesimpl.h>      /*I "petscsnes.h"  I*/
  3: #include <petscdmshell.h>
  4: #include <petscdraw.h>

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

  9: /* Logging support */
 10: PetscClassId  SNES_CLASSID, DMSNES_CLASSID;
 11: 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: }

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

 51:    Not Collective

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

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

 59:    Level: intermediate

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

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

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

 80:    Logically Collective on SNES

 82:    Input Parameters:
 83: .  snes - the SNES context

 85:    Level: advanced

 87: .keywords: SNES, view

 89: .seealso: SNESCreate(), SNESSetFunction(), SNESFunction
 90: @*/
 91: PetscErrorCode  SNESSetFunctionDomainError(SNES snes)
 92: {
 95:   if (snes->errorifnotconverged) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"User code indicates input vector is not in the function domain");
 96:   snes->domainerror = PETSC_TRUE;
 97:   return(0);
 98: }

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

105:    Logically Collective on SNES

107:    Input Parameters:
108: .  snes - the SNES context

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

113:    Level: advanced

115: .keywords: SNES, view

117: .seealso: SNESSetFunctionDomainError(), SNESComputeFunction()
118: @*/
119: PetscErrorCode  SNESGetFunctionDomainError(SNES snes, PetscBool *domainerror)
120: {
124:   *domainerror = snes->domainerror;
125:   return(0);
126: }

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

133:   Collective on PetscViewer

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

140:    Level: intermediate

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

145:   Notes for advanced users:
146:   Most users should not need to know the details of the binary storage
147:   format, since SNESLoad() and TSView() completely hide these details.
148:   But for anyone who's interested, the standard binary matrix storage
149:   format is
150: .vb
151:      has not yet been determined
152: .ve

154: .seealso: PetscViewerBinaryOpen(), SNESView(), MatLoad(), VecLoad()
155: @*/
156: PetscErrorCode  SNESLoad(SNES snes, PetscViewer viewer)
157: {
159:   PetscBool      isbinary;
160:   PetscInt       classid;
161:   char           type[256];
162:   KSP            ksp;
163:   DM             dm;
164:   DMSNES         dmsnes;

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

172:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
173:   if (classid != SNES_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_WRONG,"Not SNES next in file");
174:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
175:   SNESSetType(snes, type);
176:   if (snes->ops->load) {
177:     (*snes->ops->load)(snes,viewer);
178:   }
179:   SNESGetDM(snes,&dm);
180:   DMGetDMSNES(dm,&dmsnes);
181:   DMSNESLoad(dmsnes,viewer);
182:   SNESGetKSP(snes,&ksp);
183:   KSPLoad(ksp,viewer);
184:   return(0);
185: }

187: #include <petscdraw.h>
188: #if defined(PETSC_HAVE_SAWS)
189: #include <petscviewersaws.h>
190: #endif
193: /*@C
194:    SNESView - Prints the SNES data structure.

196:    Collective on SNES

198:    Input Parameters:
199: +  SNES - the SNES context
200: -  viewer - visualization context

202:    Options Database Key:
203: .  -snes_view - Calls SNESView() at end of SNESSolve()

205:    Notes:
206:    The available visualization contexts include
207: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
208: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
209:          output where only the first processor opens
210:          the file.  All other processors send their
211:          data to the first processor to print.

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

216:    Level: beginner

218: .keywords: SNES, view

220: .seealso: PetscViewerASCIIOpen()
221: @*/
222: PetscErrorCode  SNESView(SNES snes,PetscViewer viewer)
223: {
224:   SNESKSPEW      *kctx;
226:   KSP            ksp;
227:   SNESLineSearch linesearch;
228:   PetscBool      iascii,isstring,isbinary,isdraw;
229:   DMSNES         dmsnes;
230: #if defined(PETSC_HAVE_SAWS)
231:   PetscBool      issaws;
232: #endif

236:   if (!viewer) {
237:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&viewer);
238:   }

242:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
243:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
244:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
245:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
246: #if defined(PETSC_HAVE_SAWS)
247:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
248: #endif
249:   if (iascii) {
250:     SNESNormSchedule normschedule;

252:     PetscObjectPrintClassNamePrefixType((PetscObject)snes,viewer);
253:     if (!snes->setupcalled) {
254:       PetscViewerASCIIPrintf(viewer,"  SNES has not been set up so information may be incomplete\n");
255:     }
256:     if (snes->ops->view) {
257:       PetscViewerASCIIPushTab(viewer);
258:       (*snes->ops->view)(snes,viewer);
259:       PetscViewerASCIIPopTab(viewer);
260:     }
261:     PetscViewerASCIIPrintf(viewer,"  maximum iterations=%D, maximum function evaluations=%D\n",snes->max_its,snes->max_funcs);
262:     PetscViewerASCIIPrintf(viewer,"  tolerances: relative=%g, absolute=%g, solution=%g\n",(double)snes->rtol,(double)snes->abstol,(double)snes->stol);
263:     PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",snes->linear_its);
264:     PetscViewerASCIIPrintf(viewer,"  total number of function evaluations=%D\n",snes->nfuncs);
265:     SNESGetNormSchedule(snes, &normschedule);
266:     if (normschedule > 0) {PetscViewerASCIIPrintf(viewer,"  norm schedule %s\n",SNESNormSchedules[normschedule]);}
267:     if (snes->gridsequence) {
268:       PetscViewerASCIIPrintf(viewer,"  total number of grid sequence refinements=%D\n",snes->gridsequence);
269:     }
270:     if (snes->ksp_ewconv) {
271:       kctx = (SNESKSPEW*)snes->kspconvctx;
272:       if (kctx) {
273:         PetscViewerASCIIPrintf(viewer,"  Eisenstat-Walker computation of KSP relative tolerance (version %D)\n",kctx->version);
274:         PetscViewerASCIIPrintf(viewer,"    rtol_0=%g, rtol_max=%g, threshold=%g\n",(double)kctx->rtol_0,(double)kctx->rtol_max,(double)kctx->threshold);
275:         PetscViewerASCIIPrintf(viewer,"    gamma=%g, alpha=%g, alpha2=%g\n",(double)kctx->gamma,(double)kctx->alpha,(double)kctx->alpha2);
276:       }
277:     }
278:     if (snes->lagpreconditioner == -1) {
279:       PetscViewerASCIIPrintf(viewer,"  Preconditioned is never rebuilt\n");
280:     } else if (snes->lagpreconditioner > 1) {
281:       PetscViewerASCIIPrintf(viewer,"  Preconditioned is rebuilt every %D new Jacobians\n",snes->lagpreconditioner);
282:     }
283:     if (snes->lagjacobian == -1) {
284:       PetscViewerASCIIPrintf(viewer,"  Jacobian is never rebuilt\n");
285:     } else if (snes->lagjacobian > 1) {
286:       PetscViewerASCIIPrintf(viewer,"  Jacobian is rebuilt every %D SNES iterations\n",snes->lagjacobian);
287:     }
288:   } else if (isstring) {
289:     const char *type;
290:     SNESGetType(snes,&type);
291:     PetscViewerStringSPrintf(viewer," %-3.3s",type);
292:   } else if (isbinary) {
293:     PetscInt    classid = SNES_FILE_CLASSID;
294:     MPI_Comm    comm;
295:     PetscMPIInt rank;
296:     char        type[256];

298:     PetscObjectGetComm((PetscObject)snes,&comm);
299:     MPI_Comm_rank(comm,&rank);
300:     if (!rank) {
301:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
302:       PetscStrncpy(type,((PetscObject)snes)->type_name,sizeof(type));
303:       PetscViewerBinaryWrite(viewer,type,sizeof(type),PETSC_CHAR,PETSC_FALSE);
304:     }
305:     if (snes->ops->view) {
306:       (*snes->ops->view)(snes,viewer);
307:     }
308:   } else if (isdraw) {
309:     PetscDraw draw;
310:     char      str[36];
311:     PetscReal x,y,bottom,h;

313:     PetscViewerDrawGetDraw(viewer,0,&draw);
314:     PetscDrawGetCurrentPoint(draw,&x,&y);
315:     PetscStrcpy(str,"SNES: ");
316:     PetscStrcat(str,((PetscObject)snes)->type_name);
317:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLUE,PETSC_DRAW_BLACK,str,NULL,&h);
318:     bottom = y - h;
319:     PetscDrawPushCurrentPoint(draw,x,bottom);
320:     if (snes->ops->view) {
321:       (*snes->ops->view)(snes,viewer);
322:     }
323: #if defined(PETSC_HAVE_SAWS)
324:   } else if (issaws) {
325:     PetscMPIInt rank;
326:     const char *name;

328:     PetscObjectGetName((PetscObject)snes,&name);
329:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
330:     if (!((PetscObject)snes)->amsmem && !rank) {
331:       char       dir[1024];

333:       PetscObjectViewSAWs((PetscObject)snes,viewer);
334:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/its",name);
335:       PetscStackCallSAWs(SAWs_Register,(dir,&snes->iter,1,SAWs_READ,SAWs_INT));
336:       if (!snes->conv_hist) {
337:         SNESSetConvergenceHistory(snes,NULL,NULL,PETSC_DECIDE,PETSC_TRUE);
338:       }
339:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/conv_hist",name);
340:       PetscStackCallSAWs(SAWs_Register,(dir,snes->conv_hist,10,SAWs_READ,SAWs_DOUBLE));
341:     }
342: #endif
343:   }
344:   if (snes->linesearch) {
345:     PetscViewerASCIIPushTab(viewer);
346:     SNESGetLineSearch(snes, &linesearch);
347:     SNESLineSearchView(linesearch, viewer);
348:     PetscViewerASCIIPopTab(viewer);
349:   }
350:   if (snes->pc && snes->usespc) {
351:     PetscViewerASCIIPushTab(viewer);
352:     SNESView(snes->pc, viewer);
353:     PetscViewerASCIIPopTab(viewer);
354:   }
355:   PetscViewerASCIIPushTab(viewer);
356:   DMGetDMSNES(snes->dm,&dmsnes);
357:   DMSNESView(dmsnes, viewer);
358:   PetscViewerASCIIPopTab(viewer);
359:   if (snes->usesksp) {
360:     SNESGetKSP(snes,&ksp);
361:     PetscViewerASCIIPushTab(viewer);
362:     KSPView(ksp,viewer);
363:     PetscViewerASCIIPopTab(viewer);
364:   }
365:   if (isdraw) {
366:     PetscDraw draw;
367:     PetscViewerDrawGetDraw(viewer,0,&draw);
368:     PetscDrawPopCurrentPoint(draw);
369:   }
370:   return(0);
371: }

373: /*
374:   We retain a list of functions that also take SNES command
375:   line options. These are called at the end SNESSetFromOptions()
376: */
377: #define MAXSETFROMOPTIONS 5
378: static PetscInt numberofsetfromoptions;
379: static PetscErrorCode (*othersetfromoptions[MAXSETFROMOPTIONS])(SNES);

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

386:   Not Collective

388:   Input Parameter:
389: . snescheck - function that checks for options

391:   Level: developer

393: .seealso: SNESSetFromOptions()
394: @*/
395: PetscErrorCode  SNESAddOptionsChecker(PetscErrorCode (*snescheck)(SNES))
396: {
398:   if (numberofsetfromoptions >= MAXSETFROMOPTIONS) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "Too many options checkers, only %D allowed", MAXSETFROMOPTIONS);
399:   othersetfromoptions[numberofsetfromoptions++] = snescheck;
400:   return(0);
401: }

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

407: static PetscErrorCode SNESSetUpMatrixFree_Private(SNES snes, PetscBool hasOperator, PetscInt version)
408: {
409:   Mat            J;
410:   KSP            ksp;
411:   PC             pc;
412:   PetscBool      match;
414:   MatNullSpace   nullsp;


419:   if (!snes->vec_func && (snes->jacobian || snes->jacobian_pre)) {
420:     Mat A = snes->jacobian, B = snes->jacobian_pre;
421:     MatCreateVecs(A ? A : B, NULL,&snes->vec_func);
422:   }

424:   if (version == 1) {
425:     MatCreateSNESMF(snes,&J);
426:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
427:     MatSetFromOptions(J);
428:   } else if (version == 2) {
429:     if (!snes->vec_func) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"SNESSetFunction() must be called first");
430: #if !defined(PETSC_USE_COMPLEX) && !defined(PETSC_USE_REAL_SINGLE) && !defined(PETSC_USE_REAL___FLOAT128)
431:     SNESDefaultMatrixFreeCreate2(snes,snes->vec_func,&J);
432: #else
433:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "matrix-free operator rutines (version 2)");
434: #endif
435:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE, "matrix-free operator rutines, only version 1 and 2");

437:   /* attach any user provided null space that was on Amat to the newly created matrix free matrix */
438:   if (snes->jacobian) {
439:     MatGetNullSpace(snes->jacobian,&nullsp);
440:     if (nullsp) {
441:       MatSetNullSpace(J,nullsp);
442:     }
443:   }

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

448:     /* This version replaces the user provided Jacobian matrix with a
449:        matrix-free version but still employs the user-provided preconditioner matrix. */
450:     SNESSetJacobian(snes,J,0,0,0);
451:   } else {
452:     /* This version replaces both the user-provided Jacobian and the user-
453:      provided preconditioner Jacobian with the default matrix free version. */
454:     if ((snes->pcside == PC_LEFT) && snes->pc) {
455:       if (!snes->jacobian){SNESSetJacobian(snes,J,0,0,0);}
456:     } else {
457:       SNESSetJacobian(snes,J,J,MatMFFDComputeJacobian,0);
458:     }
459:     /* Force no preconditioner */
460:     SNESGetKSP(snes,&ksp);
461:     KSPGetPC(ksp,&pc);
462:     PetscObjectTypeCompare((PetscObject)pc,PCSHELL,&match);
463:     if (!match) {
464:       PetscInfo(snes,"Setting default matrix-free preconditioner routines\nThat is no preconditioner is being used\n");
465:       PCSetType(pc,PCNONE);
466:     }
467:   }
468:   MatDestroy(&J);
469:   return(0);
470: }

474: static PetscErrorCode DMRestrictHook_SNESVecSol(DM dmfine,Mat Restrict,Vec Rscale,Mat Inject,DM dmcoarse,void *ctx)
475: {
476:   SNES           snes = (SNES)ctx;
478:   Vec            Xfine,Xfine_named = NULL,Xcoarse;

481:   if (PetscLogPrintInfo) {
482:     PetscInt finelevel,coarselevel,fineclevel,coarseclevel;
483:     DMGetRefineLevel(dmfine,&finelevel);
484:     DMGetCoarsenLevel(dmfine,&fineclevel);
485:     DMGetRefineLevel(dmcoarse,&coarselevel);
486:     DMGetCoarsenLevel(dmcoarse,&coarseclevel);
487:     PetscInfo4(dmfine,"Restricting SNES solution vector from level %D-%D to level %D-%D\n",finelevel,fineclevel,coarselevel,coarseclevel);
488:   }
489:   if (dmfine == snes->dm) Xfine = snes->vec_sol;
490:   else {
491:     DMGetNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);
492:     Xfine = Xfine_named;
493:   }
494:   DMGetNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
495:   if (Inject) {
496:     MatRestrict(Inject,Xfine,Xcoarse);
497:   } else {
498:     MatRestrict(Restrict,Xfine,Xcoarse);
499:     VecPointwiseMult(Xcoarse,Xcoarse,Rscale);
500:   }
501:   DMRestoreNamedGlobalVector(dmcoarse,"SNESVecSol",&Xcoarse);
502:   if (Xfine_named) {DMRestoreNamedGlobalVector(dmfine,"SNESVecSol",&Xfine_named);}
503:   return(0);
504: }

508: static PetscErrorCode DMCoarsenHook_SNESVecSol(DM dm,DM dmc,void *ctx)
509: {

513:   DMCoarsenHookAdd(dmc,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,ctx);
514:   return(0);
515: }

519: /* This may be called to rediscretize the operator on levels of linear multigrid. The DM shuffle is so the user can
520:  * safely call SNESGetDM() in their residual evaluation routine. */
521: static PetscErrorCode KSPComputeOperators_SNES(KSP ksp,Mat A,Mat B,void *ctx)
522: {
523:   SNES           snes = (SNES)ctx;
525:   Mat            Asave = A,Bsave = B;
526:   Vec            X,Xnamed = NULL;
527:   DM             dmsave;
528:   void           *ctxsave;
529:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);

532:   dmsave = snes->dm;
533:   KSPGetDM(ksp,&snes->dm);
534:   if (dmsave == snes->dm) X = snes->vec_sol; /* We are on the finest level */
535:   else {                                     /* We are on a coarser level, this vec was initialized using a DM restrict hook */
536:     DMGetNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
537:     X    = Xnamed;
538:     SNESGetJacobian(snes,NULL,NULL,&jac,&ctxsave);
539:     /* If the DM's don't match up, the MatFDColoring context needed for the jacobian won't match up either -- fixit. */
540:     if (jac == SNESComputeJacobianDefaultColor) {
541:       SNESSetJacobian(snes,NULL,NULL,SNESComputeJacobianDefaultColor,0);
542:     }
543:   }
544:   /* put the previous context back */

546:   SNESComputeJacobian(snes,X,A,B);
547:   if (snes->dm != dmsave && jac == SNESComputeJacobianDefaultColor) {
548:     SNESSetJacobian(snes,NULL,NULL,jac,ctxsave);
549:   }

551:   if (A != Asave || B != Bsave) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_SUP,"No support for changing matrices at this time");
552:   if (Xnamed) {
553:     DMRestoreNamedGlobalVector(snes->dm,"SNESVecSol",&Xnamed);
554:   }
555:   snes->dm = dmsave;
556:   return(0);
557: }

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

564:    Collective

566:    Input Arguments:
567: .  snes - snes to configure

569:    Level: developer

571: .seealso: SNESSetUp()
572: @*/
573: PetscErrorCode SNESSetUpMatrices(SNES snes)
574: {
576:   DM             dm;
577:   DMSNES         sdm;

580:   SNESGetDM(snes,&dm);
581:   DMGetDMSNES(dm,&sdm);
582:   if (!sdm->ops->computejacobian) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_PLIB,"DMSNES not properly configured");
583:   else if (!snes->jacobian && snes->mf) {
584:     Mat  J;
585:     void *functx;
586:     MatCreateSNESMF(snes,&J);
587:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
588:     MatSetFromOptions(J);
589:     SNESGetFunction(snes,NULL,NULL,&functx);
590:     SNESSetJacobian(snes,J,J,0,0);
591:     MatDestroy(&J);
592:   } else if (snes->mf_operator && !snes->jacobian_pre && !snes->jacobian) {
593:     Mat J,B;
594:     MatCreateSNESMF(snes,&J);
595:     MatMFFDSetOptionsPrefix(J,((PetscObject)snes)->prefix);
596:     MatSetFromOptions(J);
597:     DMCreateMatrix(snes->dm,&B);
598:     /* sdm->computejacobian was already set to reach here */
599:     SNESSetJacobian(snes,J,B,NULL,NULL);
600:     MatDestroy(&J);
601:     MatDestroy(&B);
602:   } else if (!snes->jacobian_pre) {
603:     Mat J,B;
604:     J    = snes->jacobian;
605:     DMCreateMatrix(snes->dm,&B);
606:     SNESSetJacobian(snes,J ? J : B,B,NULL,NULL);
607:     MatDestroy(&B);
608:   }
609:   {
610:     KSP ksp;
611:     SNESGetKSP(snes,&ksp);
612:     KSPSetComputeOperators(ksp,KSPComputeOperators_SNES,snes);
613:     DMCoarsenHookAdd(snes->dm,DMCoarsenHook_SNESVecSol,DMRestrictHook_SNESVecSol,snes);
614:   }
615:   return(0);
616: }

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

623:    Collective on SNES

625:    Input Parameters:
626: +  snes - SNES object you wish to monitor
627: .  name - the monitor type one is seeking
628: .  help - message indicating what monitoring is done
629: .  manual - manual page for the monitor
630: .  monitor - the monitor function
631: -  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

633:    Level: developer

635: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
636:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
637:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
638:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
639:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
640:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
641:           PetscOptionsFList(), PetscOptionsEList()
642: @*/
643: PetscErrorCode  SNESMonitorSetFromOptions(SNES snes,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(SNES,PetscInt,PetscReal,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(SNES,PetscViewerAndFormat*))
644: {
645:   PetscErrorCode    ierr;
646:   PetscViewer       viewer;
647:   PetscViewerFormat format;
648:   PetscBool         flg;

651:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,name,&viewer,&format,&flg);
652:   if (flg) {
653:     PetscViewerAndFormat *vf;
654:     PetscViewerAndFormatCreate(viewer,format,&vf);
655:     PetscObjectDereference((PetscObject)viewer);
656:     if (monitorsetup) {
657:       (*monitorsetup)(snes,vf);
658:     }
659:     SNESMonitorSet(snes,(PetscErrorCode (*)(SNES,PetscInt,PetscReal,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
660:   }
661:   return(0);
662: }

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

669:    Collective on SNES

671:    Input Parameter:
672: .  snes - the SNES context

674:    Options Database Keys:
675: +  -snes_type <type> - newtonls, newtontr, ngmres, ncg, nrichardson, qn, vi, fas, SNESType for complete list
676: .  -snes_stol - convergence tolerance in terms of the norm
677:                 of the change in the solution between steps
678: .  -snes_atol <abstol> - absolute tolerance of residual norm
679: .  -snes_rtol <rtol> - relative decrease in tolerance norm from initial
680: .  -snes_max_it <max_it> - maximum number of iterations
681: .  -snes_max_funcs <max_funcs> - maximum number of function evaluations
682: .  -snes_max_fail <max_fail> - maximum number of line search failures allowed before stopping, default is none
683: .  -snes_max_linear_solve_fail - number of linear solver failures before SNESSolve() stops
684: .  -snes_lag_preconditioner <lag> - how often preconditioner is rebuilt (use -1 to never rebuild)
685: .  -snes_lag_jacobian <lag> - how often Jacobian is rebuilt (use -1 to never rebuild)
686: .  -snes_trtol <trtol> - trust region tolerance
687: .  -snes_no_convergence_test - skip convergence test in nonlinear
688:                                solver; hence iterations will continue until max_it
689:                                or some other criterion is reached. Saves expense
690:                                of convergence test
691: .  -snes_monitor [ascii][:filename][:viewer format] - prints residual norm at each iteration. if no filename given prints to stdout
692: .  -snes_monitor_solution [ascii binary draw][:filename][:viewer format] - plots solution at each iteration
693: .  -snes_monitor_residual [ascii binary draw][:filename][:viewer format] - plots residual (not its norm) at each iteration
694: .  -snes_monitor_solution_update [ascii binary draw][:filename][:viewer format] - plots update to solution at each iteration
695: .  -snes_monitor_lg_residualnorm - plots residual norm at each iteration
696: .  -snes_monitor_lg_range - plots residual norm at each iteration
697: .  -snes_fd - use finite differences to compute Jacobian; very slow, only for testing
698: .  -snes_fd_color - use finite differences with coloring to compute Jacobian
699: .  -snes_mf_ksp_monitor - if using matrix-free multiply then print h at each KSP iteration
700: -  -snes_converged_reason - print the reason for convergence/divergence after each solve

702:     Options Database for Eisenstat-Walker method:
703: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
704: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
705: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
706: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
707: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
708: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
709: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
710: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

712:    Notes:
713:    To see all options, run your program with the -help option or consult
714:    Users-Manual: ch_snes

716:    Level: beginner

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

720: .seealso: SNESSetOptionsPrefix()
721: @*/
722: PetscErrorCode  SNESSetFromOptions(SNES snes)
723: {
724:   PetscBool      flg,pcset,persist,set;
725:   PetscInt       i,indx,lag,grids;
726:   const char     *deft        = SNESNEWTONLS;
727:   const char     *convtests[] = {"default","skip"};
728:   SNESKSPEW      *kctx        = NULL;
729:   char           type[256], monfilename[PETSC_MAX_PATH_LEN];
731:   PCSide         pcside;
732:   const char     *optionsprefix;

736:   SNESRegisterAll();
737:   PetscObjectOptionsBegin((PetscObject)snes);
738:   if (((PetscObject)snes)->type_name) deft = ((PetscObject)snes)->type_name;
739:   PetscOptionsFList("-snes_type","Nonlinear solver method","SNESSetType",SNESList,deft,type,256,&flg);
740:   if (flg) {
741:     SNESSetType(snes,type);
742:   } else if (!((PetscObject)snes)->type_name) {
743:     SNESSetType(snes,deft);
744:   }
745:   PetscOptionsReal("-snes_stol","Stop if step length less than","SNESSetTolerances",snes->stol,&snes->stol,NULL);
746:   PetscOptionsReal("-snes_atol","Stop if function norm less than","SNESSetTolerances",snes->abstol,&snes->abstol,NULL);

748:   PetscOptionsReal("-snes_rtol","Stop if decrease in function norm less than","SNESSetTolerances",snes->rtol,&snes->rtol,NULL);
749:   PetscOptionsInt("-snes_max_it","Maximum iterations","SNESSetTolerances",snes->max_its,&snes->max_its,NULL);
750:   PetscOptionsInt("-snes_max_funcs","Maximum function evaluations","SNESSetTolerances",snes->max_funcs,&snes->max_funcs,NULL);
751:   PetscOptionsInt("-snes_max_fail","Maximum nonlinear step failures","SNESSetMaxNonlinearStepFailures",snes->maxFailures,&snes->maxFailures,NULL);
752:   PetscOptionsInt("-snes_max_linear_solve_fail","Maximum failures in linear solves allowed","SNESSetMaxLinearSolveFailures",snes->maxLinearSolveFailures,&snes->maxLinearSolveFailures,NULL);
753:   PetscOptionsBool("-snes_error_if_not_converged","Generate error if solver does not converge","SNESSetErrorIfNotConverged",snes->errorifnotconverged,&snes->errorifnotconverged,NULL);

755:   PetscOptionsInt("-snes_lag_preconditioner","How often to rebuild preconditioner","SNESSetLagPreconditioner",snes->lagpreconditioner,&lag,&flg);
756:   if (flg) {
757:     SNESSetLagPreconditioner(snes,lag);
758:   }
759:   PetscOptionsBool("-snes_lag_preconditioner_persists","Preconditioner lagging through multiple solves","SNESSetLagPreconditionerPersists",snes->lagjac_persist,&persist,&flg);
760:   if (flg) {
761:     SNESSetLagPreconditionerPersists(snes,persist);
762:   }
763:   PetscOptionsInt("-snes_lag_jacobian","How often to rebuild Jacobian","SNESSetLagJacobian",snes->lagjacobian,&lag,&flg);
764:   if (flg) {
765:     SNESSetLagJacobian(snes,lag);
766:   }
767:   PetscOptionsBool("-snes_lag_jacobian_persists","Jacobian lagging through multiple solves","SNESSetLagJacobianPersists",snes->lagjac_persist,&persist,&flg);
768:   if (flg) {
769:     SNESSetLagJacobianPersists(snes,persist);
770:   }

772:   PetscOptionsInt("-snes_grid_sequence","Use grid sequencing to generate initial guess","SNESSetGridSequence",snes->gridsequence,&grids,&flg);
773:   if (flg) {
774:     SNESSetGridSequence(snes,grids);
775:   }

777:   PetscOptionsEList("-snes_convergence_test","Convergence test","SNESSetConvergenceTest",convtests,2,"default",&indx,&flg);
778:   if (flg) {
779:     switch (indx) {
780:     case 0: SNESSetConvergenceTest(snes,SNESConvergedDefault,NULL,NULL); break;
781:     case 1: SNESSetConvergenceTest(snes,SNESConvergedSkip,NULL,NULL);    break;
782:     }
783:   }

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

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

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

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

795:   PetscOptionsInt("-snes_ksp_ew_version","Version 1, 2 or 3","SNESKSPSetParametersEW",kctx->version,&kctx->version,NULL);
796:   PetscOptionsReal("-snes_ksp_ew_rtol0","0 <= rtol0 < 1","SNESKSPSetParametersEW",kctx->rtol_0,&kctx->rtol_0,NULL);
797:   PetscOptionsReal("-snes_ksp_ew_rtolmax","0 <= rtolmax < 1","SNESKSPSetParametersEW",kctx->rtol_max,&kctx->rtol_max,NULL);
798:   PetscOptionsReal("-snes_ksp_ew_gamma","0 <= gamma <= 1","SNESKSPSetParametersEW",kctx->gamma,&kctx->gamma,NULL);
799:   PetscOptionsReal("-snes_ksp_ew_alpha","1 < alpha <= 2","SNESKSPSetParametersEW",kctx->alpha,&kctx->alpha,NULL);
800:   PetscOptionsReal("-snes_ksp_ew_alpha2","alpha2","SNESKSPSetParametersEW",kctx->alpha2,&kctx->alpha2,NULL);
801:   PetscOptionsReal("-snes_ksp_ew_threshold","0 < threshold < 1","SNESKSPSetParametersEW",kctx->threshold,&kctx->threshold,NULL);

803:   flg  = PETSC_FALSE;
804:   PetscOptionsBool("-snes_check_jacobian","Check each Jacobian with a differenced one","SNESUpdateCheckJacobian",flg,&flg,&set);
805:   if (set && flg) {
806:     SNESSetUpdate(snes,SNESUpdateCheckJacobian);
807:   }

809:   flg  = PETSC_FALSE;
810:   PetscOptionsBool("-snes_monitor_cancel","Remove all monitors","SNESMonitorCancel",flg,&flg,&set);
811:   if (set && flg) {SNESMonitorCancel(snes);}

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

817:   SNESMonitorSetFromOptions(snes,"-snes_monitor_ratio","Monitor ratios of the norm of function for consecutive steps","SNESMonitorRatio",SNESMonitorRatio,SNESMonitorRatioSetUp);
818:   SNESMonitorSetFromOptions(snes,"-snes_monitor_field","Monitor norm of function (split into fields)","SNESMonitorDefaultField",SNESMonitorDefaultField,NULL);
819:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution","View solution at each iteration","SNESMonitorSolution",SNESMonitorSolution,NULL);
820:   SNESMonitorSetFromOptions(snes,"-snes_monitor_solution_update","View correction at each iteration","SNESMonitorSolutionUpdate",SNESMonitorSolutionUpdate,NULL);
821:   SNESMonitorSetFromOptions(snes,"-snes_monitor_residual","View residual at each iteration","SNESMonitorResidual",SNESMonitorResidual,NULL);
822:   SNESMonitorSetFromOptions(snes,"-snes_monitor_jacupdate_spectrum","Print the change in the spectrum of the Jacobian","SNESMonitorJacUpdateSpectrum",SNESMonitorJacUpdateSpectrum,NULL);
823:   SNESMonitorSetFromOptions(snes,"-snes_monitor_fields","Monitor norm of function per field","SNESMonitorSet",SNESMonitorFields,NULL);

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


829:   flg  = PETSC_FALSE;
830:   PetscOptionsBool("-snes_monitor_lg_residualnorm","Plot function norm at each iteration","SNESMonitorLGResidualNorm",flg,&flg,NULL);
831:   if (flg) {
832:     PetscDrawLG ctx;

834:     SNESMonitorLGCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
835:     SNESMonitorSet(snes,SNESMonitorLGResidualNorm,ctx,(PetscErrorCode (*)(void**))PetscDrawLGDestroy);
836:   }
837:   flg  = PETSC_FALSE;
838:   PetscOptionsBool("-snes_monitor_lg_range","Plot function range at each iteration","SNESMonitorLGRange",flg,&flg,NULL);
839:   if (flg) {
840:     PetscViewer ctx;

842:     PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,&ctx);
843:     SNESMonitorSet(snes,SNESMonitorLGRange,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
844:   }



848:   flg  = PETSC_FALSE;
849:   PetscOptionsBool("-snes_fd","Use finite differences (slow) to compute Jacobian","SNESComputeJacobianDefault",flg,&flg,NULL);
850:   if (flg) {
851:     void *functx;
852:     SNESGetFunction(snes,NULL,NULL,&functx);
853:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefault,functx);
854:     PetscInfo(snes,"Setting default finite difference Jacobian matrix\n");
855:   }

857:   flg  = PETSC_FALSE;
858:   PetscOptionsBool("-snes_fd_function","Use finite differences (slow) to compute function from user objective","SNESObjectiveComputeFunctionDefaultFD",flg,&flg,NULL);
859:   if (flg) {
860:     SNESSetFunction(snes,NULL,SNESObjectiveComputeFunctionDefaultFD,NULL);
861:   }

863:   flg  = PETSC_FALSE;
864:   PetscOptionsBool("-snes_fd_color","Use finite differences with coloring to compute Jacobian","SNESComputeJacobianDefaultColor",flg,&flg,NULL);
865:   if (flg) {
866:     DM             dm;
867:     DMSNES         sdm;
868:     SNESGetDM(snes,&dm);
869:     DMGetDMSNES(dm,&sdm);
870:     sdm->jacobianctx = NULL;
871:     SNESSetJacobian(snes,snes->jacobian,snes->jacobian_pre,SNESComputeJacobianDefaultColor,0);
872:     PetscInfo(snes,"Setting default finite difference coloring Jacobian matrix\n");
873:   }

875:   flg  = PETSC_FALSE;
876:   PetscOptionsBool("-snes_mf_operator","Use a Matrix-Free Jacobian with user-provided preconditioner matrix","MatCreateSNESMF",PETSC_FALSE,&snes->mf_operator,&flg);
877:   if (flg && snes->mf_operator) {
878:     snes->mf_operator = PETSC_TRUE;
879:     snes->mf          = PETSC_TRUE;
880:   }
881:   flg  = PETSC_FALSE;
882:   PetscOptionsBool("-snes_mf","Use a Matrix-Free Jacobian with no preconditioner matrix","MatCreateSNESMF",PETSC_FALSE,&snes->mf,&flg);
883:   if (!flg && snes->mf_operator) snes->mf = PETSC_TRUE;
884:   PetscOptionsInt("-snes_mf_version","Matrix-Free routines version 1 or 2","None",snes->mf_version,&snes->mf_version,0);

886:   flg  = PETSC_FALSE;
887:   SNESGetNPCSide(snes,&pcside);
888:   PetscOptionsEnum("-snes_npc_side","SNES nonlinear preconditioner side","SNESSetNPCSide",PCSides,(PetscEnum)pcside,(PetscEnum*)&pcside,&flg);
889:   if (flg) {SNESSetNPCSide(snes,pcside);}

891: #if defined(PETSC_HAVE_SAWS)
892:   /*
893:     Publish convergence information using SAWs
894:   */
895:   flg  = PETSC_FALSE;
896:   PetscOptionsBool("-snes_monitor_saws","Publish SNES progress using SAWs","SNESMonitorSet",flg,&flg,NULL);
897:   if (flg) {
898:     void *ctx;
899:     SNESMonitorSAWsCreate(snes,&ctx);
900:     SNESMonitorSet(snes,SNESMonitorSAWs,ctx,SNESMonitorSAWsDestroy);
901:   }
902: #endif
903: #if defined(PETSC_HAVE_SAWS)
904:   {
905:   PetscBool set;
906:   flg  = PETSC_FALSE;
907:   PetscOptionsBool("-snes_saws_block","Block for SAWs at end of SNESSolve","PetscObjectSAWsBlock",((PetscObject)snes)->amspublishblock,&flg,&set);
908:   if (set) {
909:     PetscObjectSAWsSetBlock((PetscObject)snes,flg);
910:   }
911:   }
912: #endif

914:   for (i = 0; i < numberofsetfromoptions; i++) {
915:     (*othersetfromoptions[i])(snes);
916:   }

918:   if (snes->ops->setfromoptions) {
919:     (*snes->ops->setfromoptions)(PetscOptionsObject,snes);
920:   }

922:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
923:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)snes);
924:   PetscOptionsEnd();

926:   if (!snes->linesearch) {
927:     SNESGetLineSearch(snes, &snes->linesearch);
928:   }
929:   SNESLineSearchSetFromOptions(snes->linesearch);

931:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
932:   KSPSetOperators(snes->ksp,snes->jacobian,snes->jacobian_pre);
933:   KSPSetFromOptions(snes->ksp);

935:   /* if someone has set the SNES NPC type, create it. */
936:   SNESGetOptionsPrefix(snes, &optionsprefix);
937:   PetscOptionsHasName(((PetscObject)snes)->options,optionsprefix, "-npc_snes_type", &pcset);
938:   if (pcset && (!snes->pc)) {
939:     SNESGetNPC(snes, &snes->pc);
940:   }
941:   return(0);
942: }

946: /*@C
947:    SNESSetComputeApplicationContext - Sets an optional function to compute a user-defined context for
948:    the nonlinear solvers.

950:    Logically Collective on SNES

952:    Input Parameters:
953: +  snes - the SNES context
954: .  compute - function to compute the context
955: -  destroy - function to destroy the context

957:    Level: intermediate

959:    Notes:
960:    This function is currently not available from Fortran.

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

964: .seealso: SNESGetApplicationContext(), SNESSetComputeApplicationContext(), SNESGetApplicationContext()
965: @*/
966: PetscErrorCode  SNESSetComputeApplicationContext(SNES snes,PetscErrorCode (*compute)(SNES,void**),PetscErrorCode (*destroy)(void**))
967: {
970:   snes->ops->usercompute = compute;
971:   snes->ops->userdestroy = destroy;
972:   return(0);
973: }

977: /*@
978:    SNESSetApplicationContext - Sets the optional user-defined context for
979:    the nonlinear solvers.

981:    Logically Collective on SNES

983:    Input Parameters:
984: +  snes - the SNES context
985: -  usrP - optional user context

987:    Level: intermediate

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

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

994: .seealso: SNESGetApplicationContext()
995: @*/
996: PetscErrorCode  SNESSetApplicationContext(SNES snes,void *usrP)
997: {
999:   KSP            ksp;

1003:   SNESGetKSP(snes,&ksp);
1004:   KSPSetApplicationContext(ksp,usrP);
1005:   snes->user = usrP;
1006:   return(0);
1007: }

1011: /*@
1012:    SNESGetApplicationContext - Gets the user-defined context for the
1013:    nonlinear solvers.

1015:    Not Collective

1017:    Input Parameter:
1018: .  snes - SNES context

1020:    Output Parameter:
1021: .  usrP - user context

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

1026:    Level: intermediate

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

1030: .seealso: SNESSetApplicationContext()
1031: @*/
1032: PetscErrorCode  SNESGetApplicationContext(SNES snes,void *usrP)
1033: {
1036:   *(void**)usrP = snes->user;
1037:   return(0);
1038: }

1042: /*@
1043:    SNESGetIterationNumber - Gets the number of nonlinear iterations completed
1044:    at this time.

1046:    Not Collective

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

1051:    Output Parameter:
1052: .  iter - iteration number

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

1057:    This is useful for using lagged Jacobians (where one does not recompute the
1058:    Jacobian at each SNES iteration). For example, the code
1059: .vb
1060:       SNESGetIterationNumber(snes,&it);
1061:       if (!(it % 2)) {
1062:         [compute Jacobian here]
1063:       }
1064: .ve
1065:    can be used in your ComputeJacobian() function to cause the Jacobian to be
1066:    recomputed every second SNES iteration.

1068:    Level: intermediate

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

1072: .seealso:   SNESGetLinearSolveIterations()
1073: @*/
1074: PetscErrorCode  SNESGetIterationNumber(SNES snes,PetscInt *iter)
1075: {
1079:   *iter = snes->iter;
1080:   return(0);
1081: }

1085: /*@
1086:    SNESSetIterationNumber - Sets the current iteration number.

1088:    Not Collective

1090:    Input Parameter:
1091: .  snes - SNES context
1092: .  iter - iteration number

1094:    Level: developer

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

1098: .seealso:   SNESGetLinearSolveIterations()
1099: @*/
1100: PetscErrorCode  SNESSetIterationNumber(SNES snes,PetscInt iter)
1101: {

1106:   PetscObjectSAWsTakeAccess((PetscObject)snes);
1107:   snes->iter = iter;
1108:   PetscObjectSAWsGrantAccess((PetscObject)snes);
1109:   return(0);
1110: }

1114: /*@
1115:    SNESGetNonlinearStepFailures - Gets the number of unsuccessful steps
1116:    attempted by the nonlinear solver.

1118:    Not Collective

1120:    Input Parameter:
1121: .  snes - SNES context

1123:    Output Parameter:
1124: .  nfails - number of unsuccessful steps attempted

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

1129:    Level: intermediate

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

1133: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1134:           SNESSetMaxNonlinearStepFailures(), SNESGetMaxNonlinearStepFailures()
1135: @*/
1136: PetscErrorCode  SNESGetNonlinearStepFailures(SNES snes,PetscInt *nfails)
1137: {
1141:   *nfails = snes->numFailures;
1142:   return(0);
1143: }

1147: /*@
1148:    SNESSetMaxNonlinearStepFailures - Sets the maximum number of unsuccessful steps
1149:    attempted by the nonlinear solver before it gives up.

1151:    Not Collective

1153:    Input Parameters:
1154: +  snes     - SNES context
1155: -  maxFails - maximum of unsuccessful steps

1157:    Level: intermediate

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

1161: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1162:           SNESGetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()
1163: @*/
1164: PetscErrorCode  SNESSetMaxNonlinearStepFailures(SNES snes, PetscInt maxFails)
1165: {
1168:   snes->maxFailures = maxFails;
1169:   return(0);
1170: }

1174: /*@
1175:    SNESGetMaxNonlinearStepFailures - Gets the maximum number of unsuccessful steps
1176:    attempted by the nonlinear solver before it gives up.

1178:    Not Collective

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

1183:    Output Parameter:
1184: .  maxFails - maximum of unsuccessful steps

1186:    Level: intermediate

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

1190: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(),
1191:           SNESSetMaxNonlinearStepFailures(), SNESGetNonlinearStepFailures()

1193: @*/
1194: PetscErrorCode  SNESGetMaxNonlinearStepFailures(SNES snes, PetscInt *maxFails)
1195: {
1199:   *maxFails = snes->maxFailures;
1200:   return(0);
1201: }

1205: /*@
1206:    SNESGetNumberFunctionEvals - Gets the number of user provided function evaluations
1207:      done by SNES.

1209:    Not Collective

1211:    Input Parameter:
1212: .  snes     - SNES context

1214:    Output Parameter:
1215: .  nfuncs - number of evaluations

1217:    Level: intermediate

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

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

1223: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures(), SNESGetLinearSolveFailures(), SNESSetCountersReset()
1224: @*/
1225: PetscErrorCode  SNESGetNumberFunctionEvals(SNES snes, PetscInt *nfuncs)
1226: {
1230:   *nfuncs = snes->nfuncs;
1231:   return(0);
1232: }

1236: /*@
1237:    SNESGetLinearSolveFailures - Gets the number of failed (non-converged)
1238:    linear solvers.

1240:    Not Collective

1242:    Input Parameter:
1243: .  snes - SNES context

1245:    Output Parameter:
1246: .  nfails - number of failed solves

1248:    Level: intermediate

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

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

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

1258: .seealso: SNESGetMaxLinearSolveFailures(), SNESGetLinearSolveIterations(), SNESSetMaxLinearSolveFailures()
1259: @*/
1260: PetscErrorCode  SNESGetLinearSolveFailures(SNES snes,PetscInt *nfails)
1261: {
1265:   *nfails = snes->numLinearSolveFailures;
1266:   return(0);
1267: }

1271: /*@
1272:    SNESSetMaxLinearSolveFailures - the number of failed linear solve attempts
1273:    allowed before SNES returns with a diverged reason of SNES_DIVERGED_LINEAR_SOLVE

1275:    Logically Collective on SNES

1277:    Input Parameters:
1278: +  snes     - SNES context
1279: -  maxFails - maximum allowed linear solve failures

1281:    Level: intermediate

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

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

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

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

1303: /*@
1304:    SNESGetMaxLinearSolveFailures - gets the maximum number of linear solve failures that
1305:      are allowed before SNES terminates

1307:    Not Collective

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

1312:    Output Parameter:
1313: .  maxFails - maximum of unsuccessful solves allowed

1315:    Level: intermediate

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

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

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

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

1338:    Not Collective

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

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

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

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

1352:    Level: intermediate

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

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

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

1373:    Logically Collective on SNES

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

1379:    Notes:
1380:    This defaults to PETSC_TRUE

1382:    Level: developer

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

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


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

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

1405:    Input Parameters:
1406: +  snes - the SNES context
1407: -  ksp - the KSP context

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

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

1416:    Level: developer

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

1420: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
1421: @*/
1422: PetscErrorCode  SNESSetKSP(SNES snes,KSP ksp)
1423: {

1430:   PetscObjectReference((PetscObject)ksp);
1431:   if (snes->ksp) {PetscObjectDereference((PetscObject)snes->ksp);}
1432:   snes->ksp = ksp;
1433:   return(0);
1434: }

1436: /* -----------------------------------------------------------*/
1439: /*@
1440:    SNESCreate - Creates a nonlinear solver context.

1442:    Collective on MPI_Comm

1444:    Input Parameters:
1445: .  comm - MPI communicator

1447:    Output Parameter:
1448: .  outsnes - the new SNES context

1450:    Options Database Keys:
1451: +   -snes_mf - Activates default matrix-free Jacobian-vector products,
1452:                and no preconditioning matrix
1453: .   -snes_mf_operator - Activates default matrix-free Jacobian-vector
1454:                products, and a user-provided preconditioning matrix
1455:                as set by SNESSetJacobian()
1456: -   -snes_fd - Uses (slow!) finite differences to compute Jacobian

1458:    Level: beginner

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

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

1464: @*/
1465: PetscErrorCode  SNESCreate(MPI_Comm comm,SNES *outsnes)
1466: {
1468:   SNES           snes;
1469:   SNESKSPEW      *kctx;

1473:   *outsnes = NULL;
1474:   SNESInitializePackage();

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

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

1535:   snes->mf          = PETSC_FALSE;
1536:   snes->mf_operator = PETSC_FALSE;
1537:   snes->mf_version  = 1;

1539:   snes->numLinearSolveFailures = 0;
1540:   snes->maxLinearSolveFailures = 1;

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

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

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

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

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

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

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

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

1579:    Level: intermediate

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

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

1591:    Logically Collective on SNES

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

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

1605:    Level: beginner

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

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

1618:   if (r) {
1621:     PetscObjectReference((PetscObject)r);
1622:     VecDestroy(&snes->vec_func);

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


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

1641:    Logically Collective on SNES

1643:    Input Parameters:
1644: +  snes - the SNES context
1645: -  f - vector to store function value

1647:    Notes:
1648:    This should not be modified during the solution procedure.

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

1652:    Level: developer

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

1656: .seealso: SNESSetFunction(), SNESComputeFunction(), SNESSetInitialFunctionNorm()
1657: @*/
1658: PetscErrorCode  SNESSetInitialFunction(SNES snes, Vec f)
1659: {
1661:   Vec            vec_func;

1667:   if (snes->pcside == PC_LEFT && snes->functype == SNES_FUNCTION_PRECONDITIONED) {
1668:     snes->vec_func_init_set = PETSC_FALSE;
1669:     return(0);
1670:   }
1671:   SNESGetFunction(snes,&vec_func,NULL,NULL);
1672:   VecCopy(f, vec_func);

1674:   snes->vec_func_init_set = PETSC_TRUE;
1675:   return(0);
1676: }

1680: /*@
1681:    SNESSetNormSchedule - Sets the SNESNormSchedule used in covergence and monitoring
1682:    of the SNES method.

1684:    Logically Collective on SNES

1686:    Input Parameters:
1687: +  snes - the SNES context
1688: -  normschedule - the frequency of norm computation

1690:    Options Database Key:
1691: .  -snes_norm_schedule <none, always, initialonly, finalonly, initalfinalonly>

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

1702:    Level: developer

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

1706: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1707: @*/
1708: PetscErrorCode  SNESSetNormSchedule(SNES snes, SNESNormSchedule normschedule)
1709: {
1712:   snes->normschedule = normschedule;
1713:   return(0);
1714: }


1719: /*@
1720:    SNESGetNormSchedule - Gets the SNESNormSchedule used in covergence and monitoring
1721:    of the SNES method.

1723:    Logically Collective on SNES

1725:    Input Parameters:
1726: +  snes - the SNES context
1727: -  normschedule - the type of the norm used

1729:    Level: advanced

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

1733: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1734: @*/
1735: PetscErrorCode  SNESGetNormSchedule(SNES snes, SNESNormSchedule *normschedule)
1736: {
1739:   *normschedule = snes->normschedule;
1740:   return(0);
1741: }


1746: /*@
1747:   SNESSetFunctionNorm - Sets the last computed residual norm.

1749:   Logically Collective on SNES

1751:   Input Parameters:
1752: + snes - the SNES context

1754: - normschedule - the frequency of norm computation

1756:   Level: developer

1758: .keywords: SNES, nonlinear, set, function, norm, type
1759: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1760: @*/
1761: PetscErrorCode SNESSetFunctionNorm(SNES snes, PetscReal norm)
1762: {
1765:   snes->norm = norm;
1766:   return(0);
1767: }

1771: /*@
1772:   SNESGetFunctionNorm - Gets the last computed norm of the residual

1774:   Not Collective

1776:   Input Parameter:
1777: . snes - the SNES context

1779:   Output Parameter:
1780: . norm - the last computed residual norm

1782:   Level: developer

1784: .keywords: SNES, nonlinear, set, function, norm, type
1785: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1786: @*/
1787: PetscErrorCode SNESGetFunctionNorm(SNES snes, PetscReal *norm)
1788: {
1792:   *norm = snes->norm;
1793:   return(0);
1794: }

1798: /*@C
1799:    SNESSetFunctionType - Sets the SNESNormSchedule used in covergence and monitoring
1800:    of the SNES method.

1802:    Logically Collective on SNES

1804:    Input Parameters:
1805: +  snes - the SNES context
1806: -  normschedule - the frequency of norm computation

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

1817:    Level: developer

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

1821: .seealso: SNESGetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1822: @*/
1823: PetscErrorCode  SNESSetFunctionType(SNES snes, SNESFunctionType type)
1824: {
1827:   snes->functype = type;
1828:   return(0);
1829: }


1834: /*@C
1835:    SNESGetFunctionType - Gets the SNESNormSchedule used in covergence and monitoring
1836:    of the SNES method.

1838:    Logically Collective on SNES

1840:    Input Parameters:
1841: +  snes - the SNES context
1842: -  normschedule - the type of the norm used

1844:    Level: advanced

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

1848: .seealso: SNESSetNormSchedule(), SNESComputeFunction(), VecNorm(), SNESSetFunction(), SNESSetInitialFunction(), SNESNormSchedule
1849: @*/
1850: PetscErrorCode  SNESGetFunctionType(SNES snes, SNESFunctionType *type)
1851: {
1854:   *type = snes->functype;
1855:   return(0);
1856: }

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

1861:      Synopsis:
1862:      #include <petscsnes.h>
1863: $    SNESNGSFunction(SNES snes,Vec x,Vec b,void *ctx);

1865: +  X   - solution vector
1866: .  B   - RHS vector
1867: -  ctx - optional user-defined Gauss-Seidel context

1869:    Level: intermediate

1871: .seealso:   SNESSetNGS(), SNESGetNGS()
1872: M*/

1876: /*@C
1877:    SNESSetNGS - Sets the user nonlinear Gauss-Seidel routine for
1878:    use with composed nonlinear solvers.

1880:    Input Parameters:
1881: +  snes   - the SNES context
1882: .  f - function evaluation routine to apply Gauss-Seidel see SNESNGSFunction
1883: -  ctx    - [optional] user-defined context for private data for the
1884:             smoother evaluation routine (may be NULL)

1886:    Notes:
1887:    The NGS routines are used by the composed nonlinear solver to generate
1888:     a problem appropriate update to the solution, particularly FAS.

1890:    Level: intermediate

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

1894: .seealso: SNESGetFunction(), SNESComputeNGS()
1895: @*/
1896: PetscErrorCode SNESSetNGS(SNES snes,PetscErrorCode (*f)(SNES,Vec,Vec,void*),void *ctx)
1897: {
1899:   DM             dm;

1903:   SNESGetDM(snes,&dm);
1904:   DMSNESSetNGS(dm,f,ctx);
1905:   return(0);
1906: }

1910: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES snes,Vec x,Vec f,void *ctx)
1911: {
1913:   DM             dm;
1914:   DMSNES         sdm;

1917:   SNESGetDM(snes,&dm);
1918:   DMGetDMSNES(dm,&sdm);
1919:   /*  A(x)*x - b(x) */
1920:   if (sdm->ops->computepfunction) {
1921:     (*sdm->ops->computepfunction)(snes,x,f,sdm->pctx);
1922:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard function.");

1924:   if (sdm->ops->computepjacobian) {
1925:     (*sdm->ops->computepjacobian)(snes,x,snes->jacobian,snes->jacobian_pre,sdm->pctx);
1926:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetPicard() to provide Picard matrix.");
1927:   VecScale(f,-1.0);
1928:   MatMultAdd(snes->jacobian,x,f,f);
1929:   return(0);
1930: }

1934: PETSC_EXTERN PetscErrorCode SNESPicardComputeJacobian(SNES snes,Vec x1,Mat J,Mat B,void *ctx)
1935: {
1937:   /* the jacobian matrix should be pre-filled in SNESPicardComputeFunction */
1938:   return(0);
1939: }

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

1946:    Logically Collective on SNES

1948:    Input Parameters:
1949: +  snes - the SNES context
1950: .  r - vector to store function value
1951: .  b - function evaluation routine
1952: .  Amat - matrix with which A(x) x - b(x) is to be computed
1953: .  Pmat - matrix from which preconditioner is computed (usually the same as Amat)
1954: .  J  - function to compute matrix value, see SNESJacobianFunction for details on its calling sequence
1955: -  ctx - [optional] user-defined context for private data for the
1956:          function evaluation routine (may be NULL)

1958:    Notes:
1959:     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
1960:     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.

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

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

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

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

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

1976:    Level: intermediate

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

1980: .seealso: SNESGetFunction(), SNESSetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESGetPicard(), SNESLineSearchPreCheckPicard(), SNESJacobianFunction
1981: @*/
1982: 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)
1983: {
1985:   DM             dm;

1989:   SNESGetDM(snes, &dm);
1990:   DMSNESSetPicard(dm,b,J,ctx);
1991:   SNESSetFunction(snes,r,SNESPicardComputeFunction,ctx);
1992:   SNESSetJacobian(snes,Amat,Pmat,SNESPicardComputeJacobian,ctx);
1993:   return(0);
1994: }

1998: /*@C
1999:    SNESGetPicard - Returns the context for the Picard iteration

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

2003:    Input Parameter:
2004: .  snes - the SNES context

2006:    Output Parameter:
2007: +  r - the function (or NULL)
2008: .  f - the function (or NULL); see SNESFunction for calling sequence details
2009: .  Amat - the matrix used to defined the operation A(x) x - b(x) (or NULL)
2010: .  Pmat  - the matrix from which the preconditioner will be constructed (or NULL)
2011: .  J - the function for matrix evaluation (or NULL); see SNESJacobianFunction for calling sequence details
2012: -  ctx - the function context (or NULL)

2014:    Level: advanced

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

2018: .seealso: SNESSetPicard(), SNESGetFunction(), SNESGetJacobian(), SNESGetDM(), SNESFunction, SNESJacobianFunction
2019: @*/
2020: 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)
2021: {
2023:   DM             dm;

2027:   SNESGetFunction(snes,r,NULL,NULL);
2028:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
2029:   SNESGetDM(snes,&dm);
2030:   DMSNESGetPicard(dm,f,J,ctx);
2031:   return(0);
2032: }

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

2039:    Logically Collective on SNES

2041:    Input Parameters:
2042: +  snes - the SNES context
2043: .  func - function evaluation routine
2044: -  ctx - [optional] user-defined context for private data for the
2045:          function evaluation routine (may be NULL)

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

2050: .  f - function vector
2051: -  ctx - optional user-defined function context

2053:    Level: intermediate

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

2057: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian()
2058: @*/
2059: PetscErrorCode  SNESSetComputeInitialGuess(SNES snes,PetscErrorCode (*func)(SNES,Vec,void*),void *ctx)
2060: {
2063:   if (func) snes->ops->computeinitialguess = func;
2064:   if (ctx)  snes->initialguessP            = ctx;
2065:   return(0);
2066: }

2068: /* --------------------------------------------------------------- */
2071: /*@C
2072:    SNESGetRhs - Gets the vector for solving F(x) = rhs. If rhs is not set
2073:    it assumes a zero right hand side.

2075:    Logically Collective on SNES

2077:    Input Parameter:
2078: .  snes - the SNES context

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

2083:    Level: intermediate

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

2087: .seealso: SNESGetSolution(), SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
2088: @*/
2089: PetscErrorCode  SNESGetRhs(SNES snes,Vec *rhs)
2090: {
2094:   *rhs = snes->vec_rhs;
2095:   return(0);
2096: }

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

2103:    Collective on SNES

2105:    Input Parameters:
2106: +  snes - the SNES context
2107: -  x - input vector

2109:    Output Parameter:
2110: .  y - function vector, as set by SNESSetFunction()

2112:    Notes:
2113:    SNESComputeFunction() is typically used within nonlinear solvers
2114:    implementations, so most users would not generally call this routine
2115:    themselves.

2117:    Level: developer

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

2121: .seealso: SNESSetFunction(), SNESGetFunction()
2122: @*/
2123: PetscErrorCode  SNESComputeFunction(SNES snes,Vec x,Vec y)
2124: {
2126:   DM             dm;
2127:   DMSNES         sdm;

2135:   VecValidValues(x,2,PETSC_TRUE);

2137:   SNESGetDM(snes,&dm);
2138:   DMGetDMSNES(dm,&sdm);
2139:   if (sdm->ops->computefunction) {
2140:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2141:       PetscLogEventBegin(SNES_FunctionEval,snes,x,y,0);
2142:     }
2143:     VecLockPush(x);
2144:     PetscStackPush("SNES user function");
2145:     (*sdm->ops->computefunction)(snes,x,y,sdm->functionctx);
2146:     PetscStackPop;
2147:     VecLockPop(x);
2148:     if (sdm->ops->computefunction != SNESObjectiveComputeFunctionDefaultFD) {
2149:       PetscLogEventEnd(SNES_FunctionEval,snes,x,y,0);
2150:     }
2151:   } else if (snes->vec_rhs) {
2152:     MatMult(snes->jacobian, x, y);
2153:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetFunction() or SNESSetDM() before SNESComputeFunction(), likely called from SNESSolve().");
2154:   if (snes->vec_rhs) {
2155:     VecAXPY(y,-1.0,snes->vec_rhs);
2156:   }
2157:   snes->nfuncs++;
2158:   /*
2159:      domainerror might not be set on all processes; so we tag vector locally with Inf and the next inner product or norm will
2160:      propagate the value to all processes
2161:   */
2162:   if (snes->domainerror) {
2163:     VecSetInf(y);
2164:   }
2165:   return(0);
2166: }

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

2173:    Collective on SNES

2175:    Input Parameters:
2176: +  snes - the SNES context
2177: .  x - input vector
2178: -  b - rhs vector

2180:    Output Parameter:
2181: .  x - new solution vector

2183:    Notes:
2184:    SNESComputeNGS() is typically used within composed nonlinear solver
2185:    implementations, so most users would not generally call this routine
2186:    themselves.

2188:    Level: developer

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

2192: .seealso: SNESSetNGS(), SNESComputeFunction()
2193: @*/
2194: PetscErrorCode  SNESComputeNGS(SNES snes,Vec b,Vec x)
2195: {
2197:   DM             dm;
2198:   DMSNES         sdm;

2206:   if (b) {VecValidValues(b,2,PETSC_TRUE);}
2207:   PetscLogEventBegin(SNES_NGSEval,snes,x,b,0);
2208:   SNESGetDM(snes,&dm);
2209:   DMGetDMSNES(dm,&sdm);
2210:   if (sdm->ops->computegs) {
2211:     if (b) {VecLockPush(b);}
2212:     PetscStackPush("SNES user NGS");
2213:     (*sdm->ops->computegs)(snes,x,b,sdm->gsctx);
2214:     PetscStackPop;
2215:     if (b) {VecLockPop(b);}
2216:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, "Must call SNESSetNGS() before SNESComputeNGS(), likely called from SNESSolve().");
2217:   PetscLogEventEnd(SNES_NGSEval,snes,x,b,0);
2218:   return(0);
2219: }

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

2226:    Collective on SNES and Mat

2228:    Input Parameters:
2229: +  snes - the SNES context
2230: -  x - input vector

2232:    Output Parameters:
2233: +  A - Jacobian matrix
2234: -  B - optional preconditioning matrix

2236:   Options Database Keys:
2237: +    -snes_lag_preconditioner <lag>
2238: .    -snes_lag_jacobian <lag>
2239: .    -snes_compare_explicit - Compare the computed Jacobian to the finite difference Jacobian and output the differences
2240: .    -snes_compare_explicit_draw  - Compare the computed Jacobian to the finite difference Jacobian and draw the result
2241: .    -snes_compare_explicit_contour  - Compare the computed Jacobian to the finite difference Jacobian and draw a contour plot with the result
2242: .    -snes_compare_operator  - Make the comparison options above use the operator instead of the preconditioning matrix
2243: .    -snes_compare_coloring - Compute the finite difference Jacobian using coloring and display norms of difference
2244: .    -snes_compare_coloring_display - Compute the finite differece Jacobian using coloring and display verbose differences
2245: .    -snes_compare_coloring_threshold - Display only those matrix entries that differ by more than a given threshold
2246: .    -snes_compare_coloring_threshold_atol - Absolute tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2247: .    -snes_compare_coloring_threshold_rtol - Relative tolerance for difference in matrix entries to be displayed by -snes_compare_coloring_threshold
2248: .    -snes_compare_coloring_draw - Compute the finite differece Jacobian using coloring and draw differences
2249: -    -snes_compare_coloring_draw_contour - Compute the finite differece Jacobian using coloring and show contours of matrices and differences


2252:    Notes:
2253:    Most users should not need to explicitly call this routine, as it
2254:    is used internally within the nonlinear solvers.

2256:    Level: developer

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

2260: .seealso:  SNESSetJacobian(), KSPSetOperators(), MatStructure, SNESSetLagPreconditioner(), SNESSetLagJacobian()
2261: @*/
2262: PetscErrorCode  SNESComputeJacobian(SNES snes,Vec X,Mat A,Mat B)
2263: {
2265:   PetscBool      flag;
2266:   DM             dm;
2267:   DMSNES         sdm;
2268:   KSP            ksp;

2274:   VecValidValues(X,2,PETSC_TRUE);
2275:   SNESGetDM(snes,&dm);
2276:   DMGetDMSNES(dm,&sdm);

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

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

2282:   if (snes->lagjacobian == -2) {
2283:     snes->lagjacobian = -1;

2285:     PetscInfo(snes,"Recomputing Jacobian/preconditioner because lag is -2 (means compute Jacobian, but then never again) \n");
2286:   } else if (snes->lagjacobian == -1) {
2287:     PetscInfo(snes,"Reusing Jacobian/preconditioner because lag is -1\n");
2288:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2289:     if (flag) {
2290:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2291:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2292:     }
2293:     return(0);
2294:   } else if (snes->lagjacobian > 1 && (snes->iter + snes->jac_iter) % snes->lagjacobian) {
2295:     PetscInfo2(snes,"Reusing Jacobian/preconditioner because lag is %D and SNES iteration is %D\n",snes->lagjacobian,snes->iter);
2296:     PetscObjectTypeCompare((PetscObject)A,MATMFFD,&flag);
2297:     if (flag) {
2298:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2299:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2300:     }
2301:     return(0);
2302:   }
2303:   if (snes->pc && snes->pcside == PC_LEFT) {
2304:       MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
2305:       MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
2306:       return(0);
2307:   }

2309:   PetscLogEventBegin(SNES_JacobianEval,snes,X,A,B);
2310:   VecLockPush(X);
2311:   PetscStackPush("SNES user Jacobian function");
2312:   (*sdm->ops->computejacobian)(snes,X,A,B,sdm->jacobianctx);
2313:   PetscStackPop;
2314:   VecLockPop(X);
2315:   PetscLogEventEnd(SNES_JacobianEval,snes,X,A,B);

2317:   /* the next line ensures that snes->ksp exists */
2318:   SNESGetKSP(snes,&ksp);
2319:   if (snes->lagpreconditioner == -2) {
2320:     PetscInfo(snes,"Rebuilding preconditioner exactly once since lag is -2\n");
2321:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2322:     snes->lagpreconditioner = -1;
2323:   } else if (snes->lagpreconditioner == -1) {
2324:     PetscInfo(snes,"Reusing preconditioner because lag is -1\n");
2325:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2326:   } else if (snes->lagpreconditioner > 1 && (snes->iter + snes->pre_iter) % snes->lagpreconditioner) {
2327:     PetscInfo2(snes,"Reusing preconditioner because lag is %D and SNES iteration is %D\n",snes->lagpreconditioner,snes->iter);
2328:     KSPSetReusePreconditioner(snes->ksp,PETSC_TRUE);
2329:   } else {
2330:     PetscInfo(snes,"Rebuilding preconditioner\n");
2331:     KSPSetReusePreconditioner(snes->ksp,PETSC_FALSE);
2332:   }

2334:   /* make sure user returned a correct Jacobian and preconditioner */
2337:   {
2338:     PetscBool flag = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_operator = PETSC_FALSE;
2339:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit",NULL,NULL,&flag);
2340:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw",NULL,NULL,&flag_draw);
2341:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_explicit_draw_contour",NULL,NULL,&flag_contour);
2342:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_operator",NULL,NULL,&flag_operator);
2343:     if (flag || flag_draw || flag_contour) {
2344:       Mat          Bexp_mine = NULL,Bexp,FDexp;
2345:       PetscViewer  vdraw,vstdout;
2346:       PetscBool    flg;
2347:       if (flag_operator) {
2348:         MatComputeExplicitOperator(A,&Bexp_mine);
2349:         Bexp = Bexp_mine;
2350:       } else {
2351:         /* See if the preconditioning matrix can be viewed and added directly */
2352:         PetscObjectTypeCompareAny((PetscObject)B,&flg,MATSEQAIJ,MATMPIAIJ,MATSEQDENSE,MATMPIDENSE,MATSEQBAIJ,MATMPIBAIJ,MATSEQSBAIJ,MATMPIBAIJ,"");
2353:         if (flg) Bexp = B;
2354:         else {
2355:           /* If the "preconditioning" matrix is itself MATSHELL or some other type without direct support */
2356:           MatComputeExplicitOperator(B,&Bexp_mine);
2357:           Bexp = Bexp_mine;
2358:         }
2359:       }
2360:       MatConvert(Bexp,MATSAME,MAT_INITIAL_MATRIX,&FDexp);
2361:       SNESComputeJacobianDefault(snes,X,FDexp,FDexp,NULL);
2362:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2363:       if (flag_draw || flag_contour) {
2364:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Explicit Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2365:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2366:       } else vdraw = NULL;
2367:       PetscViewerASCIIPrintf(vstdout,"Explicit %s\n",flag_operator ? "Jacobian" : "preconditioning Jacobian");
2368:       if (flag) {MatView(Bexp,vstdout);}
2369:       if (vdraw) {MatView(Bexp,vdraw);}
2370:       PetscViewerASCIIPrintf(vstdout,"Finite difference Jacobian\n");
2371:       if (flag) {MatView(FDexp,vstdout);}
2372:       if (vdraw) {MatView(FDexp,vdraw);}
2373:       MatAYPX(FDexp,-1.0,Bexp,SAME_NONZERO_PATTERN);
2374:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian\n");
2375:       if (flag) {MatView(FDexp,vstdout);}
2376:       if (vdraw) {              /* Always use contour for the difference */
2377:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2378:         MatView(FDexp,vdraw);
2379:         PetscViewerPopFormat(vdraw);
2380:       }
2381:       if (flag_contour) {PetscViewerPopFormat(vdraw);}
2382:       PetscViewerDestroy(&vdraw);
2383:       MatDestroy(&Bexp_mine);
2384:       MatDestroy(&FDexp);
2385:     }
2386:   }
2387:   {
2388:     PetscBool flag = PETSC_FALSE,flag_display = PETSC_FALSE,flag_draw = PETSC_FALSE,flag_contour = PETSC_FALSE,flag_threshold = PETSC_FALSE;
2389:     PetscReal threshold_atol = PETSC_SQRT_MACHINE_EPSILON,threshold_rtol = 10*PETSC_SQRT_MACHINE_EPSILON;
2390:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring",NULL,NULL,&flag);
2391:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_display",NULL,NULL,&flag_display);
2392:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw",NULL,NULL,&flag_draw);
2393:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_draw_contour",NULL,NULL,&flag_contour);
2394:     PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold",NULL,NULL,&flag_threshold);
2395:     if (flag_threshold) {
2396:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_rtol",&threshold_rtol,NULL);
2397:       PetscOptionsGetReal(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-snes_compare_coloring_threshold_atol",&threshold_atol,NULL);
2398:     }
2399:     if (flag || flag_display || flag_draw || flag_contour || flag_threshold) {
2400:       Mat            Bfd;
2401:       PetscViewer    vdraw,vstdout;
2402:       MatColoring    coloring;
2403:       ISColoring     iscoloring;
2404:       MatFDColoring  matfdcoloring;
2405:       PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2406:       void           *funcctx;
2407:       PetscReal      norm1,norm2,normmax;

2409:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&Bfd);
2410:       MatColoringCreate(Bfd,&coloring);
2411:       MatColoringSetType(coloring,MATCOLORINGSL);
2412:       MatColoringSetFromOptions(coloring);
2413:       MatColoringApply(coloring,&iscoloring);
2414:       MatColoringDestroy(&coloring);
2415:       MatFDColoringCreate(Bfd,iscoloring,&matfdcoloring);
2416:       MatFDColoringSetFromOptions(matfdcoloring);
2417:       MatFDColoringSetUp(Bfd,iscoloring,matfdcoloring);
2418:       ISColoringDestroy(&iscoloring);

2420:       /* This method of getting the function is currently unreliable since it doesn't work for DM local functions. */
2421:       SNESGetFunction(snes,NULL,&func,&funcctx);
2422:       MatFDColoringSetFunction(matfdcoloring,(PetscErrorCode (*)(void))func,funcctx);
2423:       PetscObjectSetOptionsPrefix((PetscObject)matfdcoloring,((PetscObject)snes)->prefix);
2424:       PetscObjectAppendOptionsPrefix((PetscObject)matfdcoloring,"coloring_");
2425:       MatFDColoringSetFromOptions(matfdcoloring);
2426:       MatFDColoringApply(Bfd,matfdcoloring,X,snes);
2427:       MatFDColoringDestroy(&matfdcoloring);

2429:       PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)snes),&vstdout);
2430:       if (flag_draw || flag_contour) {
2431:         PetscViewerDrawOpen(PetscObjectComm((PetscObject)snes),0,"Colored Jacobians",PETSC_DECIDE,PETSC_DECIDE,300,300,&vdraw);
2432:         if (flag_contour) {PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);}
2433:       } else vdraw = NULL;
2434:       PetscViewerASCIIPrintf(vstdout,"Explicit preconditioning Jacobian\n");
2435:       if (flag_display) {MatView(B,vstdout);}
2436:       if (vdraw) {MatView(B,vdraw);}
2437:       PetscViewerASCIIPrintf(vstdout,"Colored Finite difference Jacobian\n");
2438:       if (flag_display) {MatView(Bfd,vstdout);}
2439:       if (vdraw) {MatView(Bfd,vdraw);}
2440:       MatAYPX(Bfd,-1.0,B,SAME_NONZERO_PATTERN);
2441:       MatNorm(Bfd,NORM_1,&norm1);
2442:       MatNorm(Bfd,NORM_FROBENIUS,&norm2);
2443:       MatNorm(Bfd,NORM_MAX,&normmax);
2444:       PetscViewerASCIIPrintf(vstdout,"User-provided matrix minus finite difference Jacobian, norm1=%g normFrob=%g normmax=%g\n",(double)norm1,(double)norm2,(double)normmax);
2445:       if (flag_display) {MatView(Bfd,vstdout);}
2446:       if (vdraw) {              /* Always use contour for the difference */
2447:         PetscViewerPushFormat(vdraw,PETSC_VIEWER_DRAW_CONTOUR);
2448:         MatView(Bfd,vdraw);
2449:         PetscViewerPopFormat(vdraw);
2450:       }
2451:       if (flag_contour) {PetscViewerPopFormat(vdraw);}

2453:       if (flag_threshold) {
2454:         PetscInt bs,rstart,rend,i;
2455:         MatGetBlockSize(B,&bs);
2456:         MatGetOwnershipRange(B,&rstart,&rend);
2457:         for (i=rstart; i<rend; i++) {
2458:           const PetscScalar *ba,*ca;
2459:           const PetscInt    *bj,*cj;
2460:           PetscInt          bn,cn,j,maxentrycol = -1,maxdiffcol = -1,maxrdiffcol = -1;
2461:           PetscReal         maxentry = 0,maxdiff = 0,maxrdiff = 0;
2462:           MatGetRow(B,i,&bn,&bj,&ba);
2463:           MatGetRow(Bfd,i,&cn,&cj,&ca);
2464:           if (bn != cn) SETERRQ(((PetscObject)A)->comm,PETSC_ERR_PLIB,"Unexpected different nonzero pattern in -snes_compare_coloring_threshold");
2465:           for (j=0; j<bn; j++) {
2466:             PetscReal rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2467:             if (PetscAbsScalar(ba[j]) > PetscAbs(maxentry)) {
2468:               maxentrycol = bj[j];
2469:               maxentry    = PetscRealPart(ba[j]);
2470:             }
2471:             if (PetscAbsScalar(ca[j]) > PetscAbs(maxdiff)) {
2472:               maxdiffcol = bj[j];
2473:               maxdiff    = PetscRealPart(ca[j]);
2474:             }
2475:             if (rdiff > maxrdiff) {
2476:               maxrdiffcol = bj[j];
2477:               maxrdiff    = rdiff;
2478:             }
2479:           }
2480:           if (maxrdiff > 1) {
2481:             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);
2482:             for (j=0; j<bn; j++) {
2483:               PetscReal rdiff;
2484:               rdiff = PetscAbsScalar(ca[j]) / (threshold_atol + threshold_rtol*PetscAbsScalar(ba[j]));
2485:               if (rdiff > 1) {
2486:                 PetscViewerASCIIPrintf(vstdout," (%D,%g:%g)",bj[j],(double)PetscRealPart(ba[j]),(double)PetscRealPart(ca[j]));
2487:               }
2488:             }
2489:             PetscViewerASCIIPrintf(vstdout,"\n",i,maxentry,maxdiff,maxrdiff);
2490:           }
2491:           MatRestoreRow(B,i,&bn,&bj,&ba);
2492:           MatRestoreRow(Bfd,i,&cn,&cj,&ca);
2493:         }
2494:       }
2495:       PetscViewerDestroy(&vdraw);
2496:       MatDestroy(&Bfd);
2497:     }
2498:   }
2499:   return(0);
2500: }

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

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

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

2514:    Level: intermediate

2516: .seealso:   SNESSetFunction(), SNESGetFunction(), SNESSetJacobian(), SNESGetJacobian()
2517: M*/

2521: /*@C
2522:    SNESSetJacobian - Sets the function to compute Jacobian as well as the
2523:    location to store the matrix.

2525:    Logically Collective on SNES and Mat

2527:    Input Parameters:
2528: +  snes - the SNES context
2529: .  Amat - the matrix that defines the (approximate) Jacobian
2530: .  Pmat - the matrix to be used in constructing the preconditioner, usually the same as Amat.
2531: .  J - Jacobian evaluation routine (if NULL then SNES retains any previously set value), see SNESJacobianFunction for details
2532: -  ctx - [optional] user-defined context for private data for the
2533:          Jacobian evaluation routine (may be NULL) (if NULL then SNES retains any previously set value)

2535:    Notes:
2536:    If the Amat matrix and Pmat matrix are different you must call MatAssemblyBegin/End() on
2537:    each matrix.

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

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

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

2548:    Level: beginner

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

2552: .seealso: KSPSetOperators(), SNESSetFunction(), MatMFFDComputeJacobian(), SNESComputeJacobianDefaultColor(), MatStructure, J, 
2553:           SNESSetPicard(), SNESJacobianFunction
2554: @*/
2555: PetscErrorCode  SNESSetJacobian(SNES snes,Mat Amat,Mat Pmat,PetscErrorCode (*J)(SNES,Vec,Mat,Mat,void*),void *ctx)
2556: {
2558:   DM             dm;

2566:   SNESGetDM(snes,&dm);
2567:   DMSNESSetJacobian(dm,J,ctx);
2568:   if (Amat) {
2569:     PetscObjectReference((PetscObject)Amat);
2570:     MatDestroy(&snes->jacobian);

2572:     snes->jacobian = Amat;
2573:   }
2574:   if (Pmat) {
2575:     PetscObjectReference((PetscObject)Pmat);
2576:     MatDestroy(&snes->jacobian_pre);

2578:     snes->jacobian_pre = Pmat;
2579:   }
2580:   return(0);
2581: }

2585: /*@C
2586:    SNESGetJacobian - Returns the Jacobian matrix and optionally the user
2587:    provided context for evaluating the Jacobian.

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

2591:    Input Parameter:
2592: .  snes - the nonlinear solver context

2594:    Output Parameters:
2595: +  Amat - location to stash (approximate) Jacobian matrix (or NULL)
2596: .  Pmat - location to stash matrix used to compute the preconditioner (or NULL)
2597: .  J - location to put Jacobian function (or NULL), see SNESJacobianFunction for details on its calling sequence
2598: -  ctx - location to stash Jacobian ctx (or NULL)

2600:    Level: advanced

2602: .seealso: SNESSetJacobian(), SNESComputeJacobian(), SNESJacobianFunction, SNESGetFunction()
2603: @*/
2604: PetscErrorCode SNESGetJacobian(SNES snes,Mat *Amat,Mat *Pmat,PetscErrorCode (**J)(SNES,Vec,Mat,Mat,void*),void **ctx)
2605: {
2607:   DM             dm;
2608:   DMSNES         sdm;

2612:   if (Amat) *Amat = snes->jacobian;
2613:   if (Pmat) *Pmat = snes->jacobian_pre;
2614:   SNESGetDM(snes,&dm);
2615:   DMGetDMSNES(dm,&sdm);
2616:   if (J) *J = sdm->ops->computejacobian;
2617:   if (ctx) *ctx = sdm->jacobianctx;
2618:   return(0);
2619: }

2623: /*@
2624:    SNESSetUp - Sets up the internal data structures for the later use
2625:    of a nonlinear solver.

2627:    Collective on SNES

2629:    Input Parameters:
2630: .  snes - the SNES context

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

2639:    Level: advanced

2641: .keywords: SNES, nonlinear, setup

2643: .seealso: SNESCreate(), SNESSolve(), SNESDestroy()
2644: @*/
2645: PetscErrorCode  SNESSetUp(SNES snes)
2646: {
2648:   DM             dm;
2649:   DMSNES         sdm;
2650:   SNESLineSearch linesearch, pclinesearch;
2651:   void           *lsprectx,*lspostctx;
2652:   PetscErrorCode (*precheck)(SNESLineSearch,Vec,Vec,PetscBool*,void*);
2653:   PetscErrorCode (*postcheck)(SNESLineSearch,Vec,Vec,Vec,PetscBool*,PetscBool*,void*);
2654:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2655:   Vec            f,fpc;
2656:   void           *funcctx;
2657:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2658:   void           *jacctx,*appctx;
2659:   Mat            j,jpre;

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

2665:   if (!((PetscObject)snes)->type_name) {
2666:     SNESSetType(snes,SNESNEWTONLS);
2667:   }

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

2671:   SNESGetDM(snes,&dm);
2672:   DMGetDMSNES(dm,&sdm);
2673:   if (!sdm->ops->computefunction) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE,"Function never provided to SNES object");
2674:   if (!sdm->ops->computejacobian) {
2675:     DMSNESSetJacobian(dm,SNESComputeJacobianDefaultColor,NULL);
2676:   }
2677:   if (!snes->vec_func) {
2678:     DMCreateGlobalVector(dm,&snes->vec_func);
2679:   }

2681:   if (!snes->ksp) {
2682:     SNESGetKSP(snes, &snes->ksp);
2683:   }

2685:   if (!snes->linesearch) {
2686:     SNESGetLineSearch(snes, &snes->linesearch);
2687:   }
2688:   SNESLineSearchSetFunction(snes->linesearch,SNESComputeFunction);

2690:   if (snes->pc && (snes->pcside == PC_LEFT)) {
2691:     snes->mf          = PETSC_TRUE;
2692:     snes->mf_operator = PETSC_FALSE;
2693:   }

2695:   if (snes->pc) {
2696:     /* copy the DM over */
2697:     SNESGetDM(snes,&dm);
2698:     SNESSetDM(snes->pc,dm);

2700:     SNESGetFunction(snes,&f,&func,&funcctx);
2701:     VecDuplicate(f,&fpc);
2702:     SNESSetFunction(snes->pc,fpc,func,funcctx);
2703:     SNESGetJacobian(snes,&j,&jpre,&jac,&jacctx);
2704:     SNESSetJacobian(snes->pc,j,jpre,jac,jacctx);
2705:     SNESGetApplicationContext(snes,&appctx);
2706:     SNESSetApplicationContext(snes->pc,appctx);
2707:     VecDestroy(&fpc);

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

2712:     /* default to 1 iteration */
2713:     SNESSetTolerances(snes->pc,0.0,0.0,0.0,1,snes->pc->max_funcs);
2714:     if (snes->pcside==PC_RIGHT) {
2715:       SNESSetNormSchedule(snes->pc,SNES_NORM_FINAL_ONLY);
2716:     } else {
2717:       SNESSetNormSchedule(snes->pc,SNES_NORM_NONE);
2718:     }
2719:     SNESSetFromOptions(snes->pc);

2721:     /* copy the line search context over */
2722:     SNESGetLineSearch(snes,&linesearch);
2723:     SNESGetLineSearch(snes->pc,&pclinesearch);
2724:     SNESLineSearchGetPreCheck(linesearch,&precheck,&lsprectx);
2725:     SNESLineSearchGetPostCheck(linesearch,&postcheck,&lspostctx);
2726:     SNESLineSearchSetPreCheck(pclinesearch,precheck,lsprectx);
2727:     SNESLineSearchSetPostCheck(pclinesearch,postcheck,lspostctx);
2728:     PetscObjectCopyFortranFunctionPointers((PetscObject)linesearch, (PetscObject)pclinesearch);
2729:   }
2730:   if (snes->mf) {
2731:     SNESSetUpMatrixFree_Private(snes, snes->mf_operator, snes->mf_version);
2732:   }
2733:   if (snes->ops->usercompute && !snes->user) {
2734:     (*snes->ops->usercompute)(snes,(void**)&snes->user);
2735:   }

2737:   snes->jac_iter = 0;
2738:   snes->pre_iter = 0;

2740:   if (snes->ops->setup) {
2741:     (*snes->ops->setup)(snes);
2742:   }

2744:   if (snes->pc && (snes->pcside == PC_LEFT)) {
2745:     if (snes->functype == SNES_FUNCTION_PRECONDITIONED) {
2746:       SNESGetLineSearch(snes,&linesearch);
2747:       SNESLineSearchSetFunction(linesearch,SNESComputeFunctionDefaultNPC);
2748:     }
2749:   }

2751:   snes->setupcalled = PETSC_TRUE;
2752:   return(0);
2753: }

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

2760:    Collective on SNES

2762:    Input Parameter:
2763: .  snes - iterative context obtained from SNESCreate()

2765:    Level: intermediate

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

2769: .keywords: SNES, destroy

2771: .seealso: SNESCreate(), SNESSetUp(), SNESSolve()
2772: @*/
2773: PetscErrorCode  SNESReset(SNES snes)
2774: {

2779:   if (snes->ops->userdestroy && snes->user) {
2780:     (*snes->ops->userdestroy)((void**)&snes->user);
2781:     snes->user = NULL;
2782:   }
2783:   if (snes->pc) {
2784:     SNESReset(snes->pc);
2785:   }

2787:   if (snes->ops->reset) {
2788:     (*snes->ops->reset)(snes);
2789:   }
2790:   if (snes->ksp) {
2791:     KSPReset(snes->ksp);
2792:   }

2794:   if (snes->linesearch) {
2795:     SNESLineSearchReset(snes->linesearch);
2796:   }

2798:   VecDestroy(&snes->vec_rhs);
2799:   VecDestroy(&snes->vec_sol);
2800:   VecDestroy(&snes->vec_sol_update);
2801:   VecDestroy(&snes->vec_func);
2802:   MatDestroy(&snes->jacobian);
2803:   MatDestroy(&snes->jacobian_pre);
2804:   VecDestroyVecs(snes->nwork,&snes->work);
2805:   VecDestroyVecs(snes->nvwork,&snes->vwork);

2807:   snes->nwork       = snes->nvwork = 0;
2808:   snes->setupcalled = PETSC_FALSE;
2809:   return(0);
2810: }

2814: /*@
2815:    SNESDestroy - Destroys the nonlinear solver context that was created
2816:    with SNESCreate().

2818:    Collective on SNES

2820:    Input Parameter:
2821: .  snes - the SNES context

2823:    Level: beginner

2825: .keywords: SNES, nonlinear, destroy

2827: .seealso: SNESCreate(), SNESSolve()
2828: @*/
2829: PetscErrorCode  SNESDestroy(SNES *snes)
2830: {

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

2838:   SNESReset((*snes));
2839:   SNESDestroy(&(*snes)->pc);

2841:   /* if memory was published with SAWs then destroy it */
2842:   PetscObjectSAWsViewOff((PetscObject)*snes);
2843:   if ((*snes)->ops->destroy) {(*((*snes))->ops->destroy)((*snes));}

2845:   DMDestroy(&(*snes)->dm);
2846:   KSPDestroy(&(*snes)->ksp);
2847:   SNESLineSearchDestroy(&(*snes)->linesearch);

2849:   PetscFree((*snes)->kspconvctx);
2850:   if ((*snes)->ops->convergeddestroy) {
2851:     (*(*snes)->ops->convergeddestroy)((*snes)->cnvP);
2852:   }
2853:   if ((*snes)->conv_malloc) {
2854:     PetscFree((*snes)->conv_hist);
2855:     PetscFree((*snes)->conv_hist_its);
2856:   }
2857:   SNESMonitorCancel((*snes));
2858:   PetscHeaderDestroy(snes);
2859:   return(0);
2860: }

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

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

2869:    Logically Collective on SNES

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

2876:    Options Database Keys:
2877: .    -snes_lag_preconditioner <lag>

2879:    Notes:
2880:    The default is 1
2881:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1
2882:    If  -1 is used before the very first nonlinear solve the preconditioner is still built because there is no previous preconditioner to use

2884:    Level: intermediate

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

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

2890: @*/
2891: PetscErrorCode  SNESSetLagPreconditioner(SNES snes,PetscInt lag)
2892: {
2895:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
2896:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
2898:   snes->lagpreconditioner = lag;
2899:   return(0);
2900: }

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

2907:    Logically Collective on SNES

2909:    Input Parameters:
2910: +  snes - the SNES context
2911: -  steps - the number of refinements to do, defaults to 0

2913:    Options Database Keys:
2914: .    -snes_grid_sequence <steps>

2916:    Level: intermediate

2918:    Notes:
2919:    Use SNESGetSolution() to extract the fine grid solution after grid sequencing.

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

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

2925: @*/
2926: PetscErrorCode  SNESSetGridSequence(SNES snes,PetscInt steps)
2927: {
2931:   snes->gridsequence = steps;
2932:   return(0);
2933: }

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

2940:    Logically Collective on SNES

2942:    Input Parameter:
2943: .  snes - the SNES context

2945:    Output Parameter:
2946: .  steps - the number of refinements to do, defaults to 0

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

2951:    Level: intermediate

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

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

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

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

2971: /*@
2972:    SNESGetLagPreconditioner - Indicates how often the preconditioner is rebuilt

2974:    Not Collective

2976:    Input Parameter:
2977: .  snes - the SNES context

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

2983:    Options Database Keys:
2984: .    -snes_lag_preconditioner <lag>

2986:    Notes:
2987:    The default is 1
2988:    The preconditioner is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

2990:    Level: intermediate

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

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

2996: @*/
2997: PetscErrorCode  SNESGetLagPreconditioner(SNES snes,PetscInt *lag)
2998: {
3001:   *lag = snes->lagpreconditioner;
3002:   return(0);
3003: }

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

3011:    Logically Collective on SNES

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

3018:    Options Database Keys:
3019: .    -snes_lag_jacobian <lag>

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

3027:    Level: intermediate

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

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

3033: @*/
3034: PetscErrorCode  SNESSetLagJacobian(SNES snes,PetscInt lag)
3035: {
3038:   if (lag < -2) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag must be -2, -1, 1 or greater");
3039:   if (!lag) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Lag cannot be 0");
3041:   snes->lagjacobian = lag;
3042:   return(0);
3043: }

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

3050:    Not Collective

3052:    Input Parameter:
3053: .  snes - the SNES context

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

3059:    Options Database Keys:
3060: .    -snes_lag_jacobian <lag>

3062:    Notes:
3063:    The default is 1
3064:    The jacobian is ALWAYS built in the first iteration of a nonlinear solve unless lag is -1

3066:    Level: intermediate

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

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

3072: @*/
3073: PetscErrorCode  SNESGetLagJacobian(SNES snes,PetscInt *lag)
3074: {
3077:   *lag = snes->lagjacobian;
3078:   return(0);
3079: }

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

3086:    Logically collective on SNES

3088:    Input Parameter:
3089: +  snes - the SNES context
3090: -   flg - jacobian lagging persists if true

3092:    Options Database Keys:
3093: .    -snes_lag_jacobian_persists <flg>

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

3099:    Level: developer

3101: .keywords: SNES, nonlinear, lag

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

3105: @*/
3106: PetscErrorCode  SNESSetLagJacobianPersists(SNES snes,PetscBool flg)
3107: {
3111:   snes->lagjac_persist = flg;
3112:   return(0);
3113: }

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

3120:    Logically Collective on SNES

3122:    Input Parameter:
3123: +  snes - the SNES context
3124: -   flg - preconditioner lagging persists if true

3126:    Options Database Keys:
3127: .    -snes_lag_jacobian_persists <flg>

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

3133:    Level: developer

3135: .keywords: SNES, nonlinear, lag

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

3139: @*/
3140: PetscErrorCode  SNESSetLagPreconditionerPersists(SNES snes,PetscBool flg)
3141: {
3145:   snes->lagpre_persist = flg;
3146:   return(0);
3147: }

3151: /*@
3152:    SNESSetTolerances - Sets various parameters used in convergence tests.

3154:    Logically Collective on SNES

3156:    Input Parameters:
3157: +  snes - the SNES context
3158: .  abstol - absolute convergence tolerance
3159: .  rtol - relative convergence tolerance
3160: .  stol -  convergence tolerance in terms of the norm of the change in the solution between steps,  || delta x || < stol*|| x ||
3161: .  maxit - maximum number of iterations
3162: -  maxf - maximum number of function evaluations

3164:    Options Database Keys:
3165: +    -snes_atol <abstol> - Sets abstol
3166: .    -snes_rtol <rtol> - Sets rtol
3167: .    -snes_stol <stol> - Sets stol
3168: .    -snes_max_it <maxit> - Sets maxit
3169: -    -snes_max_funcs <maxf> - Sets maxf

3171:    Notes:
3172:    The default maximum number of iterations is 50.
3173:    The default maximum number of function evaluations is 1000.

3175:    Level: intermediate

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

3179: .seealso: SNESSetTrustRegionTolerance()
3180: @*/
3181: PetscErrorCode  SNESSetTolerances(SNES snes,PetscReal abstol,PetscReal rtol,PetscReal stol,PetscInt maxit,PetscInt maxf)
3182: {

3191:   if (abstol != PETSC_DEFAULT) {
3192:     if (abstol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Absolute tolerance %g must be non-negative",(double)abstol);
3193:     snes->abstol = abstol;
3194:   }
3195:   if (rtol != PETSC_DEFAULT) {
3196:     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);
3197:     snes->rtol = rtol;
3198:   }
3199:   if (stol != PETSC_DEFAULT) {
3200:     if (stol < 0.0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Step tolerance %g must be non-negative",(double)stol);
3201:     snes->stol = stol;
3202:   }
3203:   if (maxit != PETSC_DEFAULT) {
3204:     if (maxit < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of iterations %D must be non-negative",maxit);
3205:     snes->max_its = maxit;
3206:   }
3207:   if (maxf != PETSC_DEFAULT) {
3208:     if (maxf < 0) SETERRQ1(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of function evaluations %D must be non-negative",maxf);
3209:     snes->max_funcs = maxf;
3210:   }
3211:   snes->tolerancesset = PETSC_TRUE;
3212:   return(0);
3213: }

3217: /*@
3218:    SNESGetTolerances - Gets various parameters used in convergence tests.

3220:    Not Collective

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

3231:    Notes:
3232:    The user can specify NULL for any parameter that is not needed.

3234:    Level: intermediate

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

3238: .seealso: SNESSetTolerances()
3239: @*/
3240: PetscErrorCode  SNESGetTolerances(SNES snes,PetscReal *atol,PetscReal *rtol,PetscReal *stol,PetscInt *maxit,PetscInt *maxf)
3241: {
3244:   if (atol)  *atol  = snes->abstol;
3245:   if (rtol)  *rtol  = snes->rtol;
3246:   if (stol)  *stol  = snes->stol;
3247:   if (maxit) *maxit = snes->max_its;
3248:   if (maxf)  *maxf  = snes->max_funcs;
3249:   return(0);
3250: }

3254: /*@
3255:    SNESSetTrustRegionTolerance - Sets the trust region parameter tolerance.

3257:    Logically Collective on SNES

3259:    Input Parameters:
3260: +  snes - the SNES context
3261: -  tol - tolerance

3263:    Options Database Key:
3264: .  -snes_trtol <tol> - Sets tol

3266:    Level: intermediate

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

3270: .seealso: SNESSetTolerances()
3271: @*/
3272: PetscErrorCode  SNESSetTrustRegionTolerance(SNES snes,PetscReal tol)
3273: {
3277:   snes->deltatol = tol;
3278:   return(0);
3279: }

3281: /*
3282:    Duplicate the lg monitors for SNES from KSP; for some reason with
3283:    dynamic libraries things don't work under Sun4 if we just use
3284:    macros instead of functions
3285: */
3288: PetscErrorCode  SNESMonitorLGResidualNorm(SNES snes,PetscInt it,PetscReal norm,void *ctx)
3289: {

3294:   KSPMonitorLGResidualNorm((KSP)snes,it,norm,ctx);
3295:   return(0);
3296: }

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

3305:   KSPMonitorLGResidualNormCreate(comm,host,label,x,y,m,n,lgctx);
3306:   return(0);
3307: }

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

3313: PetscErrorCode  SNESMonitorLGRange(SNES snes,PetscInt n,PetscReal rnorm,void *monctx)
3314: {
3315:   PetscDrawLG      lg;
3316:   PetscErrorCode   ierr;
3317:   PetscReal        x,y,per;
3318:   PetscViewer      v = (PetscViewer)monctx;
3319:   static PetscReal prev; /* should be in the context */
3320:   PetscDraw        draw;

3324:   PetscViewerDrawGetDrawLG(v,0,&lg);
3325:   if (!n) {PetscDrawLGReset(lg);}
3326:   PetscDrawLGGetDraw(lg,&draw);
3327:   PetscDrawSetTitle(draw,"Residual norm");
3328:   x    = (PetscReal)n;
3329:   if (rnorm > 0.0) y = PetscLog10Real(rnorm);
3330:   else y = -15.0;
3331:   PetscDrawLGAddPoint(lg,&x,&y);
3332:   if (n < 20 || !(n % 5) || snes->reason) {
3333:     PetscDrawLGDraw(lg);
3334:     PetscDrawLGSave(lg);
3335:   }

3337:   PetscViewerDrawGetDrawLG(v,1,&lg);
3338:   if (!n) {PetscDrawLGReset(lg);}
3339:   PetscDrawLGGetDraw(lg,&draw);
3340:   PetscDrawSetTitle(draw,"% elemts > .2*max elemt");
3341:    SNESMonitorRange_Private(snes,n,&per);
3342:   x    = (PetscReal)n;
3343:   y    = 100.0*per;
3344:   PetscDrawLGAddPoint(lg,&x,&y);
3345:   if (n < 20 || !(n % 5) || snes->reason) {
3346:     PetscDrawLGDraw(lg);
3347:     PetscDrawLGSave(lg);
3348:   }

3350:   PetscViewerDrawGetDrawLG(v,2,&lg);
3351:   if (!n) {prev = rnorm;PetscDrawLGReset(lg);}
3352:   PetscDrawLGGetDraw(lg,&draw);
3353:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm");
3354:   x    = (PetscReal)n;
3355:   y    = (prev - rnorm)/prev;
3356:   PetscDrawLGAddPoint(lg,&x,&y);
3357:   if (n < 20 || !(n % 5) || snes->reason) {
3358:     PetscDrawLGDraw(lg);
3359:     PetscDrawLGSave(lg);
3360:   }

3362:   PetscViewerDrawGetDrawLG(v,3,&lg);
3363:   if (!n) {PetscDrawLGReset(lg);}
3364:   PetscDrawLGGetDraw(lg,&draw);
3365:   PetscDrawSetTitle(draw,"(norm -oldnorm)/oldnorm*(% > .2 max)");
3366:   x    = (PetscReal)n;
3367:   y    = (prev - rnorm)/(prev*per);
3368:   if (n > 2) { /*skip initial crazy value */
3369:     PetscDrawLGAddPoint(lg,&x,&y);
3370:   }
3371:   if (n < 20 || !(n % 5) || snes->reason) {
3372:     PetscDrawLGDraw(lg);
3373:     PetscDrawLGSave(lg);
3374:   }
3375:   prev = rnorm;
3376:   return(0);
3377: }

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

3384:    Collective on SNES

3386:    Input Parameters:
3387: +  snes - nonlinear solver context obtained from SNESCreate()
3388: .  iter - iteration number
3389: -  rnorm - relative norm of the residual

3391:    Notes:
3392:    This routine is called by the SNES implementations.
3393:    It does not typically need to be called by the user.

3395:    Level: developer

3397: .seealso: SNESMonitorSet()
3398: @*/
3399: PetscErrorCode  SNESMonitor(SNES snes,PetscInt iter,PetscReal rnorm)
3400: {
3402:   PetscInt       i,n = snes->numbermonitors;

3405:   VecLockPush(snes->vec_sol);
3406:   for (i=0; i<n; i++) {
3407:     (*snes->monitor[i])(snes,iter,rnorm,snes->monitorcontext[i]);
3408:   }
3409:   VecLockPop(snes->vec_sol);
3410:   return(0);
3411: }

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

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

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

3422: +    snes - the SNES context
3423: .    its - iteration number
3424: .    norm - 2-norm function value (may be estimated)
3425: -    mctx - [optional] monitoring context

3427:    Level: advanced

3429: .seealso:   SNESMonitorSet(), SNESMonitorGet()
3430: M*/

3434: /*@C
3435:    SNESMonitorSet - Sets an ADDITIONAL function that is to be used at every
3436:    iteration of the nonlinear solver to display the iteration's
3437:    progress.

3439:    Logically Collective on SNES

3441:    Input Parameters:
3442: +  snes - the SNES context
3443: .  f - the monitor function, see SNESMonitorFunction for the calling sequence
3444: .  mctx - [optional] user-defined context for private data for the
3445:           monitor routine (use NULL if no context is desired)
3446: -  monitordestroy - [optional] routine that frees monitor context
3447:           (may be NULL)

3449:    Options Database Keys:
3450: +    -snes_monitor        - sets SNESMonitorDefault()
3451: .    -snes_monitor_lg_residualnorm    - sets line graph monitor,
3452:                             uses SNESMonitorLGCreate()
3453: -    -snes_monitor_cancel - cancels all monitors that have
3454:                             been hardwired into a code by
3455:                             calls to SNESMonitorSet(), but
3456:                             does not cancel those set via
3457:                             the options database.

3459:    Notes:
3460:    Several different monitoring routines may be set by calling
3461:    SNESMonitorSet() multiple times; all will be called in the
3462:    order in which they were set.

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

3466:    Level: intermediate

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

3470: .seealso: SNESMonitorDefault(), SNESMonitorCancel(), SNESMonitorFunction
3471: @*/
3472: PetscErrorCode  SNESMonitorSet(SNES snes,PetscErrorCode (*f)(SNES,PetscInt,PetscReal,void*),void *mctx,PetscErrorCode (*monitordestroy)(void**))
3473: {
3474:   PetscInt       i;
3476:   PetscBool      identical;

3480:   for (i=0; i<snes->numbermonitors;i++) {
3481:     PetscMonitorCompare((PetscErrorCode (*)(void))f,mctx,monitordestroy,(PetscErrorCode (*)(void))snes->monitor[i],snes->monitorcontext[i],snes->monitordestroy[i],&identical);
3482:     if (identical) return(0);
3483:   }
3484:   if (snes->numbermonitors >= MAXSNESMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3485:   snes->monitor[snes->numbermonitors]          = f;
3486:   snes->monitordestroy[snes->numbermonitors]   = monitordestroy;
3487:   snes->monitorcontext[snes->numbermonitors++] = (void*)mctx;
3488:   return(0);
3489: }

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

3496:    Logically Collective on SNES

3498:    Input Parameters:
3499: .  snes - the SNES context

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

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

3509:    Level: intermediate

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

3513: .seealso: SNESMonitorDefault(), SNESMonitorSet()
3514: @*/
3515: PetscErrorCode  SNESMonitorCancel(SNES snes)
3516: {
3518:   PetscInt       i;

3522:   for (i=0; i<snes->numbermonitors; i++) {
3523:     if (snes->monitordestroy[i]) {
3524:       (*snes->monitordestroy[i])(&snes->monitorcontext[i]);
3525:     }
3526:   }
3527:   snes->numbermonitors = 0;
3528:   return(0);
3529: }

3531: /*MC
3532:     SNESConvergenceTestFunction - functional form used for testing of convergence of nonlinear solver

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

3538: +    snes - the SNES context
3539: .    it - current iteration (0 is the first and is before any Newton step)
3540: .    cctx - [optional] convergence context
3541: .    reason - reason for convergence/divergence
3542: .    xnorm - 2-norm of current iterate
3543: .    gnorm - 2-norm of current step
3544: -    f - 2-norm of function

3546:    Level: intermediate

3548: .seealso:   SNESSetConvergenceTest(), SNESGetConvergenceTest()
3549: M*/

3553: /*@C
3554:    SNESSetConvergenceTest - Sets the function that is to be used
3555:    to test for convergence of the nonlinear iterative solution.

3557:    Logically Collective on SNES

3559:    Input Parameters:
3560: +  snes - the SNES context
3561: .  SNESConvergenceTestFunction - routine to test for convergence
3562: .  cctx - [optional] context for private data for the convergence routine  (may be NULL)
3563: -  destroy - [optional] destructor for the context (may be NULL; NULL_FUNCTION in Fortran)

3565:    Level: advanced

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

3569: .seealso: SNESConvergedDefault(), SNESConvergedSkip(), SNESConvergenceTestFunction
3570: @*/
3571: PetscErrorCode  SNESSetConvergenceTest(SNES snes,PetscErrorCode (*SNESConvergenceTestFunction)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*),void *cctx,PetscErrorCode (*destroy)(void*))
3572: {

3577:   if (!SNESConvergenceTestFunction) SNESConvergenceTestFunction = SNESConvergedSkip;
3578:   if (snes->ops->convergeddestroy) {
3579:     (*snes->ops->convergeddestroy)(snes->cnvP);
3580:   }
3581:   snes->ops->converged        = SNESConvergenceTestFunction;
3582:   snes->ops->convergeddestroy = destroy;
3583:   snes->cnvP                  = cctx;
3584:   return(0);
3585: }

3589: /*@
3590:    SNESGetConvergedReason - Gets the reason the SNES iteration was stopped.

3592:    Not Collective

3594:    Input Parameter:
3595: .  snes - the SNES context

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

3601:    Level: intermediate

3603:    Notes: Can only be called after the call the SNESSolve() is complete.

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

3607: .seealso: SNESSetConvergenceTest(), SNESSetConvergedReason(), SNESConvergedReason
3608: @*/
3609: PetscErrorCode SNESGetConvergedReason(SNES snes,SNESConvergedReason *reason)
3610: {
3614:   *reason = snes->reason;
3615:   return(0);
3616: }

3620: /*@
3621:    SNESSetConvergedReason - Sets the reason the SNES iteration was stopped.

3623:    Not Collective

3625:    Input Parameters:
3626: +  snes - the SNES context
3627: -  reason - negative value indicates diverged, positive value converged, see SNESConvergedReason or the
3628:             manual pages for the individual convergence tests for complete lists

3630:    Level: intermediate

3632: .keywords: SNES, nonlinear, set, convergence, test
3633: .seealso: SNESGetConvergedReason(), SNESSetConvergenceTest(), SNESConvergedReason
3634: @*/
3635: PetscErrorCode SNESSetConvergedReason(SNES snes,SNESConvergedReason reason)
3636: {
3639:   snes->reason = reason;
3640:   return(0);
3641: }

3645: /*@
3646:    SNESSetConvergenceHistory - Sets the array used to hold the convergence history.

3648:    Logically Collective on SNES

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

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

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

3666:    Level: intermediate

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

3670: .seealso: SNESGetConvergenceHistory()

3672: @*/
3673: PetscErrorCode  SNESSetConvergenceHistory(SNES snes,PetscReal a[],PetscInt its[],PetscInt na,PetscBool reset)
3674: {

3681:   if (!a) {
3682:     if (na == PETSC_DECIDE || na == PETSC_DEFAULT) na = 1000;
3683:     PetscCalloc1(na,&a);
3684:     PetscCalloc1(na,&its);

3686:     snes->conv_malloc = PETSC_TRUE;
3687:   }
3688:   snes->conv_hist       = a;
3689:   snes->conv_hist_its   = its;
3690:   snes->conv_hist_max   = na;
3691:   snes->conv_hist_len   = 0;
3692:   snes->conv_hist_reset = reset;
3693:   return(0);
3694: }

3696: #if defined(PETSC_HAVE_MATLAB_ENGINE)
3697: #include <engine.h>   /* MATLAB include file */
3698: #include <mex.h>      /* MATLAB include file */

3702: PETSC_EXTERN mxArray *SNESGetConvergenceHistoryMatlab(SNES snes)
3703: {
3704:   mxArray   *mat;
3705:   PetscInt  i;
3706:   PetscReal *ar;

3709:   mat = mxCreateDoubleMatrix(snes->conv_hist_len,1,mxREAL);
3710:   ar  = (PetscReal*) mxGetData(mat);
3711:   for (i=0; i<snes->conv_hist_len; i++) ar[i] = snes->conv_hist[i];
3712:   PetscFunctionReturn(mat);
3713: }
3714: #endif

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

3721:    Not Collective

3723:    Input Parameter:
3724: .  snes - iterative context obtained from SNESCreate()

3726:    Output Parameters:
3727: .  a   - array to hold history
3728: .  its - integer array holds the number of linear iterations (or
3729:          negative if not converged) for each solve.
3730: -  na  - size of a and its

3732:    Notes:
3733:     The calling sequence for this routine in Fortran is
3734: $   call SNESGetConvergenceHistory(SNES snes, integer na, integer ierr)

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

3740:    Level: intermediate

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

3744: .seealso: SNESSetConvergencHistory()

3746: @*/
3747: PetscErrorCode  SNESGetConvergenceHistory(SNES snes,PetscReal *a[],PetscInt *its[],PetscInt *na)
3748: {
3751:   if (a)   *a   = snes->conv_hist;
3752:   if (its) *its = snes->conv_hist_its;
3753:   if (na)  *na  = snes->conv_hist_len;
3754:   return(0);
3755: }

3759: /*@C
3760:   SNESSetUpdate - Sets the general-purpose update function called
3761:   at the beginning of every iteration of the nonlinear solve. Specifically
3762:   it is called just before the Jacobian is "evaluated".

3764:   Logically Collective on SNES

3766:   Input Parameters:
3767: . snes - The nonlinear solver context
3768: . func - The function

3770:   Calling sequence of func:
3771: . func (SNES snes, PetscInt step);

3773: . step - The current step of the iteration

3775:   Level: advanced

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

3780: .keywords: SNES, update

3782: .seealso SNESSetJacobian(), SNESSolve()
3783: @*/
3784: PetscErrorCode  SNESSetUpdate(SNES snes, PetscErrorCode (*func)(SNES, PetscInt))
3785: {
3788:   snes->ops->update = func;
3789:   return(0);
3790: }

3794: /*
3795:    SNESScaleStep_Private - Scales a step so that its length is less than the
3796:    positive parameter delta.

3798:     Input Parameters:
3799: +   snes - the SNES context
3800: .   y - approximate solution of linear system
3801: .   fnorm - 2-norm of current function
3802: -   delta - trust region size

3804:     Output Parameters:
3805: +   gpnorm - predicted function norm at the new point, assuming local
3806:     linearization.  The value is zero if the step lies within the trust
3807:     region, and exceeds zero otherwise.
3808: -   ynorm - 2-norm of the step

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

3814: .keywords: SNES, nonlinear, scale, step
3815: */
3816: PetscErrorCode SNESScaleStep_Private(SNES snes,Vec y,PetscReal *fnorm,PetscReal *delta,PetscReal *gpnorm,PetscReal *ynorm)
3817: {
3818:   PetscReal      nrm;
3819:   PetscScalar    cnorm;


3827:   VecNorm(y,NORM_2,&nrm);
3828:   if (nrm > *delta) {
3829:     nrm     = *delta/nrm;
3830:     *gpnorm = (1.0 - nrm)*(*fnorm);
3831:     cnorm   = nrm;
3832:     VecScale(y,cnorm);
3833:     *ynorm  = *delta;
3834:   } else {
3835:     *gpnorm = 0.0;
3836:     *ynorm  = nrm;
3837:   }
3838:   return(0);
3839: }

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

3846:    Collective on SNES

3848:    Parameter:
3849: +  snes - iterative context obtained from SNESCreate()
3850: -  viewer - the viewer to display the reason


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

3856:    Level: beginner

3858: .keywords: SNES, solve, linear system

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

3862: @*/
3863: PetscErrorCode  SNESReasonView(SNES snes,PetscViewer viewer)
3864: {
3866:   PetscBool      isAscii;

3869:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isAscii);
3870:   if (isAscii) {
3871:     PetscViewerASCIIAddTab(viewer,((PetscObject)snes)->tablevel);
3872:     if (snes->reason > 0) {
3873:       if (((PetscObject) snes)->prefix) {
3874:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve converged due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3875:       } else {
3876:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve converged due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3877:       }
3878:     } else {
3879:       if (((PetscObject) snes)->prefix) {
3880:         PetscViewerASCIIPrintf(viewer,"Nonlinear %s solve did not converge due to %s iterations %D\n",((PetscObject) snes)->prefix,SNESConvergedReasons[snes->reason],snes->iter);
3881:       } else {
3882:         PetscViewerASCIIPrintf(viewer,"Nonlinear solve did not converge due to %s iterations %D\n",SNESConvergedReasons[snes->reason],snes->iter);
3883:       }
3884:     }
3885:     PetscViewerASCIISubtractTab(viewer,((PetscObject)snes)->tablevel);
3886:   }
3887:   return(0);
3888: }

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

3895:   Collective on SNES

3897:   Input Parameters:
3898: . snes   - the SNES object

3900:   Level: intermediate

3902: @*/
3903: PetscErrorCode SNESReasonViewFromOptions(SNES snes)
3904: {
3905:   PetscErrorCode    ierr;
3906:   PetscViewer       viewer;
3907:   PetscBool         flg;
3908:   static PetscBool  incall = PETSC_FALSE;
3909:   PetscViewerFormat format;

3912:   if (incall) return(0);
3913:   incall = PETSC_TRUE;
3914:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)snes),((PetscObject)snes)->prefix,"-snes_converged_reason",&viewer,&format,&flg);
3915:   if (flg) {
3916:     PetscViewerPushFormat(viewer,format);
3917:     SNESReasonView(snes,viewer);
3918:     PetscViewerPopFormat(viewer);
3919:     PetscViewerDestroy(&viewer);
3920:   }
3921:   incall = PETSC_FALSE;
3922:   return(0);
3923: }

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

3931:    Collective on SNES

3933:    Input Parameters:
3934: +  snes - the SNES context
3935: .  b - the constant part of the equation F(x) = b, or NULL to use zero.
3936: -  x - the solution vector.

3938:    Notes:
3939:    The user should initialize the vector,x, with the initial guess
3940:    for the nonlinear solve prior to calling SNESSolve.  In particular,
3941:    to employ an initial guess of zero, the user should explicitly set
3942:    this vector to zero by calling VecSet().

3944:    Level: beginner

3946: .keywords: SNES, nonlinear, solve

3948: .seealso: SNESCreate(), SNESDestroy(), SNESSetFunction(), SNESSetJacobian(), SNESSetGridSequence(), SNESGetSolution()
3949: @*/
3950: PetscErrorCode  SNESSolve(SNES snes,Vec b,Vec x)
3951: {
3952:   PetscErrorCode    ierr;
3953:   PetscBool         flg;
3954:   PetscInt          grid;
3955:   Vec               xcreated = NULL;
3956:   DM                dm;


3965:   if (!x) {
3966:     SNESGetDM(snes,&dm);
3967:     DMCreateGlobalVector(dm,&xcreated);
3968:     x    = xcreated;
3969:   }
3970:   SNESViewFromOptions(snes,NULL,"-snes_view_pre");

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

3975:     /* set solution vector */
3976:     if (!grid) {PetscObjectReference((PetscObject)x);}
3977:     VecDestroy(&snes->vec_sol);
3978:     snes->vec_sol = x;
3979:     SNESGetDM(snes,&dm);

3981:     /* set affine vector if provided */
3982:     if (b) { PetscObjectReference((PetscObject)b); }
3983:     VecDestroy(&snes->vec_rhs);
3984:     snes->vec_rhs = b;

3986:     if (snes->vec_func == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be function vector");
3987:     if (snes->vec_rhs  == snes->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_IDN,"Solution vector cannot be right hand side vector");
3988:     if (!snes->vec_sol_update /* && snes->vec_sol */) {
3989:       VecDuplicate(snes->vec_sol,&snes->vec_sol_update);
3990:       PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->vec_sol_update);
3991:     }
3992:     DMShellSetGlobalVector(dm,snes->vec_sol);
3993:     SNESSetUp(snes);

3995:     if (!grid) {
3996:       if (snes->ops->computeinitialguess) {
3997:         (*snes->ops->computeinitialguess)(snes,snes->vec_sol,snes->initialguessP);
3998:       }
3999:     }

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

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

4010:     if (snes->lagjac_persist) snes->jac_iter += snes->iter;
4011:     if (snes->lagpre_persist) snes->pre_iter += snes->iter;

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

4017:     if (snes->errorifnotconverged && snes->reason < 0) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged");
4018:     if (snes->reason < 0) break;
4019:     if (grid <  snes->gridsequence) {
4020:       DM  fine;
4021:       Vec xnew;
4022:       Mat interp;

4024:       DMRefine(snes->dm,PetscObjectComm((PetscObject)snes),&fine);
4025:       if (!fine) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_ARG_INCOMP,"DMRefine() did not perform any refinement, cannot continue grid sequencing");
4026:       DMCreateInterpolation(snes->dm,fine,&interp,NULL);
4027:       DMCreateGlobalVector(fine,&xnew);
4028:       MatInterpolate(interp,x,xnew);
4029:       DMInterpolate(snes->dm,interp,fine);
4030:       MatDestroy(&interp);
4031:       x    = xnew;

4033:       SNESReset(snes);
4034:       SNESSetDM(snes,fine);
4035:       DMDestroy(&fine);
4036:       PetscViewerASCIIPopTab(PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes)));
4037:     }
4038:   }
4039:   SNESViewFromOptions(snes,NULL,"-snes_view");
4040:   VecViewFromOptions(snes->vec_sol,(PetscObject)snes,"-snes_view_solution");

4042:   VecDestroy(&xcreated);
4043:   PetscObjectSAWsBlock((PetscObject)snes);
4044:   return(0);
4045: }

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

4051: /*@C
4052:    SNESSetType - Sets the method for the nonlinear solver.

4054:    Collective on SNES

4056:    Input Parameters:
4057: +  snes - the SNES context
4058: -  type - a known method

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

4064:    Notes:
4065:    See "petsc/include/petscsnes.h" for available methods (for instance)
4066: +    SNESNEWTONLS - Newton's method with line search
4067:      (systems of nonlinear equations)
4068: .    SNESNEWTONTR - Newton's method with trust region
4069:      (systems of nonlinear equations)

4071:   Normally, it is best to use the SNESSetFromOptions() command and then
4072:   set the SNES solver type from the options database rather than by using
4073:   this routine.  Using the options database provides the user with
4074:   maximum flexibility in evaluating the many nonlinear solvers.
4075:   The SNESSetType() routine is provided for those situations where it
4076:   is necessary to set the nonlinear solver independently of the command
4077:   line or options database.  This might be the case, for example, when
4078:   the choice of solver changes during the execution of the program,
4079:   and the user's application is taking responsibility for choosing the
4080:   appropriate method.

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

4085:   Level: intermediate

4087: .keywords: SNES, set, type

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

4091: @*/
4092: PetscErrorCode  SNESSetType(SNES snes,SNESType type)
4093: {
4094:   PetscErrorCode ierr,(*r)(SNES);
4095:   PetscBool      match;


4101:   PetscObjectTypeCompare((PetscObject)snes,type,&match);
4102:   if (match) return(0);

4104:    PetscFunctionListFind(SNESList,type,&r);
4105:   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unable to find requested SNES type %s",type);
4106:   /* Destroy the previous private SNES context */
4107:   if (snes->ops->destroy) {
4108:     (*(snes)->ops->destroy)(snes);
4109:     snes->ops->destroy = NULL;
4110:   }
4111:   /* Reinitialize function pointers in SNESOps structure */
4112:   snes->ops->setup          = 0;
4113:   snes->ops->solve          = 0;
4114:   snes->ops->view           = 0;
4115:   snes->ops->setfromoptions = 0;
4116:   snes->ops->destroy        = 0;
4117:   /* Call the SNESCreate_XXX routine for this particular Nonlinear solver */
4118:   snes->setupcalled = PETSC_FALSE;

4120:   PetscObjectChangeTypeName((PetscObject)snes,type);
4121:   (*r)(snes);
4122:   return(0);
4123: }

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

4130:    Not Collective

4132:    Input Parameter:
4133: .  snes - nonlinear solver context

4135:    Output Parameter:
4136: .  type - SNES method (a character string)

4138:    Level: intermediate

4140: .keywords: SNES, nonlinear, get, type, name
4141: @*/
4142: PetscErrorCode  SNESGetType(SNES snes,SNESType *type)
4143: {
4147:   *type = ((PetscObject)snes)->type_name;
4148:   return(0);
4149: }

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

4156:   Logically Collective on SNES and Vec

4158:   Input Parameters:
4159: + snes - the SNES context obtained from SNESCreate()
4160: - u    - the solution vector

4162:   Level: beginner

4164: .keywords: SNES, set, solution
4165: @*/
4166: PetscErrorCode SNESSetSolution(SNES snes, Vec u)
4167: {
4168:   DM             dm;

4174:   PetscObjectReference((PetscObject) u);
4175:   VecDestroy(&snes->vec_sol);

4177:   snes->vec_sol = u;

4179:   SNESGetDM(snes, &dm);
4180:   DMShellSetGlobalVector(dm, u);
4181:   return(0);
4182: }

4186: /*@
4187:    SNESGetSolution - Returns the vector where the approximate solution is
4188:    stored. This is the fine grid solution when using SNESSetGridSequence().

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

4192:    Input Parameter:
4193: .  snes - the SNES context

4195:    Output Parameter:
4196: .  x - the solution

4198:    Level: intermediate

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

4202: .seealso:  SNESGetSolutionUpdate(), SNESGetFunction()
4203: @*/
4204: PetscErrorCode  SNESGetSolution(SNES snes,Vec *x)
4205: {
4209:   *x = snes->vec_sol;
4210:   return(0);
4211: }

4215: /*@
4216:    SNESGetSolutionUpdate - Returns the vector where the solution update is
4217:    stored.

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

4221:    Input Parameter:
4222: .  snes - the SNES context

4224:    Output Parameter:
4225: .  x - the solution update

4227:    Level: advanced

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

4231: .seealso: SNESGetSolution(), SNESGetFunction()
4232: @*/
4233: PetscErrorCode  SNESGetSolutionUpdate(SNES snes,Vec *x)
4234: {
4238:   *x = snes->vec_sol_update;
4239:   return(0);
4240: }

4244: /*@C
4245:    SNESGetFunction - Returns the vector where the function is stored.

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

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

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

4257:    Level: advanced

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

4261: .seealso: SNESSetFunction(), SNESGetSolution(), SNESFunction
4262: @*/
4263: PetscErrorCode  SNESGetFunction(SNES snes,Vec *r,PetscErrorCode (**f)(SNES,Vec,Vec,void*),void **ctx)
4264: {
4266:   DM             dm;

4270:   if (r) {
4271:     if (!snes->vec_func) {
4272:       if (snes->vec_rhs) {
4273:         VecDuplicate(snes->vec_rhs,&snes->vec_func);
4274:       } else if (snes->vec_sol) {
4275:         VecDuplicate(snes->vec_sol,&snes->vec_func);
4276:       } else if (snes->dm) {
4277:         DMCreateGlobalVector(snes->dm,&snes->vec_func);
4278:       }
4279:     }
4280:     *r = snes->vec_func;
4281:   }
4282:   SNESGetDM(snes,&dm);
4283:   DMSNESGetFunction(dm,f,ctx);
4284:   return(0);
4285: }

4287: /*@C
4288:    SNESGetNGS - Returns the NGS function and context.

4290:    Input Parameter:
4291: .  snes - the SNES context

4293:    Output Parameter:
4294: +  f - the function (or NULL) see SNESNGSFunction for details
4295: -  ctx    - the function context (or NULL)

4297:    Level: advanced

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

4301: .seealso: SNESSetNGS(), SNESGetFunction()
4302: @*/

4306: PetscErrorCode SNESGetNGS (SNES snes, PetscErrorCode (**f)(SNES, Vec, Vec, void*), void ** ctx)
4307: {
4309:   DM             dm;

4313:   SNESGetDM(snes,&dm);
4314:   DMSNESGetNGS(dm,f,ctx);
4315:   return(0);
4316: }

4320: /*@C
4321:    SNESSetOptionsPrefix - Sets the prefix used for searching for all
4322:    SNES options in the database.

4324:    Logically Collective on SNES

4326:    Input Parameter:
4327: +  snes - the SNES context
4328: -  prefix - the prefix to prepend to all option names

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

4334:    Level: advanced

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

4338: .seealso: SNESSetFromOptions()
4339: @*/
4340: PetscErrorCode  SNESSetOptionsPrefix(SNES snes,const char prefix[])
4341: {

4346:   PetscObjectSetOptionsPrefix((PetscObject)snes,prefix);
4347:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4348:   if (snes->linesearch) {
4349:     SNESGetLineSearch(snes,&snes->linesearch);
4350:     PetscObjectSetOptionsPrefix((PetscObject)snes->linesearch,prefix);
4351:   }
4352:   KSPSetOptionsPrefix(snes->ksp,prefix);
4353:   return(0);
4354: }

4358: /*@C
4359:    SNESAppendOptionsPrefix - Appends to the prefix used for searching for all
4360:    SNES options in the database.

4362:    Logically Collective on SNES

4364:    Input Parameters:
4365: +  snes - the SNES context
4366: -  prefix - the prefix to prepend to all option names

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

4372:    Level: advanced

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

4376: .seealso: SNESGetOptionsPrefix()
4377: @*/
4378: PetscErrorCode  SNESAppendOptionsPrefix(SNES snes,const char prefix[])
4379: {

4384:   PetscObjectAppendOptionsPrefix((PetscObject)snes,prefix);
4385:   if (!snes->ksp) {SNESGetKSP(snes,&snes->ksp);}
4386:   if (snes->linesearch) {
4387:     SNESGetLineSearch(snes,&snes->linesearch);
4388:     PetscObjectAppendOptionsPrefix((PetscObject)snes->linesearch,prefix);
4389:   }
4390:   KSPAppendOptionsPrefix(snes->ksp,prefix);
4391:   return(0);
4392: }

4396: /*@C
4397:    SNESGetOptionsPrefix - Sets the prefix used for searching for all
4398:    SNES options in the database.

4400:    Not Collective

4402:    Input Parameter:
4403: .  snes - the SNES context

4405:    Output Parameter:
4406: .  prefix - pointer to the prefix string used

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

4411:    Level: advanced

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

4415: .seealso: SNESAppendOptionsPrefix()
4416: @*/
4417: PetscErrorCode  SNESGetOptionsPrefix(SNES snes,const char *prefix[])
4418: {

4423:   PetscObjectGetOptionsPrefix((PetscObject)snes,prefix);
4424:   return(0);
4425: }


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

4433:    Not collective

4435:    Input Parameters:
4436: +  name_solver - name of a new user-defined solver
4437: -  routine_create - routine to create method context

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

4442:    Sample usage:
4443: .vb
4444:    SNESRegister("my_solver",MySolverCreate);
4445: .ve

4447:    Then, your solver can be chosen with the procedural interface via
4448: $     SNESSetType(snes,"my_solver")
4449:    or at runtime via the option
4450: $     -snes_type my_solver

4452:    Level: advanced

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

4456: .keywords: SNES, nonlinear, register

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

4460:   Level: advanced
4461: @*/
4462: PetscErrorCode  SNESRegister(const char sname[],PetscErrorCode (*function)(SNES))
4463: {

4467:   PetscFunctionListAdd(&SNESList,sname,function);
4468:   return(0);
4469: }

4473: PetscErrorCode  SNESTestLocalMin(SNES snes)
4474: {
4476:   PetscInt       N,i,j;
4477:   Vec            u,uh,fh;
4478:   PetscScalar    value;
4479:   PetscReal      norm;

4482:   SNESGetSolution(snes,&u);
4483:   VecDuplicate(u,&uh);
4484:   VecDuplicate(u,&fh);

4486:   /* currently only works for sequential */
4487:   PetscPrintf(PETSC_COMM_WORLD,"Testing FormFunction() for local min\n");
4488:   VecGetSize(u,&N);
4489:   for (i=0; i<N; i++) {
4490:     VecCopy(u,uh);
4491:     PetscPrintf(PETSC_COMM_WORLD,"i = %D\n",i);
4492:     for (j=-10; j<11; j++) {
4493:       value = PetscSign(j)*PetscExpReal(PetscAbs(j)-10.0);
4494:       VecSetValue(uh,i,value,ADD_VALUES);
4495:       SNESComputeFunction(snes,uh,fh);
4496:       VecNorm(fh,NORM_2,&norm);
4497:       PetscPrintf(PETSC_COMM_WORLD,"       j norm %D %18.16e\n",j,norm);
4498:       value = -value;
4499:       VecSetValue(uh,i,value,ADD_VALUES);
4500:     }
4501:   }
4502:   VecDestroy(&uh);
4503:   VecDestroy(&fh);
4504:   return(0);
4505: }

4509: /*@
4510:    SNESKSPSetUseEW - Sets SNES use Eisenstat-Walker method for
4511:    computing relative tolerance for linear solvers within an inexact
4512:    Newton method.

4514:    Logically Collective on SNES

4516:    Input Parameters:
4517: +  snes - SNES context
4518: -  flag - PETSC_TRUE or PETSC_FALSE

4520:     Options Database:
4521: +  -snes_ksp_ew - use Eisenstat-Walker method for determining linear system convergence
4522: .  -snes_ksp_ew_version ver - version of  Eisenstat-Walker method
4523: .  -snes_ksp_ew_rtol0 <rtol0> - Sets rtol0
4524: .  -snes_ksp_ew_rtolmax <rtolmax> - Sets rtolmax
4525: .  -snes_ksp_ew_gamma <gamma> - Sets gamma
4526: .  -snes_ksp_ew_alpha <alpha> - Sets alpha
4527: .  -snes_ksp_ew_alpha2 <alpha2> - Sets alpha2
4528: -  -snes_ksp_ew_threshold <threshold> - Sets threshold

4530:    Notes:
4531:    Currently, the default is to use a constant relative tolerance for
4532:    the inner linear solvers.  Alternatively, one can use the
4533:    Eisenstat-Walker method, where the relative convergence tolerance
4534:    is reset at each Newton iteration according progress of the nonlinear
4535:    solver.

4537:    Level: advanced

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

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

4545: .seealso: SNESKSPGetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4546: @*/
4547: PetscErrorCode  SNESKSPSetUseEW(SNES snes,PetscBool flag)
4548: {
4552:   snes->ksp_ewconv = flag;
4553:   return(0);
4554: }

4558: /*@
4559:    SNESKSPGetUseEW - Gets if SNES is using Eisenstat-Walker method
4560:    for computing relative tolerance for linear solvers within an
4561:    inexact Newton method.

4563:    Not Collective

4565:    Input Parameter:
4566: .  snes - SNES context

4568:    Output Parameter:
4569: .  flag - PETSC_TRUE or PETSC_FALSE

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

4578:    Level: advanced

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

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

4586: .seealso: SNESKSPSetUseEW(), SNESKSPGetParametersEW(), SNESKSPSetParametersEW()
4587: @*/
4588: PetscErrorCode  SNESKSPGetUseEW(SNES snes, PetscBool  *flag)
4589: {
4593:   *flag = snes->ksp_ewconv;
4594:   return(0);
4595: }

4599: /*@
4600:    SNESKSPSetParametersEW - Sets parameters for Eisenstat-Walker
4601:    convergence criteria for the linear solvers within an inexact
4602:    Newton method.

4604:    Logically Collective on SNES

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

4617:    Note:
4618:    Version 3 was contributed by Luis Chacon, June 2006.

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

4622:    Level: advanced

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

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

4631: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPGetParametersEW()
4632: @*/
4633: PetscErrorCode  SNESKSPSetParametersEW(SNES snes,PetscInt version,PetscReal rtol_0,PetscReal rtol_max,PetscReal gamma,PetscReal alpha,PetscReal alpha2,PetscReal threshold)
4634: {
4635:   SNESKSPEW *kctx;

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

4649:   if (version != PETSC_DEFAULT)   kctx->version   = version;
4650:   if (rtol_0 != PETSC_DEFAULT)    kctx->rtol_0    = rtol_0;
4651:   if (rtol_max != PETSC_DEFAULT)  kctx->rtol_max  = rtol_max;
4652:   if (gamma != PETSC_DEFAULT)     kctx->gamma     = gamma;
4653:   if (alpha != PETSC_DEFAULT)     kctx->alpha     = alpha;
4654:   if (alpha2 != PETSC_DEFAULT)    kctx->alpha2    = alpha2;
4655:   if (threshold != PETSC_DEFAULT) kctx->threshold = threshold;

4657:   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);
4658:   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);
4659:   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);
4660:   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);
4661:   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);
4662:   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);
4663:   return(0);
4664: }

4668: /*@
4669:    SNESKSPGetParametersEW - Gets parameters for Eisenstat-Walker
4670:    convergence criteria for the linear solvers within an inexact
4671:    Newton method.

4673:    Not Collective

4675:    Input Parameters:
4676:      snes - SNES context

4678:    Output Parameters:
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 (0 <= gamma2 <= 1)
4683: .    alpha - power for version 2 rtol computation (1 < alpha <= 2)
4684: .    alpha2 - power for safeguard
4685: -    threshold - threshold for imposing safeguard (0 < threshold < 1)

4687:    Level: advanced

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

4691: .seealso: SNESKSPSetUseEW(), SNESKSPGetUseEW(), SNESKSPSetParametersEW()
4692: @*/
4693: PetscErrorCode  SNESKSPGetParametersEW(SNES snes,PetscInt *version,PetscReal *rtol_0,PetscReal *rtol_max,PetscReal *gamma,PetscReal *alpha,PetscReal *alpha2,PetscReal *threshold)
4694: {
4695:   SNESKSPEW *kctx;

4699:   kctx = (SNESKSPEW*)snes->kspconvctx;
4700:   if (!kctx) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"No Eisenstat-Walker context existing");
4701:   if (version)   *version   = kctx->version;
4702:   if (rtol_0)    *rtol_0    = kctx->rtol_0;
4703:   if (rtol_max)  *rtol_max  = kctx->rtol_max;
4704:   if (gamma)     *gamma     = kctx->gamma;
4705:   if (alpha)     *alpha     = kctx->alpha;
4706:   if (alpha2)    *alpha2    = kctx->alpha2;
4707:   if (threshold) *threshold = kctx->threshold;
4708:   return(0);
4709: }

4713:  PetscErrorCode KSPPreSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4714: {
4716:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4717:   PetscReal      rtol  = PETSC_DEFAULT,stol;

4720:   if (!snes->ksp_ewconv) return(0);
4721:   if (!snes->iter) {
4722:     rtol = kctx->rtol_0; /* first time in, so use the original user rtol */
4723:     VecNorm(snes->vec_func,NORM_2,&kctx->norm_first);
4724:   }
4725:   else {
4726:     if (kctx->version == 1) {
4727:       rtol = (snes->norm - kctx->lresid_last)/kctx->norm_last;
4728:       if (rtol < 0.0) rtol = -rtol;
4729:       stol = PetscPowReal(kctx->rtol_last,kctx->alpha2);
4730:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4731:     } else if (kctx->version == 2) {
4732:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4733:       stol = kctx->gamma * PetscPowReal(kctx->rtol_last,kctx->alpha);
4734:       if (stol > kctx->threshold) rtol = PetscMax(rtol,stol);
4735:     } else if (kctx->version == 3) { /* contributed by Luis Chacon, June 2006. */
4736:       rtol = kctx->gamma * PetscPowReal(snes->norm/kctx->norm_last,kctx->alpha);
4737:       /* safeguard: avoid sharp decrease of rtol */
4738:       stol = kctx->gamma*PetscPowReal(kctx->rtol_last,kctx->alpha);
4739:       stol = PetscMax(rtol,stol);
4740:       rtol = PetscMin(kctx->rtol_0,stol);
4741:       /* safeguard: avoid oversolving */
4742:       stol = kctx->gamma*(kctx->norm_first*snes->rtol)/snes->norm;
4743:       stol = PetscMax(rtol,stol);
4744:       rtol = PetscMin(kctx->rtol_0,stol);
4745:     } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Only versions 1, 2 or 3 are supported: %D",kctx->version);
4746:   }
4747:   /* safeguard: avoid rtol greater than one */
4748:   rtol = PetscMin(rtol,kctx->rtol_max);
4749:   KSPSetTolerances(ksp,rtol,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT);
4750:   PetscInfo3(snes,"iter %D, Eisenstat-Walker (version %D) KSP rtol=%g\n",snes->iter,kctx->version,(double)rtol);
4751:   return(0);
4752: }

4756: PetscErrorCode KSPPostSolve_SNESEW(KSP ksp, Vec b, Vec x, SNES snes)
4757: {
4759:   SNESKSPEW      *kctx = (SNESKSPEW*)snes->kspconvctx;
4760:   PCSide         pcside;
4761:   Vec            lres;

4764:   if (!snes->ksp_ewconv) return(0);
4765:   KSPGetTolerances(ksp,&kctx->rtol_last,0,0,0);
4766:   kctx->norm_last = snes->norm;
4767:   if (kctx->version == 1) {
4768:     PC        pc;
4769:     PetscBool isNone;

4771:     KSPGetPC(ksp, &pc);
4772:     PetscObjectTypeCompare((PetscObject) pc, PCNONE, &isNone);
4773:     KSPGetPCSide(ksp,&pcside);
4774:      if (pcside == PC_RIGHT || isNone) { /* XXX Should we also test KSP_UNPRECONDITIONED_NORM ? */
4775:       /* KSP residual is true linear residual */
4776:       KSPGetResidualNorm(ksp,&kctx->lresid_last);
4777:     } else {
4778:       /* KSP residual is preconditioned residual */
4779:       /* compute true linear residual norm */
4780:       VecDuplicate(b,&lres);
4781:       MatMult(snes->jacobian,x,lres);
4782:       VecAYPX(lres,-1.0,b);
4783:       VecNorm(lres,NORM_2,&kctx->lresid_last);
4784:       VecDestroy(&lres);
4785:     }
4786:   }
4787:   return(0);
4788: }

4792: /*@
4793:    SNESGetKSP - Returns the KSP context for a SNES solver.

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

4797:    Input Parameter:
4798: .  snes - the SNES context

4800:    Output Parameter:
4801: .  ksp - the KSP context

4803:    Notes:
4804:    The user can then directly manipulate the KSP context to set various
4805:    options, etc.  Likewise, the user can then extract and manipulate the
4806:    PC contexts as well.

4808:    Level: beginner

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

4812: .seealso: KSPGetPC(), SNESCreate(), KSPCreate(), SNESSetKSP()
4813: @*/
4814: PetscErrorCode  SNESGetKSP(SNES snes,KSP *ksp)
4815: {


4822:   if (!snes->ksp) {
4823:     PetscBool monitor = PETSC_FALSE;

4825:     KSPCreate(PetscObjectComm((PetscObject)snes),&snes->ksp);
4826:     PetscObjectIncrementTabLevel((PetscObject)snes->ksp,(PetscObject)snes,1);
4827:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->ksp);

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

4832:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes",&monitor,NULL);
4833:     if (monitor) {
4834:       KSPMonitorSet(snes->ksp,KSPMonitorSNES,snes,NULL);
4835:     }
4836:     monitor = PETSC_FALSE;
4837:     PetscOptionsGetBool(((PetscObject)snes)->options,((PetscObject)snes)->prefix,"-ksp_monitor_snes_lg",&monitor,NULL);
4838:     if (monitor) {
4839:       PetscObject *objs;
4840:       KSPMonitorSNESLGResidualNormCreate(PetscObjectComm((PetscObject)snes),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,600,&objs);
4841:       objs[0] = (PetscObject) snes;
4842:       KSPMonitorSet(snes->ksp,(PetscErrorCode (*)(KSP,PetscInt,PetscReal,void*))KSPMonitorSNESLGResidualNorm,objs,(PetscErrorCode (*)(void**))KSPMonitorSNESLGResidualNormDestroy);
4843:     }
4844:   }
4845:   *ksp = snes->ksp;
4846:   return(0);
4847: }


4850: #include <petsc/private/dmimpl.h>
4853: /*@
4854:    SNESSetDM - Sets the DM that may be used by some preconditioners

4856:    Logically Collective on SNES

4858:    Input Parameters:
4859: +  snes - the preconditioner context
4860: -  dm - the dm

4862:    Level: intermediate

4864: .seealso: SNESGetDM(), KSPSetDM(), KSPGetDM()
4865: @*/
4866: PetscErrorCode  SNESSetDM(SNES snes,DM dm)
4867: {
4869:   KSP            ksp;
4870:   DMSNES         sdm;

4874:   if (dm) {PetscObjectReference((PetscObject)dm);}
4875:   if (snes->dm) {               /* Move the DMSNES context over to the new DM unless the new DM already has one */
4876:     if (snes->dm->dmsnes && snes->dmAuto && !dm->dmsnes) {
4877:       DMCopyDMSNES(snes->dm,dm);
4878:       DMGetDMSNES(snes->dm,&sdm);
4879:       if (sdm->originaldm == snes->dm) sdm->originaldm = dm; /* Grant write privileges to the replacement DM */
4880:     }
4881:     DMDestroy(&snes->dm);
4882:   }
4883:   snes->dm     = dm;
4884:   snes->dmAuto = PETSC_FALSE;

4886:   SNESGetKSP(snes,&ksp);
4887:   KSPSetDM(ksp,dm);
4888:   KSPSetDMActive(ksp,PETSC_FALSE);
4889:   if (snes->pc) {
4890:     SNESSetDM(snes->pc, snes->dm);
4891:     SNESSetNPCSide(snes,snes->pcside);
4892:   }
4893:   return(0);
4894: }

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

4901:    Not Collective but DM obtained is parallel on SNES

4903:    Input Parameter:
4904: . snes - the preconditioner context

4906:    Output Parameter:
4907: .  dm - the dm

4909:    Level: intermediate

4911: .seealso: SNESSetDM(), KSPSetDM(), KSPGetDM()
4912: @*/
4913: PetscErrorCode  SNESGetDM(SNES snes,DM *dm)
4914: {

4919:   if (!snes->dm) {
4920:     DMShellCreate(PetscObjectComm((PetscObject)snes),&snes->dm);
4921:     snes->dmAuto = PETSC_TRUE;
4922:   }
4923:   *dm = snes->dm;
4924:   return(0);
4925: }

4929: /*@
4930:   SNESSetNPC - Sets the nonlinear preconditioner to be used.

4932:   Collective on SNES

4934:   Input Parameters:
4935: + snes - iterative context obtained from SNESCreate()
4936: - pc   - the preconditioner object

4938:   Notes:
4939:   Use SNESGetNPC() to retrieve the preconditioner context (for example,
4940:   to configure it using the API).

4942:   Level: developer

4944: .keywords: SNES, set, precondition
4945: .seealso: SNESGetNPC(), SNESHasNPC()
4946: @*/
4947: PetscErrorCode SNESSetNPC(SNES snes, SNES pc)
4948: {

4955:   PetscObjectReference((PetscObject) pc);
4956:   SNESDestroy(&snes->pc);
4957:   snes->pc = pc;
4958:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->pc);
4959:   return(0);
4960: }

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

4967:   Not Collective

4969:   Input Parameter:
4970: . snes - iterative context obtained from SNESCreate()

4972:   Output Parameter:
4973: . pc - preconditioner context

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

4977:   Level: developer

4979: .keywords: SNES, get, preconditioner
4980: .seealso: SNESSetNPC(), SNESHasNPC()
4981: @*/
4982: PetscErrorCode SNESGetNPC(SNES snes, SNES *pc)
4983: {
4985:   const char     *optionsprefix;

4990:   if (!snes->pc) {
4991:     SNESCreate(PetscObjectComm((PetscObject)snes),&snes->pc);
4992:     PetscObjectIncrementTabLevel((PetscObject)snes->pc,(PetscObject)snes,1);
4993:     PetscLogObjectParent((PetscObject)snes,(PetscObject)snes->pc);
4994:     SNESGetOptionsPrefix(snes,&optionsprefix);
4995:     SNESSetOptionsPrefix(snes->pc,optionsprefix);
4996:     SNESAppendOptionsPrefix(snes->pc,"npc_");
4997:     SNESSetCountersReset(snes->pc,PETSC_FALSE);
4998:   }
4999:   *pc = snes->pc;
5000:   return(0);
5001: }

5005: /*@
5006:   SNESHasNPC - Returns whether a nonlinear preconditioner exists

5008:   Not Collective

5010:   Input Parameter:
5011: . snes - iterative context obtained from SNESCreate()

5013:   Output Parameter:
5014: . has_npc - whether the SNES has an NPC or not

5016:   Level: developer

5018: .keywords: SNES, has, preconditioner
5019: .seealso: SNESSetNPC(), SNESGetNPC()
5020: @*/
5021: PetscErrorCode SNESHasNPC(SNES snes, PetscBool *has_npc)
5022: {
5025:   *has_npc = (PetscBool) (snes->pc ? PETSC_TRUE : PETSC_FALSE);
5026:   return(0);
5027: }

5031: /*@
5032:     SNESSetNPCSide - Sets the preconditioning side.

5034:     Logically Collective on SNES

5036:     Input Parameter:
5037: .   snes - iterative context obtained from SNESCreate()

5039:     Output Parameter:
5040: .   side - the preconditioning side, where side is one of
5041: .vb
5042:       PC_LEFT - left preconditioning (default)
5043:       PC_RIGHT - right preconditioning
5044: .ve

5046:     Options Database Keys:
5047: .   -snes_pc_side <right,left>

5049:     Level: intermediate

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

5053: .seealso: SNESGetNPCSide(), KSPSetPCSide()
5054: @*/
5055: PetscErrorCode  SNESSetNPCSide(SNES snes,PCSide side)
5056: {
5060:   snes->pcside = side;
5061:   return(0);
5062: }

5066: /*@
5067:     SNESGetNPCSide - Gets the preconditioning side.

5069:     Not Collective

5071:     Input Parameter:
5072: .   snes - iterative context obtained from SNESCreate()

5074:     Output Parameter:
5075: .   side - the preconditioning side, where side is one of
5076: .vb
5077:       PC_LEFT - left preconditioning (default)
5078:       PC_RIGHT - right preconditioning
5079: .ve

5081:     Level: intermediate

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

5085: .seealso: SNESSetNPCSide(), KSPGetPCSide()
5086: @*/
5087: PetscErrorCode  SNESGetNPCSide(SNES snes,PCSide *side)
5088: {
5092:   *side = snes->pcside;
5093:   return(0);
5094: }

5098: /*@
5099:   SNESSetLineSearch - Sets the linesearch on the SNES instance.

5101:   Collective on SNES

5103:   Input Parameters:
5104: + snes - iterative context obtained from SNESCreate()
5105: - linesearch   - the linesearch object

5107:   Notes:
5108:   Use SNESGetLineSearch() to retrieve the preconditioner context (for example,
5109:   to configure it using the API).

5111:   Level: developer

5113: .keywords: SNES, set, linesearch
5114: .seealso: SNESGetLineSearch()
5115: @*/
5116: PetscErrorCode SNESSetLineSearch(SNES snes, SNESLineSearch linesearch)
5117: {

5124:   PetscObjectReference((PetscObject) linesearch);
5125:   SNESLineSearchDestroy(&snes->linesearch);

5127:   snes->linesearch = linesearch;

5129:   PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5130:   return(0);
5131: }

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

5139:   Not Collective

5141:   Input Parameter:
5142: . snes - iterative context obtained from SNESCreate()

5144:   Output Parameter:
5145: . linesearch - linesearch context

5147:   Level: beginner

5149: .keywords: SNES, get, linesearch
5150: .seealso: SNESSetLineSearch(), SNESLineSearchCreate()
5151: @*/
5152: PetscErrorCode SNESGetLineSearch(SNES snes, SNESLineSearch *linesearch)
5153: {
5155:   const char     *optionsprefix;

5160:   if (!snes->linesearch) {
5161:     SNESGetOptionsPrefix(snes, &optionsprefix);
5162:     SNESLineSearchCreate(PetscObjectComm((PetscObject)snes), &snes->linesearch);
5163:     SNESLineSearchSetSNES(snes->linesearch, snes);
5164:     SNESLineSearchAppendOptionsPrefix(snes->linesearch, optionsprefix);
5165:     PetscObjectIncrementTabLevel((PetscObject) snes->linesearch, (PetscObject) snes, 1);
5166:     PetscLogObjectParent((PetscObject)snes, (PetscObject)snes->linesearch);
5167:   }
5168:   *linesearch = snes->linesearch;
5169:   return(0);
5170: }

5172: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5173: #include <mex.h>

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

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

5182:    Collective on SNES

5184:    Input Parameters:
5185: +  snes - the SNES context
5186: -  x - input vector

5188:    Output Parameter:
5189: .  y - function vector, as set by SNESSetFunction()

5191:    Notes:
5192:    SNESComputeFunction() is typically used within nonlinear solvers
5193:    implementations, so most users would not generally call this routine
5194:    themselves.

5196:    Level: developer

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

5200: .seealso: SNESSetFunction(), SNESGetFunction()
5201: */
5202: PetscErrorCode  SNESComputeFunction_Matlab(SNES snes,Vec x,Vec y, void *ctx)
5203: {
5204:   PetscErrorCode    ierr;
5205:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5206:   int               nlhs  = 1,nrhs = 5;
5207:   mxArray           *plhs[1],*prhs[5];
5208:   long long int     lx = 0,ly = 0,ls = 0;


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

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

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

5244:    Logically Collective on SNES

5246:    Input Parameters:
5247: +  snes - the SNES context
5248: .  r - vector to store function value
5249: -  f - function evaluation routine

5251:    Notes:
5252:    The Newton-like methods typically solve linear systems of the form
5253: $      f'(x) x = -f(x),
5254:    where f'(x) denotes the Jacobian matrix and f(x) is the function.

5256:    Level: beginner

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

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

5262: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5263: */
5264: PetscErrorCode  SNESSetFunctionMatlab(SNES snes,Vec r,const char *f,mxArray *ctx)
5265: {
5266:   PetscErrorCode    ierr;
5267:   SNESMatlabContext *sctx;

5270:   /* currently sctx is memory bleed */
5271:   PetscNew(&sctx);
5272:   PetscStrallocpy(f,&sctx->funcname);
5273:   /*
5274:      This should work, but it doesn't
5275:   sctx->ctx = ctx;
5276:   mexMakeArrayPersistent(sctx->ctx);
5277:   */
5278:   sctx->ctx = mxDuplicateArray(ctx);
5279:   SNESSetFunction(snes,r,SNESComputeFunction_Matlab,sctx);
5280:   return(0);
5281: }

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

5288:    Collective on SNES

5290:    Input Parameters:
5291: +  snes - the SNES context
5292: .  x - input vector
5293: .  A, B - the matrices
5294: -  ctx - user context

5296:    Level: developer

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

5300: .seealso: SNESSetFunction(), SNESGetFunction()
5301: @*/
5302: PetscErrorCode  SNESComputeJacobian_Matlab(SNES snes,Vec x,Mat A,Mat B,void *ctx)
5303: {
5304:   PetscErrorCode    ierr;
5305:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5306:   int               nlhs  = 2,nrhs = 6;
5307:   mxArray           *plhs[2],*prhs[6];
5308:   long long int     lx = 0,lA = 0,ls = 0, lB = 0;


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

5316:   PetscMemcpy(&ls,&snes,sizeof(snes));
5317:   PetscMemcpy(&lx,&x,sizeof(x));
5318:   PetscMemcpy(&lA,A,sizeof(x));
5319:   PetscMemcpy(&lB,B,sizeof(x));
5320:   prhs[0] = mxCreateDoubleScalar((double)ls);
5321:   prhs[1] = mxCreateDoubleScalar((double)lx);
5322:   prhs[2] = mxCreateDoubleScalar((double)lA);
5323:   prhs[3] = mxCreateDoubleScalar((double)lB);
5324:   prhs[4] = mxCreateString(sctx->funcname);
5325:   prhs[5] = sctx->ctx;
5326:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESComputeJacobianInternal");
5327:   mxGetScalar(plhs[0]);
5328:   mxDestroyArray(prhs[0]);
5329:   mxDestroyArray(prhs[1]);
5330:   mxDestroyArray(prhs[2]);
5331:   mxDestroyArray(prhs[3]);
5332:   mxDestroyArray(prhs[4]);
5333:   mxDestroyArray(plhs[0]);
5334:   mxDestroyArray(plhs[1]);
5335:   return(0);
5336: }

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

5345:    Logically Collective on SNES

5347:    Input Parameters:
5348: +  snes - the SNES context
5349: .  A,B - Jacobian matrices
5350: .  J - function evaluation routine
5351: -  ctx - user context

5353:    Level: developer

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

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

5359: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction(), J
5360: */
5361: PetscErrorCode  SNESSetJacobianMatlab(SNES snes,Mat A,Mat B,const char *J,mxArray *ctx)
5362: {
5363:   PetscErrorCode    ierr;
5364:   SNESMatlabContext *sctx;

5367:   /* currently sctx is memory bleed */
5368:   PetscNew(&sctx);
5369:   PetscStrallocpy(J,&sctx->funcname);
5370:   /*
5371:      This should work, but it doesn't
5372:   sctx->ctx = ctx;
5373:   mexMakeArrayPersistent(sctx->ctx);
5374:   */
5375:   sctx->ctx = mxDuplicateArray(ctx);
5376:   SNESSetJacobian(snes,A,B,SNESComputeJacobian_Matlab,sctx);
5377:   return(0);
5378: }

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

5385:    Collective on SNES

5387: .seealso: SNESSetFunction(), SNESGetFunction()
5388: @*/
5389: PetscErrorCode  SNESMonitor_Matlab(SNES snes,PetscInt it, PetscReal fnorm, void *ctx)
5390: {
5391:   PetscErrorCode    ierr;
5392:   SNESMatlabContext *sctx = (SNESMatlabContext*)ctx;
5393:   int               nlhs  = 1,nrhs = 6;
5394:   mxArray           *plhs[1],*prhs[6];
5395:   long long int     lx = 0,ls = 0;
5396:   Vec               x  = snes->vec_sol;


5401:   PetscMemcpy(&ls,&snes,sizeof(snes));
5402:   PetscMemcpy(&lx,&x,sizeof(x));
5403:   prhs[0] = mxCreateDoubleScalar((double)ls);
5404:   prhs[1] = mxCreateDoubleScalar((double)it);
5405:   prhs[2] = mxCreateDoubleScalar((double)fnorm);
5406:   prhs[3] = mxCreateDoubleScalar((double)lx);
5407:   prhs[4] = mxCreateString(sctx->funcname);
5408:   prhs[5] = sctx->ctx;
5409:   mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscSNESMonitorInternal");
5410:   mxGetScalar(plhs[0]);
5411:   mxDestroyArray(prhs[0]);
5412:   mxDestroyArray(prhs[1]);
5413:   mxDestroyArray(prhs[2]);
5414:   mxDestroyArray(prhs[3]);
5415:   mxDestroyArray(prhs[4]);
5416:   mxDestroyArray(plhs[0]);
5417:   return(0);
5418: }

5422: /*
5423:    SNESMonitorSetMatlab - Sets the monitor function from MATLAB

5425:    Level: developer

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

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

5431: .seealso: SNESGetFunction(), SNESComputeFunction(), SNESSetJacobian(), SNESSetFunction()
5432: */
5433: PetscErrorCode  SNESMonitorSetMatlab(SNES snes,const char *f,mxArray *ctx)
5434: {
5435:   PetscErrorCode    ierr;
5436:   SNESMatlabContext *sctx;

5439:   /* currently sctx is memory bleed */
5440:   PetscNew(&sctx);
5441:   PetscStrallocpy(f,&sctx->funcname);
5442:   /*
5443:      This should work, but it doesn't
5444:   sctx->ctx = ctx;
5445:   mexMakeArrayPersistent(sctx->ctx);
5446:   */
5447:   sctx->ctx = mxDuplicateArray(ctx);
5448:   SNESMonitorSet(snes,SNESMonitor_Matlab,sctx,NULL);
5449:   return(0);
5450: }

5452: #endif