Actual source code: snesimpl.h
1: #ifndef __SNESIMPL_H
4: #include <petscsnes.h>
5: #include <petsc/private/petscimpl.h>
7: PETSC_EXTERN PetscBool SNESRegisterAllCalled;
8: PETSC_EXTERN PetscErrorCode SNESRegisterAll(void);
10: typedef struct _SNESOps *SNESOps;
12: struct _SNESOps {
13: PetscErrorCode (*computeinitialguess)(SNES,Vec,void*);
14: PetscErrorCode (*computescaling)(Vec,Vec,void*);
15: PetscErrorCode (*update)(SNES, PetscInt); /* General purpose function for update */
16: PetscErrorCode (*converged)(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*);
17: PetscErrorCode (*convergeddestroy)(void*);
18: PetscErrorCode (*setup)(SNES); /* routine to set up the nonlinear solver */
19: PetscErrorCode (*solve)(SNES); /* actual nonlinear solver */
20: PetscErrorCode (*view)(SNES,PetscViewer);
21: PetscErrorCode (*setfromoptions)(PetscOptionItems*,SNES); /* sets options from database */
22: PetscErrorCode (*destroy)(SNES);
23: PetscErrorCode (*reset)(SNES);
24: PetscErrorCode (*usercompute)(SNES,void**);
25: PetscErrorCode (*userdestroy)(void**);
26: PetscErrorCode (*computevariablebounds)(SNES,Vec,Vec); /* user provided routine to set box constrained variable bounds */
27: PetscErrorCode (*computepfunction)(SNES,Vec,Vec,void*);
28: PetscErrorCode (*computepjacobian)(SNES,Vec,Mat,Mat,void*);
29: PetscErrorCode (*load)(SNES,PetscViewer);
30: };
32: /*
33: Nonlinear solver context
34: */
35: #define MAXSNESMONITORS 5
36: #define MAXSNESREASONVIEWS 5
38: struct _p_SNES {
39: PETSCHEADER(struct _SNESOps);
40: DM dm;
41: PetscBool dmAuto; /* SNES created currently used DM automatically */
42: SNES npc;
43: PCSide npcside;
44: PetscBool usesnpc; /* type can use a nonlinear preconditioner */
46: /* ------------------------ User-provided stuff -------------------------------*/
47: void *user; /* user-defined context */
49: Vec vec_rhs; /* If non-null, solve F(x) = rhs */
50: Vec vec_sol; /* pointer to solution */
52: Vec vec_func; /* pointer to function */
54: Mat jacobian; /* Jacobian matrix */
55: Mat jacobian_pre; /* preconditioner matrix */
56: void *initialguessP; /* user-defined initial guess context */
57: KSP ksp; /* linear solver context */
58: SNESLineSearch linesearch; /* line search context */
59: PetscBool usesksp;
60: MatStructure matstruct; /* Used by Picard solver */
62: Vec vec_sol_update; /* pointer to solution update */
64: Vec scaling; /* scaling vector */
65: void *scaP; /* scaling context */
67: PetscReal precheck_picard_angle; /* For use with SNESLineSearchPreCheckPicard */
69: /* ------------------------Time stepping hooks-----------------------------------*/
71: /* ---------------- PETSc-provided (or user-provided) stuff ---------------------*/
73: PetscErrorCode (*monitor[MAXSNESMONITORS])(SNES,PetscInt,PetscReal,void*); /* monitor routine */
74: PetscErrorCode (*monitordestroy[MAXSNESMONITORS])(void**); /* monitor context destroy routine */
75: void *monitorcontext[MAXSNESMONITORS]; /* monitor context */
76: PetscInt numbermonitors; /* number of monitors */
77: void *cnvP; /* convergence context */
78: SNESConvergedReason reason; /* converged reason */
79: PetscErrorCode (*reasonview[MAXSNESREASONVIEWS])(SNES,void*); /* snes converged reason view */
80: PetscErrorCode (*reasonviewdestroy[MAXSNESREASONVIEWS])(void**); /* reason view context destroy routine */
81: void *reasonviewcontext[MAXSNESREASONVIEWS]; /* reason view context */
82: PetscInt numberreasonviews; /* number of reason views */
83: PetscBool errorifnotconverged;
85: /* --- Routines and data that are unique to each particular solver --- */
87: PetscBool setupcalled; /* true if setup has been called */
88: void *data; /* implementation-specific data */
90: /* -------------------------- Parameters -------------------------------------- */
92: PetscInt max_its; /* max number of iterations */
93: PetscInt max_funcs; /* max number of function evals */
94: PetscInt nfuncs; /* number of function evaluations */
95: PetscInt iter; /* global iteration number */
96: PetscInt linear_its; /* total number of linear solver iterations */
97: PetscReal norm; /* residual norm of current iterate */
98: PetscReal ynorm; /* update norm of current iterate */
99: PetscReal xnorm; /* solution norm of current iterate */
100: PetscReal rtol; /* relative tolerance */
101: PetscReal divtol; /* relative divergence tolerance */
102: PetscReal abstol; /* absolute tolerance */
103: PetscReal stol; /* step length tolerance*/
104: PetscReal deltatol; /* trust region convergence tolerance */
105: PetscBool forceiteration; /* Force SNES to take at least one iteration regardless of the initial residual norm */
106: PetscInt lagpreconditioner; /* SNESSetLagPreconditioner() */
107: PetscInt lagjacobian; /* SNESSetLagJacobian() */
108: PetscInt jac_iter; /* The present iteration of the Jacobian lagging */
109: PetscBool lagjac_persist; /* The jac_iter persists until reset */
110: PetscInt pre_iter; /* The present iteration of the Preconditioner lagging */
111: PetscBool lagpre_persist; /* The pre_iter persists until reset */
112: PetscInt gridsequence; /* number of grid sequence steps to take; defaults to zero */
114: PetscBool tolerancesset; /* SNESSetTolerances() called and tolerances should persist through SNESCreate_XXX()*/
116: PetscBool vec_func_init_set; /* the initial function has been set */
118: SNESNormSchedule normschedule; /* Norm computation type for SNES instance */
119: SNESFunctionType functype; /* Function type for the SNES instance */
121: /* ------------------------ Default work-area management ---------------------- */
123: PetscInt nwork;
124: Vec *work;
126: /* ------------------------- Miscellaneous Information ------------------------ */
128: PetscInt setfromoptionscalled;
129: PetscReal *conv_hist; /* If !0, stores function norm (or
130: gradient norm) at each iteration */
131: PetscInt *conv_hist_its; /* linear iterations for each Newton step */
132: PetscInt conv_hist_len; /* size of convergence history array */
133: PetscInt conv_hist_max; /* actual amount of data in conv_history */
134: PetscBool conv_hist_reset; /* reset counter for each new SNES solve */
135: PetscBool conv_hist_alloc;
136: PetscBool counters_reset; /* reset counter for each new SNES solve */
138: /* the next two are used for failures in the line search; they should be put elsewhere */
139: PetscInt numFailures; /* number of unsuccessful step attempts */
140: PetscInt maxFailures; /* maximum number of unsuccessful step attempts */
142: PetscInt numLinearSolveFailures;
143: PetscInt maxLinearSolveFailures;
145: PetscBool domainerror; /* set with SNESSetFunctionDomainError() */
146: PetscBool jacobiandomainerror; /* set with SNESSetJacobianDomainError() */
147: PetscBool checkjacdomainerror; /* if or not check Jacobian domain error after Jacobian evaluations */
149: PetscBool ksp_ewconv; /* flag indicating use of Eisenstat-Walker KSP convergence criteria */
150: void *kspconvctx; /* Eisenstat-Walker KSP convergence context */
152: /* SNESConvergedDefault context: split it off into a separate var/struct to be passed as context to SNESConvergedDefault? */
153: PetscReal ttol; /* rtol*initial_residual_norm */
154: PetscReal rnorm0; /* initial residual norm (used for divergence testing) */
156: Vec *vwork; /* more work vectors for Jacobian approx */
157: PetscInt nvwork;
159: PetscBool mf; /* -snes_mf was used on this snes */
160: PetscBool mf_operator; /* -snes_mf_operator was used on this snes */
161: PetscInt mf_version; /* The version of snes_mf used */
163: PetscReal vizerotolerance; /* tolerance for considering an x[] value to be on the bound */
164: Vec xl,xu; /* upper and lower bounds for box constrained VI problems */
165: PetscInt ntruebounds; /* number of non-infinite bounds set for VI box constraints */
166: PetscBool usersetbounds; /* bounds have been set via SNESVISetVariableBounds(), rather than via computevariablebounds() callback. */
168: PetscBool alwayscomputesfinalresidual; /* Does SNESSolve_XXX always compute the value of the residual at the final
169: * solution and put it in vec_func? Used inside SNESSolve_FAS to determine
170: * if the final residual must be computed before restricting or prolonging
171: * it. */
173: };
175: typedef struct _p_DMSNES *DMSNES;
176: typedef struct _DMSNESOps *DMSNESOps;
177: struct _DMSNESOps {
178: PetscErrorCode (*computefunction)(SNES,Vec,Vec,void*);
179: PetscErrorCode (*computejacobian)(SNES,Vec,Mat,Mat,void*);
181: /* objective */
182: PetscErrorCode (*computeobjective)(SNES,Vec,PetscReal*,void*);
184: /* Picard iteration functions */
185: PetscErrorCode (*computepfunction)(SNES,Vec,Vec,void*);
186: PetscErrorCode (*computepjacobian)(SNES,Vec,Mat,Mat,void*);
188: /* User-defined smoother */
189: PetscErrorCode (*computegs)(SNES,Vec,Vec,void*);
191: PetscErrorCode (*destroy)(DMSNES);
192: PetscErrorCode (*duplicate)(DMSNES,DMSNES);
193: };
195: struct _p_DMSNES {
196: PETSCHEADER(struct _DMSNESOps);
197: void *functionctx;
198: void *gsctx;
199: void *pctx;
200: void *jacobianctx;
201: void *objectivectx;
203: void *data;
205: /* This is NOT reference counted. The DM on which this context was first created is cached here to implement one-way
206: * copy-on-write. When DMGetDMSNESWrite() sees a request using a different DM, it makes a copy. Thus, if a user
207: * only interacts directly with one level, e.g., using SNESSetFunction(), then SNESSetUp_FAS() is called to build
208: * coarse levels, then the user changes the routine with another call to SNESSetFunction(), it automatically
209: * propagates to all the levels. If instead, they get out a specific level and set the function on that level,
210: * subsequent changes to the original level will no longer propagate to that level.
211: */
212: DM originaldm;
213: };
214: PETSC_EXTERN PetscErrorCode DMGetDMSNES(DM,DMSNES*);
215: PETSC_EXTERN PetscErrorCode DMSNESView(DMSNES,PetscViewer);
216: PETSC_EXTERN PetscErrorCode DMSNESLoad(DMSNES,PetscViewer);
217: PETSC_EXTERN PetscErrorCode DMGetDMSNESWrite(DM,DMSNES*);
220: /* Context for Eisenstat-Walker convergence criteria for KSP solvers */
221: typedef struct {
222: PetscInt version; /* flag indicating version 1 or 2 of test */
223: PetscReal rtol_0; /* initial rtol */
224: PetscReal rtol_last; /* last rtol */
225: PetscReal rtol_max; /* maximum rtol */
226: PetscReal gamma; /* mult. factor for version 2 rtol computation */
227: PetscReal alpha; /* power for version 2 rtol computation */
228: PetscReal alpha2; /* power for safeguard */
229: PetscReal threshold; /* threshold for imposing safeguard */
230: PetscReal lresid_last; /* linear residual from last iteration */
231: PetscReal norm_last; /* function norm from last iteration */
232: PetscReal norm_first; /* function norm from the beginning of the first iteration. */
233: } SNESKSPEW;
235: PETSC_STATIC_INLINE PetscErrorCode SNESLogConvergenceHistory(SNES snes,PetscReal res,PetscInt its)
236: {
240: PetscObjectSAWsTakeAccess((PetscObject)snes);
241: if (snes->conv_hist && snes->conv_hist_max > snes->conv_hist_len) {
242: if (snes->conv_hist) snes->conv_hist[snes->conv_hist_len] = res;
243: if (snes->conv_hist_its) snes->conv_hist_its[snes->conv_hist_len] = its;
244: snes->conv_hist_len++;
245: }
246: PetscObjectSAWsGrantAccess((PetscObject)snes);
247: return(0);
248: }
250: PETSC_EXTERN PetscErrorCode SNESVIProjectOntoBounds(SNES,Vec);
251: PETSC_INTERN PetscErrorCode SNESVICheckLocalMin_Private(SNES,Mat,Vec,Vec,PetscReal,PetscBool*);
252: PETSC_INTERN PetscErrorCode SNESReset_VI(SNES);
253: PETSC_INTERN PetscErrorCode SNESDestroy_VI(SNES);
254: PETSC_INTERN PetscErrorCode SNESView_VI(SNES,PetscViewer);
255: PETSC_INTERN PetscErrorCode SNESSetFromOptions_VI(PetscOptionItems*,SNES);
256: PETSC_INTERN PetscErrorCode SNESSetUp_VI(SNES);
257: PETSC_EXTERN_TYPEDEF typedef PetscErrorCode (*SNESVIComputeVariableBoundsFunction)(SNES,Vec,Vec);
258: PETSC_INTERN PetscErrorCode SNESVISetComputeVariableBounds_VI(SNES,SNESVIComputeVariableBoundsFunction);
259: PETSC_INTERN PetscErrorCode SNESVISetVariableBounds_VI(SNES,Vec,Vec);
260: PETSC_INTERN PetscErrorCode SNESConvergedDefault_VI(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*);
262: PetscErrorCode SNESScaleStep_Private(SNES,Vec,PetscReal*,PetscReal*,PetscReal*,PetscReal*);
263: PETSC_EXTERN PetscErrorCode DMSNESCheck_Internal(SNES,DM,Vec);
265: PETSC_EXTERN PetscLogEvent SNES_Solve;
266: PETSC_EXTERN PetscLogEvent SNES_Setup;
267: PETSC_EXTERN PetscLogEvent SNES_LineSearch;
268: PETSC_EXTERN PetscLogEvent SNES_FunctionEval;
269: PETSC_EXTERN PetscLogEvent SNES_JacobianEval;
270: PETSC_EXTERN PetscLogEvent SNES_NGSEval;
271: PETSC_EXTERN PetscLogEvent SNES_NGSFuncEval;
272: PETSC_EXTERN PetscLogEvent SNES_NPCSolve;
273: PETSC_EXTERN PetscLogEvent SNES_ObjectiveEval;
275: PETSC_INTERN PetscBool SNEScite;
276: PETSC_INTERN const char SNESCitation[];
278: /*
279: Either generate an error or mark as diverged when a real from a SNES function norm is Nan or Inf.
280: domainerror is reset here, once reason is set, to allow subsequent iterations to be feasible (e.g. line search).
281: */
282: #define SNESCheckFunctionNorm(snes,beta) do { \
283: if (PetscIsInfOrNanReal(beta)) {\
284: if (snes->errorifnotconverged) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged due to Nan or Inf norm");\
285: else {\
286: PetscBool domainerror;\
287: PetscErrorCode MPIU_Allreduce(&snes->domainerror,&domainerror,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)snes));\
288: if (domainerror) {\
289: snes->reason = SNES_DIVERGED_FUNCTION_DOMAIN;\
290: snes->domainerror = PETSC_FALSE;\
291: } else snes->reason = SNES_DIVERGED_FNORM_NAN;\
292: return(0);\
293: }\
294: } } while (0)
296: #define SNESCheckJacobianDomainerror(snes) do { \
297: if (snes->checkjacdomainerror) {\
298: PetscBool domainerror;\
299: PetscErrorCode MPIU_Allreduce(&snes->jacobiandomainerror,&domainerror,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)snes));\
300: if (domainerror) {\
301: snes->reason = SNES_DIVERGED_JACOBIAN_DOMAIN;\
302: if (snes->errorifnotconverged) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged due to Jacobian domain error");\
303: return(0);\
304: }\
305: } } while (0)
307: #define SNESCheckKSPSolve(snes)\
308: do {\
309: KSPConvergedReason kspreason; \
311: PetscInt lits; \
312: KSPGetIterationNumber(snes->ksp,&lits); \
313: snes->linear_its += lits; \
314: KSPGetConvergedReason(snes->ksp,&kspreason);\
315: if (kspreason < 0) {\
316: if (kspreason == KSP_DIVERGED_NANORINF) {\
317: PetscBool domainerror;\
318: MPIU_Allreduce(&snes->domainerror,&domainerror,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)snes));\
319: if (domainerror) snes->reason = SNES_DIVERGED_FUNCTION_DOMAIN;\
320: else snes->reason = SNES_DIVERGED_LINEAR_SOLVE; \
321: return(0);\
322: } else {\
323: if (++snes->numLinearSolveFailures >= snes->maxLinearSolveFailures) {\
324: PetscInfo3(snes,"iter=%D, number linear solve failures %D greater than current SNES allowed %D, stopping solve\n",snes->iter,snes->numLinearSolveFailures,snes->maxLinearSolveFailures);\
325: snes->reason = SNES_DIVERGED_LINEAR_SOLVE;\
326: return(0);\
327: }\
328: }\
329: }\
330: } while (0)
332: #endif