Actual source code: snesimpl.h
petsc-3.10.5 2019-03-28
Report Typos and Errors

      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

     37: struct _p_SNES {
     38:   PETSCHEADER(struct _SNESOps);
     39:   DM        dm;
     40:   PetscBool dmAuto;             /* SNES created currently used DM automatically */
     41:   SNES      npc;
     42:   PCSide    npcside;
     43:   PetscBool usesnpc;            /* type can use a nonlinear preconditioner */

     45:   /*  ------------------------ User-provided stuff -------------------------------*/
     46:   void  *user;                   /* user-defined context */

     48:   Vec  vec_rhs;                  /* If non-null, solve F(x) = rhs */
     49:   Vec  vec_sol;                  /* pointer to solution */

     51:   Vec  vec_func;                 /* pointer to function */

     53:   Mat  jacobian;                 /* Jacobian matrix */
     54:   Mat  jacobian_pre;             /* preconditioner matrix */
     55:   void *initialguessP;           /* user-defined initial guess context */
     56:   KSP  ksp;                      /* linear solver context */
     57:   SNESLineSearch linesearch;     /* line search context */
     58:   PetscBool usesksp;
     59:   MatStructure matstruct;        /* Used by Picard solver */

     61:   Vec  vec_sol_update;           /* pointer to solution update */

     63:   Vec  scaling;                  /* scaling vector */
     64:   void *scaP;                    /* scaling context */

     66:   PetscReal precheck_picard_angle; /* For use with SNESLineSearchPreCheckPicard */

     68:   /* ------------------------Time stepping hooks-----------------------------------*/

     70:   /* ---------------- PETSc-provided (or user-provided) stuff ---------------------*/

     72:   PetscErrorCode      (*monitor[MAXSNESMONITORS])(SNES,PetscInt,PetscReal,void*); /* monitor routine */
     73:   PetscErrorCode      (*monitordestroy[MAXSNESMONITORS])(void**);                 /* monitor context destroy routine */
     74:   void                *monitorcontext[MAXSNESMONITORS];                           /* monitor context */
     75:   PetscInt            numbermonitors;                                             /* number of monitors */
     76:   void                *cnvP;                                                      /* convergence context */
     77:   SNESConvergedReason reason;
     78:   PetscBool           errorifnotconverged;

     80:   /* --- Routines and data that are unique to each particular solver --- */

     82:   PetscBool      setupcalled;                /* true if setup has been called */
     83:   void           *data;                      /* implementation-specific data */

     85:   /* --------------------------  Parameters -------------------------------------- */

     87:   PetscInt    max_its;            /* max number of iterations */
     88:   PetscInt    max_funcs;          /* max number of function evals */
     89:   PetscInt    nfuncs;             /* number of function evaluations */
     90:   PetscInt    iter;               /* global iteration number */
     91:   PetscInt    linear_its;         /* total number of linear solver iterations */
     92:   PetscReal   norm;               /* residual norm of current iterate */
     93:   PetscReal   rtol;               /* relative tolerance */
     94:   PetscReal   divtol;             /* relative divergence tolerance */
     95:   PetscReal   abstol;             /* absolute tolerance */
     96:   PetscReal   stol;               /* step length tolerance*/
     97:   PetscReal   deltatol;           /* trust region convergence tolerance */
     98:   PetscBool   forceiteration;     /* Force SNES to take at least one iteration regardless of the initial residual norm */
     99:   PetscInt    lagpreconditioner;  /* SNESSetLagPreconditioner() */
    100:   PetscInt    lagjacobian;        /* SNESSetLagJacobian() */
    101:   PetscInt    jac_iter;           /* The present iteration of the Jacobian lagging */
    102:   PetscBool   lagjac_persist;     /* The jac_iter persists until reset */
    103:   PetscInt    pre_iter;           /* The present iteration of the Preconditioner lagging */
    104:   PetscBool   lagpre_persist;     /* The pre_iter persists until reset */
    105:   PetscInt    gridsequence;       /* number of grid sequence steps to take; defaults to zero */

    107:   PetscBool   tolerancesset;      /* SNESSetTolerances() called and tolerances should persist through SNESCreate_XXX()*/

    109:   PetscBool   vec_func_init_set;  /* the initial function has been set */

    111:   SNESNormSchedule normschedule;  /* Norm computation type for SNES instance */
    112:   SNESFunctionType functype;      /* Function type for the SNES instance */

    114:   /* ------------------------ Default work-area management ---------------------- */

    116:   PetscInt    nwork;
    117:   Vec         *work;

    119:   /* ------------------------- Miscellaneous Information ------------------------ */

    121:   PetscInt    setfromoptionscalled;
    122:   PetscReal   *conv_hist;         /* If !0, stores function norm (or
    123:                                     gradient norm) at each iteration */
    124:   PetscInt    *conv_hist_its;     /* linear iterations for each Newton step */
    125:   PetscInt    conv_hist_len;      /* size of convergence history array */
    126:   PetscInt    conv_hist_max;      /* actual amount of data in conv_history */
    127:   PetscBool   conv_hist_reset;    /* reset counter for each new SNES solve */
    128:   PetscBool   conv_malloc;

    130:   PetscBool    counters_reset;    /* reset counter for each new SNES solve */

    132:   /* the next two are used for failures in the line search; they should be put elsewhere */
    133:   PetscInt    numFailures;        /* number of unsuccessful step attempts */
    134:   PetscInt    maxFailures;        /* maximum number of unsuccessful step attempts */

    136:   PetscInt    numLinearSolveFailures;
    137:   PetscInt    maxLinearSolveFailures;

    139:   PetscBool   domainerror;       /* set with SNESSetFunctionDomainError() */

    141:   PetscBool   ksp_ewconv;        /* flag indicating use of Eisenstat-Walker KSP convergence criteria */
    142:   void        *kspconvctx;       /* Eisenstat-Walker KSP convergence context */

    144:   /* SNESConvergedDefault context: split it off into a separate var/struct to be passed as context to SNESConvergedDefault? */
    145:   PetscReal   ttol;              /* rtol*initial_residual_norm */
    146:   PetscReal   rnorm0;            /* initial residual norm (used for divergence testing) */

    148:   Vec         *vwork;            /* more work vectors for Jacobian approx */
    149:   PetscInt    nvwork;

    151:   PetscBool   mf;               /* -snes_mf was used on this snes */
    152:   PetscBool   mf_operator;      /* -snes_mf_operator was used on this snes */
    153:   PetscInt    mf_version;       /* The version of snes_mf used */

    155:   PetscReal   vizerotolerance;   /* tolerance for considering an x[] value to be on the bound */
    156:   Vec         xl,xu;             /* upper and lower bounds for box constrained VI problems */
    157:   PetscInt    ntruebounds;       /* number of non-infinite bounds set for VI box constraints */
    158:   PetscBool   usersetbounds;     /* bounds have been set via SNESVISetVariableBounds(), rather than via computevariablebounds() callback. */

    160:   PetscBool   alwayscomputesfinalresidual;  /* Does SNESSolve_XXX always compute the value of the residual at the final
    161:                                              * solution and put it in vec_func?  Used inside SNESSolve_FAS to determine
    162:                                              * if the final residual must be computed before restricting or prolonging
    163:                                              * it. */

    165: };

    167: typedef struct _p_DMSNES *DMSNES;
    168: typedef struct _DMSNESOps *DMSNESOps;
    169: struct _DMSNESOps {
    170:   PetscErrorCode (*computefunction)(SNES,Vec,Vec,void*);
    171:   PetscErrorCode (*computejacobian)(SNES,Vec,Mat,Mat,void*);

    173:   /* objective */
    174:   PetscErrorCode (*computeobjective)(SNES,Vec,PetscReal*,void*);

    176:   /* Picard iteration functions */
    177:   PetscErrorCode (*computepfunction)(SNES,Vec,Vec,void*);
    178:   PetscErrorCode (*computepjacobian)(SNES,Vec,Mat,Mat,void*);

    180:   /* User-defined smoother */
    181:   PetscErrorCode (*computegs)(SNES,Vec,Vec,void*);

    183:   PetscErrorCode (*destroy)(DMSNES);
    184:   PetscErrorCode (*duplicate)(DMSNES,DMSNES);
    185: };

    187: struct _p_DMSNES {
    188:   PETSCHEADER(struct _DMSNESOps);
    189:   void *functionctx;
    190:   void *gsctx;
    191:   void *pctx;
    192:   void *jacobianctx;
    193:   void *objectivectx;

    195:   void *data;

    197:   /* This is NOT reference counted. The DM on which this context was first created is cached here to implement one-way
    198:    * copy-on-write. When DMGetDMSNESWrite() sees a request using a different DM, it makes a copy. Thus, if a user
    199:    * only interacts directly with one level, e.g., using SNESSetFunction(), then SNESSetUp_FAS() is called to build
    200:    * coarse levels, then the user changes the routine with another call to SNESSetFunction(), it automatically
    201:    * propagates to all the levels. If instead, they get out a specific level and set the function on that level,
    202:    * subsequent changes to the original level will no longer propagate to that level.
    203:    */
    204:   DM originaldm;
    205: };
    206: PETSC_EXTERN PetscErrorCode DMGetDMSNES(DM,DMSNES*);
    207: PETSC_EXTERN PetscErrorCode DMSNESView(DMSNES,PetscViewer);
    208: PETSC_EXTERN PetscErrorCode DMSNESLoad(DMSNES,PetscViewer);
    209: PETSC_EXTERN PetscErrorCode DMGetDMSNESWrite(DM,DMSNES*);

    212: /* Context for Eisenstat-Walker convergence criteria for KSP solvers */
    213: typedef struct {
    214:   PetscInt  version;             /* flag indicating version 1 or 2 of test */
    215:   PetscReal rtol_0;              /* initial rtol */
    216:   PetscReal rtol_last;           /* last rtol */
    217:   PetscReal rtol_max;            /* maximum rtol */
    218:   PetscReal gamma;               /* mult. factor for version 2 rtol computation */
    219:   PetscReal alpha;               /* power for version 2 rtol computation */
    220:   PetscReal alpha2;              /* power for safeguard */
    221:   PetscReal threshold;           /* threshold for imposing safeguard */
    222:   PetscReal lresid_last;         /* linear residual from last iteration */
    223:   PetscReal norm_last;           /* function norm from last iteration */
    224:   PetscReal norm_first;          /* function norm from the beginning of the first iteration. */
    225: } SNESKSPEW;

    227: PETSC_STATIC_INLINE PetscErrorCode SNESLogConvergenceHistory(SNES snes,PetscReal res,PetscInt its)
    228: {

    232:   PetscObjectSAWsTakeAccess((PetscObject)snes);
    233:   if (snes->conv_hist && snes->conv_hist_max > snes->conv_hist_len) {
    234:     if (snes->conv_hist)     snes->conv_hist[snes->conv_hist_len]     = res;
    235:     if (snes->conv_hist_its) snes->conv_hist_its[snes->conv_hist_len] = its;
    236:     snes->conv_hist_len++;
    237:   }
    238:   PetscObjectSAWsGrantAccess((PetscObject)snes);
    239:   return(0);
    240: }

    242: PETSC_EXTERN PetscErrorCode SNESVIProjectOntoBounds(SNES,Vec);
    243: PETSC_INTERN PetscErrorCode SNESVICheckLocalMin_Private(SNES,Mat,Vec,Vec,PetscReal,PetscBool*);
    244: PETSC_INTERN PetscErrorCode SNESReset_VI(SNES);
    245: PETSC_INTERN PetscErrorCode SNESDestroy_VI(SNES);
    246: PETSC_INTERN PetscErrorCode SNESView_VI(SNES,PetscViewer);
    247: PETSC_INTERN PetscErrorCode SNESSetFromOptions_VI(PetscOptionItems*,SNES);
    248: PETSC_INTERN PetscErrorCode SNESSetUp_VI(SNES);
    249: PETSC_EXTERN_TYPEDEF typedef PetscErrorCode (*SNESVIComputeVariableBoundsFunction)(SNES,Vec,Vec);
    250: PETSC_INTERN PetscErrorCode SNESVISetComputeVariableBounds_VI(SNES,SNESVIComputeVariableBoundsFunction);
    251: PETSC_INTERN PetscErrorCode SNESVISetVariableBounds_VI(SNES,Vec,Vec);
    252: PETSC_INTERN PetscErrorCode SNESConvergedDefault_VI(SNES,PetscInt,PetscReal,PetscReal,PetscReal,SNESConvergedReason*,void*);

    254: PetscErrorCode SNESScaleStep_Private(SNES,Vec,PetscReal*,PetscReal*,PetscReal*,PetscReal*);
    255: PETSC_EXTERN PetscErrorCode DMSNESCheckFromOptions_Internal(SNES,DM,Vec,PetscErrorCode (**)(PetscInt,PetscReal,const PetscReal[],PetscInt,PetscScalar*,void*),void**);

    257: PETSC_EXTERN PetscLogEvent SNES_Solve;
    258: PETSC_EXTERN PetscLogEvent SNES_LineSearch;
    259: PETSC_EXTERN PetscLogEvent SNES_FunctionEval;
    260: PETSC_EXTERN PetscLogEvent SNES_JacobianEval;
    261: PETSC_EXTERN PetscLogEvent SNES_NGSEval;
    262: PETSC_EXTERN PetscLogEvent SNES_NGSFuncEval;
    263: PETSC_EXTERN PetscLogEvent SNES_NPCSolve;
    264: PETSC_EXTERN PetscLogEvent SNES_ObjectiveEval;

    266: PETSC_INTERN PetscBool SNEScite;
    267: PETSC_INTERN const char SNESCitation[];

    269: /*
    270:     Either generate an error or mark as diverged when a real from a SNES function norm is Nan or Inf
    271: */
    272: #define SNESCheckFunctionNorm(snes,beta) \
    273:   if (PetscIsInfOrNanReal(beta)) {\
    274:     if (snes->errorifnotconverged) SETERRQ(PetscObjectComm((PetscObject)snes),PETSC_ERR_NOT_CONVERGED,"SNESSolve has not converged due to Nan or Inf norm");\
    275:     else {\
    276:       PetscBool domainerror;\
    277:       PetscErrorCode MPIU_Allreduce((int*)&snes->domainerror,(int*)&domainerror,1,MPI_INT,MPI_MAX,PetscObjectComm((PetscObject)snes));\
    278:       if (domainerror)  snes->reason = SNES_DIVERGED_FUNCTION_DOMAIN;\
    279:       else              snes->reason = SNES_DIVERGED_FNORM_NAN;\
    280:       return(0);\
    281:     }\
    282:   }

    284: #define SNESCheckKSPSolve(snes)\
    285:   {\
    286:     KSPConvergedReason kspreason; \
    288:     PetscInt lits;                                                      \
    289:     KSPGetIterationNumber(snes->ksp,&lits);        \
    290:     snes->linear_its += lits;                                           \
    291:     KSPGetConvergedReason(snes->ksp,&kspreason);\
    292:     if (kspreason < 0) {\
    293:       if (kspreason == KSP_DIVERGED_NANORINF) {\
    294:         PetscBool domainerror;\
    295:         MPIU_Allreduce((int*)&snes->domainerror,(int*)&domainerror,1,MPI_INT,MPI_MAX,PetscObjectComm((PetscObject)snes)); \
    296:         if (domainerror)  snes->reason = SNES_DIVERGED_FUNCTION_DOMAIN;\
    297:         else              snes->reason = SNES_DIVERGED_LINEAR_SOLVE;                  \
    298:         return(0);\
    299:       } else {\
    300:         if (++snes->numLinearSolveFailures >= snes->maxLinearSolveFailures) {\
    301:           PetscInfo2(snes,"iter=%D, number linear solve failures %D greater than current SNES allowed, stopping solve\n",snes->iter,snes->numLinearSolveFailures);\
    302:           snes->reason = SNES_DIVERGED_LINEAR_SOLVE;\
    303:           return(0);\
    304:         }\
    305:       }\
    306:     }\
    307:   }

    309: #endif