Actual source code: snesngmres.c

  1: #include <../src/snes/impls/ngmres/snesngmres.h>
  2: #include <petscblaslapack.h>
  3: #include <petscdm.h>

  5: const char *const SNESNGMRESRestartTypes[] = {"NONE", "PERIODIC", "DIFFERENCE", "SNESNGMRESRestartType", "SNES_NGMRES_RESTART_", NULL};
  6: const char *const SNESNGMRESSelectTypes[]  = {"NONE", "DIFFERENCE", "LINESEARCH", "SNESNGMRESSelectType", "SNES_NGMRES_SELECT_", NULL};

  8: PetscErrorCode SNESReset_NGMRES(SNES snes)
  9: {
 10:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

 12:   PetscFunctionBegin;
 13:   PetscCall(VecDestroyVecs(ngmres->msize, &ngmres->Fdot));
 14:   PetscCall(VecDestroyVecs(ngmres->msize, &ngmres->Xdot));
 15:   PetscCall(SNESLineSearchDestroy(&ngmres->additive_linesearch));
 16:   PetscFunctionReturn(PETSC_SUCCESS);
 17: }

 19: PetscErrorCode SNESDestroy_NGMRES(SNES snes)
 20: {
 21:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

 23:   PetscFunctionBegin;
 24:   PetscCall(SNESReset_NGMRES(snes));
 25:   PetscCall(PetscFree4(ngmres->h, ngmres->beta, ngmres->xi, ngmres->q));
 26:   PetscCall(PetscFree3(ngmres->xnorms, ngmres->fnorms, ngmres->s));
 27:   PetscCall(PetscFree3(ngmres->window, ngmres->Fwindow, ngmres->Xwindow));
 28: #if PetscDefined(USE_COMPLEX)
 29:   PetscCall(PetscFree(ngmres->rwork));
 30: #endif
 31:   PetscCall(PetscFree(ngmres->work));
 32:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetSelectType_C", NULL));
 33:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetRestartType_C", NULL));
 34:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetRestartFmRise_C", NULL));
 35:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESGetRestartFmRise_C", NULL));
 36:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetAdaptive_C", NULL));
 37:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESGetAdaptive_C", NULL));
 38:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetAdaptiveParameters_C", NULL));
 39:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESGetAdaptiveParameters_C", NULL));
 40:   PetscCall(PetscFree(snes->data));
 41:   PetscFunctionReturn(PETSC_SUCCESS);
 42: }

 44: PetscErrorCode SNESSetUp_NGMRES(SNES snes)
 45: {
 46:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;
 47:   PetscInt     msize, hsize;
 48:   DM           dm;

 50:   PetscFunctionBegin;
 51:   PetscCheck(!snes->npc || snes->npcside != PC_LEFT || snes->functype != SNES_FUNCTION_UNPRECONDITIONED, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONGSTATE, "SNESNGMRES does not support left preconditioning with unpreconditioned function");
 52:   if (snes->npcside == PC_LEFT && snes->functype == SNES_FUNCTION_DEFAULT) snes->functype = SNES_FUNCTION_PRECONDITIONED;
 53:   PetscCall(SNESSetWorkVecs(snes, 5));

 55:   if (!snes->vec_sol) {
 56:     PetscCall(SNESGetDM(snes, &dm));
 57:     PetscCall(DMCreateGlobalVector(dm, &snes->vec_sol));
 58:   }

 60:   if (!ngmres->Xdot) PetscCall(VecDuplicateVecs(snes->vec_sol, ngmres->msize, &ngmres->Xdot));
 61:   if (!ngmres->Fdot) PetscCall(VecDuplicateVecs(snes->vec_sol, ngmres->msize, &ngmres->Fdot));
 62:   if (!ngmres->setup_called) {
 63:     msize = ngmres->msize; /* restart size */
 64:     hsize = msize * msize;

 66:     /* explicit least squares minimization solve */
 67:     PetscCall(PetscCalloc4(hsize, &ngmres->h, msize, &ngmres->beta, msize, &ngmres->xi, hsize, &ngmres->q));
 68:     PetscCall(PetscMalloc3(msize, &ngmres->xnorms, msize, &ngmres->fnorms, msize, &ngmres->s));
 69:     PetscCall(PetscMalloc3(msize, &ngmres->window, msize, &ngmres->Fwindow, msize, &ngmres->Xwindow));
 70:     ngmres->nrhs = 1;
 71:     PetscCall(PetscBLASIntCast(msize, &ngmres->lda));
 72:     PetscCall(PetscBLASIntCast(msize, &ngmres->ldb));
 73:     PetscCall(PetscBLASIntCast(12 * msize, &ngmres->lwork));
 74: #if PetscDefined(USE_COMPLEX)
 75:     PetscCall(PetscMalloc1(ngmres->lwork, &ngmres->rwork));
 76: #endif
 77:     PetscCall(PetscMalloc1(ngmres->lwork, &ngmres->work));
 78:   }

 80:   ngmres->setup_called = PETSC_TRUE;
 81:   PetscFunctionReturn(PETSC_SUCCESS);
 82: }

 84: static PetscErrorCode SNESSetFromOptions_NGMRES(SNES snes, PetscOptionItems PetscOptionsObject)
 85: {
 86:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;
 87:   PetscBool    debug  = PETSC_FALSE;

 89:   PetscFunctionBegin;
 90:   PetscOptionsHeadBegin(PetscOptionsObject, "SNES NGMRES options");
 91:   PetscCall(PetscOptionsEnum("-snes_ngmres_select_type", "Select type", "SNESNGMRESSetSelectType", SNESNGMRESSelectTypes, (PetscEnum)ngmres->select_type, (PetscEnum *)&ngmres->select_type, NULL));
 92:   PetscCall(PetscOptionsEnum("-snes_ngmres_restart_type", "Restart type", "SNESNGMRESSetRestartType", SNESNGMRESRestartTypes, (PetscEnum)ngmres->restart_type, (PetscEnum *)&ngmres->restart_type, NULL));
 93:   PetscCall(PetscOptionsBool("-snes_ngmres_candidate", "Use candidate storage", "SNES", ngmres->candidate, &ngmres->candidate, NULL));
 94:   PetscCall(PetscOptionsBool("-snes_ngmres_approxfunc", "Linearly approximate the function", "SNES", ngmres->approxfunc, &ngmres->approxfunc, NULL));
 95:   PetscCall(PetscOptionsInt("-snes_ngmres_m", "Number of directions", "SNES", ngmres->msize, &ngmres->msize, NULL));
 96:   PetscCall(PetscOptionsInt("-snes_ngmres_restart", "Iterations before forced restart", "SNES", ngmres->restart_periodic, &ngmres->restart_periodic, NULL));
 97:   PetscCall(PetscOptionsInt("-snes_ngmres_restart_it", "Tolerance iterations before restart", "SNES", ngmres->restart_it, &ngmres->restart_it, NULL));
 98:   PetscCall(PetscOptionsBool("-snes_ngmres_monitor", "Monitor actions of NGMRES", "SNES", ngmres->monitor ? PETSC_TRUE : PETSC_FALSE, &debug, NULL));
 99:   if (debug) ngmres->monitor = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)snes));
100:   PetscCall(PetscOptionsReal("-snes_ngmres_gammaA", "Residual selection constant", "SNES", ngmres->gammaA, &ngmres->gammaA, NULL));
101:   PetscCall(PetscOptionsReal("-snes_ngmres_gammaC", "Residual restart constant", "SNES", ngmres->gammaC, &ngmres->gammaC, NULL));
102:   PetscCall(PetscOptionsReal("-snes_ngmres_epsilonB", "Difference selection constant", "SNES", ngmres->epsilonB, &ngmres->epsilonB, NULL));
103:   PetscCall(PetscOptionsReal("-snes_ngmres_deltaB", "Difference residual selection constant", "SNES", ngmres->deltaB, &ngmres->deltaB, NULL));
104:   PetscCall(PetscOptionsBool("-snes_ngmres_restart_fm_rise", "Restart on F_M residual rise", "SNESNGMRESSetRestartFmRise", ngmres->restart_fm_rise, &ngmres->restart_fm_rise, NULL));
105:   PetscCall(PetscOptionsBool("-snes_ngmres_adaptive", "Grow the window when theta predicts the residual reduction", "SNESNGMRESSetAdaptive", ngmres->adaptive, &ngmres->adaptive, NULL));
106:   PetscCall(PetscOptionsInt("-snes_ngmres_adaptive_m", "Initial number of stored solutions in the adaptive window", "SNESNGMRESSetAdaptiveParameters", ngmres->window_size_initial, &ngmres->window_size_initial, NULL));
107:   PetscCall(PetscOptionsReal("-snes_ngmres_adaptive_tol", "Tolerance on the prediction of the residual reduction that grows the window", "SNESNGMRESSetAdaptiveParameters", ngmres->adaptive_tol, &ngmres->adaptive_tol, NULL));
108:   PetscOptionsHeadEnd();
109:   if (ngmres->gammaA > ngmres->gammaC && ngmres->gammaC > 2.) ngmres->gammaC = ngmres->gammaA;
110:   if (ngmres->select_type == SNES_NGMRES_SELECT_LINESEARCH) {
111:     PetscCall(SNESNGMRESGetAdditiveLineSearch_Private(snes, &ngmres->additive_linesearch));
112:     PetscCall(SNESLineSearchSetFromOptions(ngmres->additive_linesearch));
113:   }
114:   PetscFunctionReturn(PETSC_SUCCESS);
115: }

117: PetscErrorCode SNESView_NGMRES(SNES snes, PetscViewer viewer)
118: {
119:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;
120:   PetscBool    isascii;

122:   PetscFunctionBegin;
123:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
124:   if (isascii) {
125:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Number of stored past updates: %" PetscInt_FMT "\n", ngmres->msize));
126:     if (ngmres->adaptive) PetscCall(PetscViewerASCIIPrintf(viewer, "  Adaptive window: initial size %" PetscInt_FMT ", tolerance %g\n", ngmres->window_size_initial, (double)ngmres->adaptive_tol));
127:     if (ngmres->select_type == SNES_NGMRES_SELECT_DIFFERENCE) {
128:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Residual selection: gammaA=%1.0e, gammaC=%1.0e\n", (double)ngmres->gammaA, (double)ngmres->gammaC));
129:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Difference restart: epsilonB=%1.0e, deltaB=%1.0e\n", (double)ngmres->epsilonB, (double)ngmres->deltaB));
130:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Restart on F_M residual increase: %s\n", PetscBools[ngmres->restart_fm_rise]));
131:     }
132:     if (ngmres->additive_linesearch) {
133:       PetscCall(PetscViewerASCIIPrintf(viewer, "  Additive line-search details:\n"));
134:       PetscCall(SNESLineSearchView(ngmres->additive_linesearch, viewer));
135:     }
136:   }
137:   PetscFunctionReturn(PETSC_SUCCESS);
138: }

140: static PetscErrorCode SNESSolve_NGMRES(SNES snes)
141: {
142:   SNES_NGMRES        *ngmres = (SNES_NGMRES *)snes->data;
143:   Vec                 X, F, B, D, Y;         /* present solution, residual, and preconditioned residual */
144:   Vec                 XA, FA, XM, FM;        /* candidate linear combination answers */
145:   PetscReal           fnorm, fMnorm, fAnorm; /* coefficients and RHS to the minimization problem */
146:   PetscReal           fnormold, ratio;       /* residual reduction for the adaptive window */
147:   PetscReal           xnorm, xMnorm, xAnorm;
148:   PetscReal           ynorm, yMnorm, yAnorm;
149:   PetscInt            k, k_restart, l, ivec, restart_count = 0;
150:   PetscReal           objmin, objM, objA, obj; /* support for objective functions minimization */
151:   PetscBool           selectRestart;           /* solution selection data */
152:   SNESConvergedReason reason;
153:   SNESObjectiveFn    *objective;
154:   /*
155:       These two variables are initialized to prevent compilers/analyzers from producing false warnings about these variables being passed
156:       to SNESNGMRESSelect_Private() without being set when SNES_NGMRES_RESTART_DIFFERENCE, the values are not used in the subroutines in that case
157:       so the code is correct as written.
158:   */
159:   PetscReal dnorm = 0.0, dminnorm = 0.0;

161:   PetscFunctionBegin;
162:   PetscCheck(!snes->xl && !snes->xu && !snes->ops->computevariablebounds, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_WRONGSTATE, "SNES solver %s does not support bounds", ((PetscObject)snes)->type_name);

164:   PetscCall(PetscCitationsRegister(SNESCitation, &SNEScite));
165:   /* variable initialization */
166:   snes->reason = SNES_CONVERGED_ITERATING;
167:   X            = snes->vec_sol;
168:   F            = snes->vec_func;
169:   B            = snes->vec_rhs;
170:   XA           = snes->work[2];
171:   FA           = snes->work[0];
172:   D            = snes->work[1];

174:   /* work for the line search */
175:   Y  = snes->vec_sol_update;
176:   XM = snes->work[3];
177:   FM = snes->work[4];

179:   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
180:   snes->iter = 0;
181:   snes->norm = 0.;
182:   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));

184:   /* initialization */

186:   if (snes->npc && snes->npcside == PC_LEFT) {
187:     PetscCall(SNESApplyNPC(snes, X, NULL, F));
188:     PetscCall(SNESGetConvergedReason(snes->npc, &reason));
189:     if (reason < 0 && reason != SNES_DIVERGED_MAX_IT) {
190:       snes->reason = SNES_DIVERGED_INNER;
191:       PetscFunctionReturn(PETSC_SUCCESS);
192:     }
193:   } else {
194:     if (!snes->vec_func_init_set) PetscCall(SNESComputeFunction(snes, X, F));
195:     else snes->vec_func_init_set = PETSC_FALSE;
196:   }
197:   PetscCall(VecNorm(F, NORM_2, &fnorm));
198:   SNESCheckFunctionDomainError(snes, fnorm);
199:   PetscCall(SNESGetObjective(snes, &objective, NULL));
200:   objmin = fnorm;
201:   if (objective) {
202:     PetscCall(SNESComputeObjective(snes, X, &objmin));
203:     SNESCheckObjectiveDomainError(snes, objmin);
204:   }
205:   obj = objmin;

207:   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
208:   snes->norm = fnorm;
209:   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
210:   PetscCall(SNESLogConvergenceHistory(snes, fnorm, 0));
211:   PetscCall(SNESConverged(snes, 0, 0.0, 0.0, fnorm));
212:   PetscCall(SNESMonitor(snes, 0, fnorm));
213:   if (snes->reason) PetscFunctionReturn(PETSC_SUCCESS);
214:   PetscCall(SNESNGMRESUpdateSubspace_Private(snes, 0, 0, F, fnorm, X));

216:   k_restart           = 1;
217:   l                   = 1;
218:   ivec                = 0;
219:   ngmres->window_size = ngmres->adaptive ? PetscMin(ngmres->window_size_initial, ngmres->msize) : ngmres->msize;
220:   for (k = 1; k < snes->max_its + 1; k++) {
221:     /* Call general purpose update function */
222:     PetscTryTypeMethod(snes, update, snes->iter);
223:     fnormold = fnorm;

225:     /* Computation of x^M */
226:     if (snes->npc && snes->npcside == PC_RIGHT) {
227:       PetscCall(VecCopy(X, XM));
228:       PetscCall(SNESSetInitialFunction(snes->npc, F));

230:       PetscCall(PetscLogEventBegin(SNES_NPCSolve, snes->npc, XM, B, 0));
231:       PetscCall(SNESSolve(snes->npc, B, XM));
232:       PetscCall(PetscLogEventEnd(SNES_NPCSolve, snes->npc, XM, B, 0));

234:       PetscCall(SNESGetConvergedReason(snes->npc, &reason));
235:       if (reason < 0 && reason != SNES_DIVERGED_MAX_IT) {
236:         snes->reason = SNES_DIVERGED_INNER;
237:         PetscFunctionReturn(PETSC_SUCCESS);
238:       }
239:       PetscCall(SNESGetNPCFunction(snes, FM, &fMnorm));
240:     } else {
241:       /* no preconditioner -- just take gradient descent with line search */
242:       PetscCall(VecCopy(F, Y));
243:       PetscCall(VecCopy(F, FM));
244:       PetscCall(VecCopy(X, XM));

246:       fMnorm = fnorm;

248:       PetscCall(SNESLineSearchApply(snes->linesearch, XM, FM, &fMnorm, Y));
249:       if (snes->reason) PetscFunctionReturn(PETSC_SUCCESS);
250:     }
251:     if (objective) {
252:       PetscCall(SNESComputeObjective(snes, XM, &objM));
253:       SNESCheckObjectiveDomainError(snes, objM);
254:     } else objM = fMnorm;
255:     objmin = PetscMin(objmin, objM);

257:     PetscCall(SNESNGMRESFormCombinedSolution_Private(snes, ivec, l, XM, FM, fMnorm, X, XA, FA));

259:     /* differences for selection and restart */
260:     if (ngmres->restart_type == SNES_NGMRES_RESTART_DIFFERENCE || ngmres->select_type == SNES_NGMRES_SELECT_DIFFERENCE) {
261:       PetscCall(SNESNGMRESNorms_Private(snes, l, X, F, XM, FM, XA, FA, D, &dnorm, &dminnorm, &xMnorm, NULL, &yMnorm, &xAnorm, &fAnorm, &yAnorm));
262:     } else {
263:       PetscCall(SNESNGMRESNorms_Private(snes, l, X, F, XM, FM, XA, FA, D, NULL, NULL, &xMnorm, NULL, &yMnorm, &xAnorm, &fAnorm, &yAnorm));
264:     }
265:     SNESCheckFunctionDomainError(snes, fnorm);
266:     if (objective) {
267:       PetscCall(SNESComputeObjective(snes, XA, &objA));
268:       SNESCheckObjectiveDomainError(snes, objA);
269:     } else objA = fAnorm;

271:     /* combination (additive) or selection (multiplicative) of the N-GMRES solution */
272:     PetscCall(SNESNGMRESSelect_Private(snes, k_restart, XM, FM, xMnorm, fMnorm, yMnorm, objM, XA, FA, xAnorm, fAnorm, yAnorm, objA, dnorm, objmin, dminnorm, X, F, Y, &xnorm, &fnorm, &ynorm));
273:     SNESCheckFunctionDomainError(snes, fnorm);
274:     if (objective) {
275:       PetscCall(SNESComputeObjective(snes, X, &obj));
276:       SNESCheckObjectiveDomainError(snes, obj);
277:     } else obj = fnorm;

279:     // grow the window when theta predicts the residual reduction, which indicates that the higher-order terms are negligible
280:     if (ngmres->adaptive) {
281:       ratio         = fnormold > 0.0 ? fnorm / fnormold : 0.0;
282:       ngmres->theta = fnormold > 0.0 ? ngmres->lsnorm / fnormold : 0.0;
283:       if (PetscAbsReal(ngmres->theta - ratio) < ngmres->adaptive_tol && ngmres->window_size < ngmres->msize) ngmres->window_size++;
284:       if (ngmres->monitor) PetscCall(PetscViewerASCIIPrintf(ngmres->monitor, "theta = %g, gamma = %g, ||F_k+1||/||F_k|| = %g, window size = %" PetscInt_FMT "\n", (double)ngmres->theta, (double)ngmres->gamma, (double)ratio, ngmres->window_size));
285:     }
286:     selectRestart = PETSC_FALSE;

288:     if (ngmres->restart_type == SNES_NGMRES_RESTART_DIFFERENCE) {
289:       PetscCall(SNESNGMRESSelectRestart_Private(snes, l, obj, objM, objA, dnorm, objmin, dminnorm, &selectRestart));

291:       /* if the restart conditions persist for more than restart_it iterations, restart. */
292:       if (selectRestart) restart_count++;
293:       else restart_count = 0;
294:     } else if (ngmres->restart_type == SNES_NGMRES_RESTART_PERIODIC) {
295:       if (k_restart > ngmres->restart_periodic) {
296:         if (ngmres->monitor) PetscCall(PetscViewerASCIIPrintf(ngmres->monitor, "periodic restart after %" PetscInt_FMT " iterations\n", k_restart));
297:         restart_count = ngmres->restart_it;
298:       }
299:     }

301:     ivec = k_restart % ngmres->msize; /* replace the last used part of the subspace */

303:     /* restart after restart conditions have persisted for a fixed number of iterations */
304:     if (restart_count >= ngmres->restart_it) {
305:       if (ngmres->monitor) PetscCall(PetscViewerASCIIPrintf(ngmres->monitor, "Restarted at iteration %" PetscInt_FMT "\n", k_restart));
306:       restart_count = 0;
307:       k_restart     = 1;
308:       l             = 1;
309:       ivec          = 0;
310:       /* q_{00} = nu */
311:       PetscCall(SNESNGMRESUpdateSubspace_Private(snes, 0, 0, FM, fMnorm, XM));
312:     } else {
313:       /* select the current size of the subspace */
314:       if (l < ngmres->window_size) l++;
315:       k_restart++;
316:       /* place the current entry in the list of previous entries */
317:       if (ngmres->candidate) {
318:         objmin = PetscMin(objmin, objM);
319:         PetscCall(SNESNGMRESUpdateSubspace_Private(snes, ivec, l, FM, fMnorm, XM));
320:       } else {
321:         objmin = PetscMin(objmin, obj);
322:         PetscCall(SNESNGMRESUpdateSubspace_Private(snes, ivec, l, F, fnorm, X));
323:       }
324:     }

326:     PetscCall(PetscObjectSAWsTakeAccess((PetscObject)snes));
327:     snes->iter  = k;
328:     snes->norm  = fnorm;
329:     snes->ynorm = ynorm;
330:     snes->xnorm = xnorm;
331:     PetscCall(PetscObjectSAWsGrantAccess((PetscObject)snes));
332:     PetscCall(SNESLogConvergenceHistory(snes, snes->norm, snes->iter));
333:     PetscCall(SNESConverged(snes, snes->iter, 0, 0, fnorm));
334:     PetscCall(SNESMonitor(snes, snes->iter, snes->norm));
335:     if (snes->reason) PetscFunctionReturn(PETSC_SUCCESS);
336:   }
337:   snes->reason = SNES_DIVERGED_MAX_IT;
338:   PetscFunctionReturn(PETSC_SUCCESS);
339: }

341: /*@
342:   SNESNGMRESSetRestartFmRise - Increase the restart count if the step x_M increases the residual F_M inside a `SNESNGMRES` solve

344:   Input Parameters:
345: + snes - the `SNES` context.
346: - flg  - boolean value deciding whether to use the option or not, default is `PETSC_FALSE`

348:   Options Database Key:
349: . -snes_ngmres_restart_fm_rise (true|false) - Increase the restart count if the step x_M increases the residual F_M

351:   Level: advanced

353:   Notes:
354:   If the proposed step x_M increases the residual F_M, it might be trying to get out of a stagnation area.
355:   To help the solver do that, remove the current stored solutions and residuals whenever F_M increases.

357:   This option must be used with the `SNESNGMRES` `SNESNGMRESRestartType` of `SNES_NGMRES_RESTART_DIFFERENCE`

359: .seealso: [](ch_snes), `SNES`, `SNES_NGMRES_RESTART_DIFFERENCE`, `SNESNGMRES`, `SNESNGMRESRestartType`, `SNESNGMRESSetRestartType()`
360:   @*/
361: PetscErrorCode SNESNGMRESSetRestartFmRise(SNES snes, PetscBool flg)
362: {
363:   PetscErrorCode (*f)(SNES, PetscBool);

365:   PetscFunctionBegin;
366:   PetscCall(PetscObjectQueryFunction((PetscObject)snes, "SNESNGMRESSetRestartFmRise_C", &f));
367:   if (f) PetscCall((f)(snes, flg));
368:   PetscFunctionReturn(PETSC_SUCCESS);
369: }

371: static PetscErrorCode SNESNGMRESSetRestartFmRise_NGMRES(SNES snes, PetscBool flg)
372: {
373:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

375:   PetscFunctionBegin;
376:   ngmres->restart_fm_rise = flg;
377:   PetscFunctionReturn(PETSC_SUCCESS);
378: }

380: /*@
381:   SNESNGMRESGetRestartFmRise - Get whether `SNESNGMRES` increases the restart count when a step $x_M$ increases the residual $F_M$

383:   Not Collective

385:   Input Parameter:
386: . snes - the `SNES` context

388:   Output Parameter:
389: . flg - `PETSC_TRUE` if the option is enabled

391:   Level: advanced

393: .seealso: [](ch_snes), `SNES`, `SNESNGMRES`, `SNESNGMRESSetRestartFmRise()`, `SNESNGMRESSetRestartType()`
394: @*/
395: PetscErrorCode SNESNGMRESGetRestartFmRise(SNES snes, PetscBool *flg)
396: {
397:   PetscErrorCode (*f)(SNES, PetscBool *);

399:   PetscFunctionBegin;
400:   PetscCall(PetscObjectQueryFunction((PetscObject)snes, "SNESNGMRESGetRestartFmRise_C", &f));
401:   if (f) PetscCall((f)(snes, flg));
402:   PetscFunctionReturn(PETSC_SUCCESS);
403: }

405: static PetscErrorCode SNESNGMRESGetRestartFmRise_NGMRES(SNES snes, PetscBool *flg)
406: {
407:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

409:   PetscFunctionBegin;
410:   *flg = ngmres->restart_fm_rise;
411:   PetscFunctionReturn(PETSC_SUCCESS);
412: }

414: /*@
415:   SNESNGMRESSetRestartType - Sets the restart type for `SNESNGMRES`.

417:   Logically Collective

419:   Input Parameters:
420: + snes  - the iterative context
421: - rtype - restart type, see `SNESNGMRESRestartType`

423:   Options Database Keys:
424: + -snes_ngmres_restart_type (difference|periodic|none) - set the restart type
425: - -snes_ngmres_restart restart                         - sets the number of iterations before restart for periodic

427:   Level: intermediate

429: .seealso: [](ch_snes), `SNES`, `SNES_NGMRES_RESTART_DIFFERENCE`, `SNESNGMRES`, `SNESNGMRESRestartType`, `SNESNGMRESSetRestartFmRise()`,
430:           `SNESNGMRESSetSelectType()`
431: @*/
432: PetscErrorCode SNESNGMRESSetRestartType(SNES snes, SNESNGMRESRestartType rtype)
433: {
434:   PetscFunctionBegin;
436:   PetscTryMethod(snes, "SNESNGMRESSetRestartType_C", (SNES, SNESNGMRESRestartType), (snes, rtype));
437:   PetscFunctionReturn(PETSC_SUCCESS);
438: }

440: /*@
441:   SNESNGMRESSetSelectType - Sets the selection type for `SNESNGMRES`.  This determines how the candidate solution and
442:   combined solution are used to create the next iterate.

444:   Logically Collective

446:   Input Parameters:
447: + snes  - the iterative context
448: - stype - selection type, see `SNESNGMRESSelectType`

450:   Options Database Key:
451: . -snes_ngmres_select_type (difference|none|linesearch) - select type

453:   Level: intermediate

455:   Note:
456:   The default line search used is the `SNESLINESEARCHSECANT` line search and it requires two additional function evaluations.

458: .seealso: [](ch_snes), `SNES`, `SNESNGMRES`, `SNESNGMRESSelectType`, `SNES_NGMRES_SELECT_NONE`, `SNES_NGMRES_SELECT_DIFFERENCE`, `SNES_NGMRES_SELECT_LINESEARCH`,
459:           `SNESNGMRESSetRestartType()`
460: @*/
461: PetscErrorCode SNESNGMRESSetSelectType(SNES snes, SNESNGMRESSelectType stype)
462: {
463:   PetscFunctionBegin;
465:   PetscTryMethod(snes, "SNESNGMRESSetSelectType_C", (SNES, SNESNGMRESSelectType), (snes, stype));
466:   PetscFunctionReturn(PETSC_SUCCESS);
467: }

469: static PetscErrorCode SNESNGMRESSetSelectType_NGMRES(SNES snes, SNESNGMRESSelectType stype)
470: {
471:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

473:   PetscFunctionBegin;
474:   ngmres->select_type = stype;
475:   PetscFunctionReturn(PETSC_SUCCESS);
476: }

478: static PetscErrorCode SNESNGMRESSetRestartType_NGMRES(SNES snes, SNESNGMRESRestartType rtype)
479: {
480:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

482:   PetscFunctionBegin;
483:   ngmres->restart_type = rtype;
484:   PetscFunctionReturn(PETSC_SUCCESS);
485: }

487: /*@
488:   SNESNGMRESSetAdaptive - Sets whether `SNESNGMRES` grows the window of stored solutions during the solve

490:   Logically Collective

492:   Input Parameters:
493: + snes - the `SNES` context
494: - flg  - `PETSC_TRUE` to grow the window adaptively

496:   Options Database Key:
497: . -snes_ngmres_adaptive (true|false) - grow the window adaptively

499:   Level: intermediate

501:   Notes:
502:   At each iteration $k$, `SNESNGMRES` combines the candidate solution $x_M$ with the stored solutions $x_j$ in a window, by minimizing
503:   the norm of the linear combination of their residuals. The ratio $\theta_{k+1}$ of the minimum to the residual norm $\| F(x_k) \|$
504:   predicts the residual reduction $\| F(x_{k+1}) \| / \| F(x_k) \|$ up to terms of higher order in the residual {cite}`he2026ngmres`.
505:   With the adaptive strategy, the window starts with a small number of stored solutions and grows by one whenever
506:   $| \theta_{k+1} - \| F(x_{k+1}) \| / \| F(x_k) \| |$ is below a tolerance, until it reaches the number set with `-snes_ngmres_m`.
507:   A small window limits the effect of the higher-order terms far from the solution, and a large window improves the rate of convergence
508:   close to the solution, where the higher-order terms are negligible.

510:   Use this strategy when a large fixed window is unreliable far from the solution but a larger history is useful near convergence.
511:   Enable it with `SNESNGMRESSetAdaptive()` or `-snes_ngmres_adaptive`, and choose the initial window size and growth tolerance
512:   with `SNESNGMRESSetAdaptiveParameters()` or `-snes_ngmres_adaptive_m` and `-snes_ngmres_adaptive_tol`.

514:   The strategy follows the algorithm of {cite}`he2026ngmres` with `SNES_NGMRES_SELECT_NONE` and `SNES_NGMRES_RESTART_NONE` or
515:   `SNES_NGMRES_RESTART_PERIODIC`.

517: .seealso: [](ch_snes), `SNES`, `SNESNGMRES`, `SNESNGMRESSetAdaptiveParameters()`, `SNESNGMRESSetSelectType()`,
518:           `SNESNGMRESSetRestartType()`
519: @*/
520: PetscErrorCode SNESNGMRESSetAdaptive(SNES snes, PetscBool flg)
521: {
522:   PetscFunctionBegin;
525:   PetscTryMethod(snes, "SNESNGMRESSetAdaptive_C", (SNES, PetscBool), (snes, flg));
526:   PetscFunctionReturn(PETSC_SUCCESS);
527: }

529: static PetscErrorCode SNESNGMRESSetAdaptive_NGMRES(SNES snes, PetscBool flg)
530: {
531:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

533:   PetscFunctionBegin;
534:   ngmres->adaptive = flg;
535:   PetscFunctionReturn(PETSC_SUCCESS);
536: }

538: /*@
539:   SNESNGMRESGetAdaptive - Gets whether `SNESNGMRES` grows the window of stored solutions during the solve

541:   Not Collective

543:   Input Parameter:
544: . snes - the `SNES` context

546:   Output Parameter:
547: . flg - `PETSC_TRUE` if the window grows adaptively

549:   Level: advanced

551: .seealso: [](ch_snes), `SNES`, `SNESNGMRES`, `SNESNGMRESSetAdaptive()`, `SNESNGMRESSetAdaptiveParameters()`
552: @*/
553: PetscErrorCode SNESNGMRESGetAdaptive(SNES snes, PetscBool *flg)
554: {
555:   PetscFunctionBegin;
557:   PetscAssertPointer(flg, 2);
558:   PetscUseMethod(snes, "SNESNGMRESGetAdaptive_C", (SNES, PetscBool *), (snes, flg));
559:   PetscFunctionReturn(PETSC_SUCCESS);
560: }

562: static PetscErrorCode SNESNGMRESGetAdaptive_NGMRES(SNES snes, PetscBool *flg)
563: {
564:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

566:   PetscFunctionBegin;
567:   *flg = ngmres->adaptive;
568:   PetscFunctionReturn(PETSC_SUCCESS);
569: }

571: /*@
572:   SNESNGMRESSetAdaptiveParameters - Sets the parameters of the adaptive window of `SNESNGMRES`

574:   Logically Collective

576:   Input Parameters:
577: + snes - the `SNES` context
578: . m    - the initial number of stored solutions in the window, or `PETSC_CURRENT` to keep the current value
579: - tol  - the tolerance on $| \theta_{k+1} - \| F(x_{k+1}) \| / \| F(x_k) \| |$ below which the window grows by one,
580:          or `PETSC_CURRENT` to keep the current value

582:   Options Database Keys:
583: + -snes_ngmres_adaptive_m m     - the initial number of stored solutions, default 4
584: - -snes_ngmres_adaptive_tol tol - the tolerance, default 1e-3

586:   Level: intermediate

588:   Note:
589:   The number of stored solutions is one more than the depth $m$ of {cite}`he2026ngmres`, so the default corresponds to the depth 3.

591: .seealso: [](ch_snes), `SNES`, `SNESNGMRES`, `SNESNGMRESSetAdaptive()`, `SNESNGMRESGetAdaptive()`
592: @*/
593: PetscErrorCode SNESNGMRESSetAdaptiveParameters(SNES snes, PetscInt m, PetscReal tol)
594: {
595:   PetscFunctionBegin;
599:   PetscTryMethod(snes, "SNESNGMRESSetAdaptiveParameters_C", (SNES, PetscInt, PetscReal), (snes, m, tol));
600:   PetscFunctionReturn(PETSC_SUCCESS);
601: }

603: static PetscErrorCode SNESNGMRESSetAdaptiveParameters_NGMRES(SNES snes, PetscInt m, PetscReal tol)
604: {
605:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

607:   PetscFunctionBegin;
608:   if (m != PETSC_CURRENT) {
609:     PetscCheck(m > 0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Initial window size %" PetscInt_FMT " must be positive", m);
610:     ngmres->window_size_initial = m;
611:   }
612:   if (tol != (PetscReal)PETSC_CURRENT) {
613:     PetscCheck(tol >= 0.0, PetscObjectComm((PetscObject)snes), PETSC_ERR_ARG_OUTOFRANGE, "Tolerance %g must be nonnegative", (double)tol);
614:     ngmres->adaptive_tol = tol;
615:   }
616:   PetscFunctionReturn(PETSC_SUCCESS);
617: }

619: /*@
620:   SNESNGMRESGetAdaptiveParameters - Gets the parameters of the adaptive window of `SNESNGMRES`

622:   Not Collective

624:   Input Parameter:
625: . snes - the `SNES` context

627:   Output Parameters:
628: + m   - the initial number of stored solutions in the window
629: - tol - the tolerance below which the window grows by one

631:   Level: advanced

633: .seealso: [](ch_snes), `SNES`, `SNESNGMRES`, `SNESNGMRESSetAdaptiveParameters()`, `SNESNGMRESSetAdaptive()`
634: @*/
635: PetscErrorCode SNESNGMRESGetAdaptiveParameters(SNES snes, PetscInt *m, PetscReal *tol)
636: {
637:   PetscFunctionBegin;
639:   if (m) PetscAssertPointer(m, 2);
640:   if (tol) PetscAssertPointer(tol, 3);
641:   PetscUseMethod(snes, "SNESNGMRESGetAdaptiveParameters_C", (SNES, PetscInt *, PetscReal *), (snes, m, tol));
642:   PetscFunctionReturn(PETSC_SUCCESS);
643: }

645: static PetscErrorCode SNESNGMRESGetAdaptiveParameters_NGMRES(SNES snes, PetscInt *m, PetscReal *tol)
646: {
647:   SNES_NGMRES *ngmres = (SNES_NGMRES *)snes->data;

649:   PetscFunctionBegin;
650:   if (m) *m = ngmres->window_size_initial;
651:   if (tol) *tol = ngmres->adaptive_tol;
652:   PetscFunctionReturn(PETSC_SUCCESS);
653: }

655: /*MC
656:   SNESNGMRES - An implementation of the Nonlinear Generalized Minimum Residual method, Nonlinear GMRES, or N-GMRES {cite}`ow1`, {cite}`bruneknepleysmithtu15` for solving
657:                nonlinear systems with `SNES`.

659:    Level: beginner

661:    Options Database Keys:
662: +  -snes_ngmres_select_type (difference|none|linesearch)             - Choose the select between candidate and combined solution
663: .  -snes_ngmres_restart_type (difference|none|periodic)              - Choose the restart conditions
664: .  -snes_ngmres_candidate (true|false)                               - Use `SNESNGMRES` variant which combines candidate solutions instead of actual solutions
665: .  -snes_ngmres_m m                                                  - Number of stored previous solutions and residuals
666: .  -snes_ngmres_restart_it it                                        - Number of iterations the restart conditions hold before restart
667: .  -snes_ngmres_gammaA gammaA                                        - Residual tolerance for solution select between the candidate and combination
668: .  -snes_ngmres_gammaC gammaB                                        - Residual tolerance for restart
669: .  -snes_ngmres_epsilonB epsilonB                                    - Difference tolerance between subsequent solutions triggering restart
670: .  -snes_ngmres_deltaB deltaB                                        - Difference tolerance between residuals triggering restart
671: .  -snes_ngmres_restart_fm_rise (true|false)                         - Restart on residual rise from $x_M$ step
672: .  -snes_ngmres_adaptive (true|false)                                - Grow the window of stored solutions when $\theta$ predicts the residual reduction, see `SNESNGMRESSetAdaptive()`
673: .  -snes_ngmres_adaptive_m m                                         - Initial number of stored solutions in the adaptive window
674: .  -snes_ngmres_adaptive_tol tol                                     - Tolerance on the prediction of the residual reduction that grows the window
675: .  -snes_ngmres_monitor (true|false)                                 - Prints relevant information about the nonlinear GNMRES iterations
676: .  -snes_linesearch_type (none|bt|secant|cp|nleqerr|bisection|shell) - Line search type used for the default smoother, see `SNESLineSearchType`
677: -  -snes_ngmres_additive_snes_linesearch_type type                   - Line search type used to select between the candidate and combined solution with additive select type, see `SNESLineSearchType`

679:    Notes:
680:    The N-GMRES method combines m previous solutions into a minimum-residual solution by solving a small linearized
681:    optimization problem at each iteration.

683:    Very similar to the `SNESANDERSON` algorithm.

685:    Unlike the linear GMRES algorithm this algorithm does not compute a Krylov subspace using the Arnoldi process. Instead it stores a
686:    collection of previous solutions and the residuals $F(x) - b$ at those solutions.

688:    This algorithm ignores any Jacobian provided with `SNESSetJacobian()`

690:    Only supports left non-linear preconditioning.

692: .seealso: [](ch_snes), `SNESCreate()`, `SNES`, `SNESSetType()`, `SNESType`, `SNESANDERSON`, `SNESNGMRESSetSelectType()`, `SNESNGMRESSetRestartType()`,
693:           `SNESNGMRESSetRestartFmRise()`, `SNESNGMRESSelectType`, `SNESNGMRESRestartType`
694: M*/

696: PETSC_EXTERN PetscErrorCode SNESCreate_NGMRES(SNES snes)
697: {
698:   SNES_NGMRES   *ngmres;
699:   SNESLineSearch linesearch;

701:   PetscFunctionBegin;
702:   snes->ops->destroy        = SNESDestroy_NGMRES;
703:   snes->ops->setup          = SNESSetUp_NGMRES;
704:   snes->ops->setfromoptions = SNESSetFromOptions_NGMRES;
705:   snes->ops->view           = SNESView_NGMRES;
706:   snes->ops->solve          = SNESSolve_NGMRES;
707:   snes->ops->reset          = SNESReset_NGMRES;

709:   snes->usesnpc = PETSC_TRUE;
710:   snes->usesksp = PETSC_FALSE;
711:   snes->npcside = PC_RIGHT;

713:   snes->alwayscomputesfinalresidual = PETSC_TRUE;

715:   PetscObjectParameterSetDefault(snes, max_funcs, 30000);
716:   PetscObjectParameterSetDefault(snes, max_its, 10000);

718:   PetscCall(SNESGetLineSearch(snes, &linesearch));
719:   if (!((PetscObject)linesearch)->type_name) PetscCall(SNESLineSearchSetType(linesearch, SNESLINESEARCHNONE));

721:   PetscCall(PetscNew(&ngmres));
722:   snes->data = (void *)ngmres;

724:   ngmres->msize            = 30;
725:   ngmres->restart_it       = 2;
726:   ngmres->restart_periodic = 30;
727:   ngmres->gammaA           = 2.0;
728:   ngmres->gammaC           = 2.0;
729:   ngmres->deltaB           = 0.9;
730:   ngmres->epsilonB         = 0.1;
731:   ngmres->restart_type     = SNES_NGMRES_RESTART_DIFFERENCE;
732:   ngmres->select_type      = SNES_NGMRES_SELECT_DIFFERENCE;

734:   ngmres->window_size_initial = 4;
735:   ngmres->adaptive_tol        = 1.e-3;

737:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetSelectType_C", SNESNGMRESSetSelectType_NGMRES));
738:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetRestartType_C", SNESNGMRESSetRestartType_NGMRES));
739:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetRestartFmRise_C", SNESNGMRESSetRestartFmRise_NGMRES));
740:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESGetRestartFmRise_C", SNESNGMRESGetRestartFmRise_NGMRES));
741:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetAdaptive_C", SNESNGMRESSetAdaptive_NGMRES));
742:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESGetAdaptive_C", SNESNGMRESGetAdaptive_NGMRES));
743:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESSetAdaptiveParameters_C", SNESNGMRESSetAdaptiveParameters_NGMRES));
744:   PetscCall(PetscObjectComposeFunction((PetscObject)snes, "SNESNGMRESGetAdaptiveParameters_C", SNESNGMRESGetAdaptiveParameters_NGMRES));
745:   PetscFunctionReturn(PETSC_SUCCESS);
746: }