Actual source code: fgmres.c

  1: /*
  2:     This file implements FGMRES (a Generalized Minimal Residual) method.
  3:     Reference:  Saad, 1993.

  5:     Preconditioning:  If the preconditioner is constant then this fgmres
  6:     code is equivalent to RIGHT-PRECONDITIONED GMRES.
  7:     FGMRES is a modification of gmres that allows the preconditioner to change
  8:     at each iteration.

 10:     Restarts:  Restarts are basically solves with x0 not equal to zero.
 11: */

 13: #include <../src/ksp/ksp/impls/gmres/fgmres/fgmresimpl.h>
 14: #define FGMRES_DELTA_DIRECTIONS 10
 15: #define FGMRES_DEFAULT_MAXK     30
 16: static PetscErrorCode KSPFGMRESGetNewVectors(KSP, PetscInt);
 17: static PetscErrorCode KSPFGMRESUpdateHessenberg(KSP, PetscInt, PetscBool, PetscReal *);
 18: static PetscErrorCode KSPFGMRESBuildSoln(PetscScalar *, Vec, Vec, KSP, PetscInt);

 20: static PetscErrorCode KSPSetUp_FGMRES(KSP ksp)
 21: {
 22:   PetscInt    max_k;
 23:   KSP_FGMRES *fgmres = (KSP_FGMRES *)ksp->data;

 25:   PetscFunctionBegin;
 26:   max_k = fgmres->max_k;

 28:   PetscCall(KSPSetUp_GMRES(ksp));

 30:   PetscCall(PetscMalloc1(max_k + 2, &fgmres->prevecs));
 31:   PetscCall(PetscMalloc1(max_k + 2, &fgmres->prevecs_user_work));

 33:   /* fgmres->vv_allocated includes extra work vectors, which are not used in the additional
 34:      block of vectors used to store the preconditioned directions, hence  the -VEC_OFFSET
 35:      term for this first allocation of vectors holding preconditioned directions */
 36:   PetscCall(KSPCreateVecs(ksp, fgmres->vv_allocated - VEC_OFFSET, &fgmres->prevecs_user_work[0], 0, NULL));
 37:   for (PetscInt k = 0; k < fgmres->vv_allocated - VEC_OFFSET; k++) fgmres->prevecs[k] = fgmres->prevecs_user_work[0][k];
 38:   PetscFunctionReturn(PETSC_SUCCESS);
 39: }

 41: static PetscErrorCode KSPFGMRESResidual(KSP ksp)
 42: {
 43:   KSP_FGMRES *fgmres = (KSP_FGMRES *)ksp->data;
 44:   Mat         Amat, Pmat;

 46:   PetscFunctionBegin;
 47:   PetscCall(PCGetOperators(ksp->pc, &Amat, &Pmat));

 49:   /* put A*x into VEC_TEMP */
 50:   PetscCall(KSP_MatMult(ksp, Amat, ksp->vec_sol, VEC_TEMP));
 51:   /* now put residual (-A*x + f) into vec_vv(0) */
 52:   PetscCall(VecWAXPY(VEC_VV(0), -1.0, VEC_TEMP, ksp->vec_rhs));
 53:   PetscFunctionReturn(PETSC_SUCCESS);
 54: }

 56: static PetscErrorCode KSPFGMRESCycle(PetscInt *itcount, KSP ksp)
 57: {
 58:   KSP_FGMRES *fgmres = (KSP_FGMRES *)ksp->data;
 59:   PetscReal   res_norm;
 60:   PetscReal   hapbnd, tt;
 61:   PetscBool   hapend = PETSC_FALSE;  /* indicates happy breakdown ending */
 62:   PetscInt    loc_it;                /* local count of # of dir. in Krylov space */
 63:   PetscInt    max_k = fgmres->max_k; /* max # of directions Krylov space */
 64:   Mat         Amat, Pmat;

 66:   PetscFunctionBegin;
 67:   /* Number of pseudo iterations since last restart is the number
 68:      of prestart directions */
 69:   loc_it = 0;

 71:   /* note: (fgmres->it) is always set one less than (loc_it) It is used in
 72:      KSPBUILDSolution_FGMRES, where it is passed to KSPFGMRESBuildSoln.
 73:      Note that when KSPFGMRESBuildSoln is called from this function,
 74:      (loc_it -1) is passed, so the two are equivalent */
 75:   fgmres->it = (loc_it - 1);

 77:   /* initial residual is in VEC_VV(0)  - compute its norm*/
 78:   PetscCall(VecNorm(VEC_VV(0), NORM_2, &res_norm));
 79:   KSPCheckNorm(ksp, res_norm);

 81:   /* The first entry in the right-hand side of the Hessenberg system is just
 82:      the initial residual norm */
 83:   *RS(0) = res_norm;

 85:   ksp->rnorm = res_norm;
 86:   PetscCall(KSPLogResidualHistory(ksp, res_norm));
 87:   PetscCall(KSPMonitor(ksp, ksp->its, res_norm));

 89:   /* check for the convergence - maybe the current guess is good enough */
 90:   PetscCall((*ksp->converged)(ksp, ksp->its, res_norm, &ksp->reason, ksp->cnvP));
 91:   if (ksp->reason) {
 92:     if (itcount) *itcount = 0;
 93:     PetscFunctionReturn(PETSC_SUCCESS);
 94:   }

 96:   /* scale VEC_VV (the initial residual) */
 97:   PetscCall(VecScale(VEC_VV(0), 1.0 / res_norm));

 99:   /* MAIN ITERATION LOOP BEGINNING*/
100:   /* keep iterating until we have converged OR generated the max number
101:      of directions OR reached the max number of iterations for the method */
102:   while (!ksp->reason && loc_it < max_k && ksp->its < ksp->max_it) {
103:     if (loc_it) {
104:       PetscCall(KSPLogResidualHistory(ksp, res_norm));
105:       PetscCall(KSPMonitor(ksp, ksp->its, res_norm));
106:     }
107:     fgmres->it = (loc_it - 1);

109:     /* see if more space is needed for work vectors */
110:     if (fgmres->vv_allocated <= loc_it + VEC_OFFSET + 1) {
111:       PetscCall(KSPFGMRESGetNewVectors(ksp, loc_it + 1));
112:       /* (loc_it+1) is passed in as number of the first vector that should
113:          be allocated */
114:     }

116:     /* CHANGE THE PRECONDITIONER? */
117:     /* ModifyPC is the callback function that can be used to
118:        change the PC or its attributes before its applied */
119:     PetscCall((*fgmres->modifypc)(ksp, ksp->its, loc_it, res_norm, fgmres->modifyctx));

121:     /* apply PRECONDITIONER to direction vector and store with
122:        preconditioned vectors in prevec */
123:     PetscCall(KSP_PCApply(ksp, VEC_VV(loc_it), PREVEC(loc_it)));

125:     PetscCall(PCGetOperators(ksp->pc, &Amat, &Pmat));
126:     /* Multiply preconditioned vector by operator - put in VEC_VV(loc_it+1) */
127:     PetscCall(KSP_MatMult(ksp, Amat, PREVEC(loc_it), VEC_VV(1 + loc_it)));

129:     /* update Hessenberg matrix and do Gram-Schmidt - new direction is in
130:        VEC_VV(1+loc_it)*/
131:     PetscCall((*ksp->orthog)(ksp, &VEC_VV(0), loc_it + 1, NULL, HH(0, loc_it)));
132:     PetscCall(PetscArraycpy(HES(0, loc_it), HH(0, loc_it), loc_it + 1));

134:     /* new entry in Hessenberg is the 2-norm of our new direction */
135:     PetscCall(VecNorm(VEC_VV(loc_it + 1), NORM_2, &tt));
136:     KSPCheckNorm(ksp, tt);

138:     *HH(loc_it + 1, loc_it)  = tt;
139:     *HES(loc_it + 1, loc_it) = tt;

141:     /* Happy Breakdown Check */
142:     hapbnd = PetscAbsScalar((tt) / *RS(loc_it));
143:     /* RS(loc_it) contains the res_norm from the last iteration  */
144:     hapbnd = PetscMin(fgmres->haptol, hapbnd);
145:     if (tt > hapbnd) {
146:       /* scale new direction by its norm */
147:       PetscCall(VecScale(VEC_VV(loc_it + 1), 1.0 / tt));
148:     } else {
149:       /* This happens when the solution is exactly reached. */
150:       /* So there is no new direction... */
151:       PetscCall(VecSet(VEC_TEMP, 0.0)); /* set VEC_TEMP to 0 */
152:       hapend = PETSC_TRUE;
153:     }
154:     /* note that for FGMRES we could get HES(loc_it+1, loc_it)  = 0 and the
155:        current solution would not be exact if HES was singular.  Note that
156:        HH non-singular implies that HES is no singular, and HES is guaranteed
157:        to be nonsingular when PREVECS are linearly independent and A is
158:        nonsingular (in GMRES, the nonsingularity of A implies the nonsingularity
159:        of HES). So we should really add a check to verify that HES is nonsingular.*/

161:     /* Now apply rotations to the new column of Hessenberg (and the right-hand side of the system),
162:        calculate new rotation, and get new residual norm at the same time*/
163:     PetscCall(KSPFGMRESUpdateHessenberg(ksp, loc_it, hapend, &res_norm));
164:     if (ksp->reason) break;

166:     loc_it++;
167:     fgmres->it = (loc_it - 1); /* Add this here in case it has converged */

169:     PetscCall(PetscObjectSAWsTakeAccess((PetscObject)ksp));
170:     ksp->its++;
171:     ksp->rnorm = res_norm;
172:     PetscCall(PetscObjectSAWsGrantAccess((PetscObject)ksp));

174:     PetscCall((*ksp->converged)(ksp, ksp->its, res_norm, &ksp->reason, ksp->cnvP));

176:     /* Catch error in happy breakdown and signal convergence and break from loop */
177:     if (hapend) {
178:       if (!ksp->reason) {
179:         PetscCheck(!ksp->errorifnotconverged, PetscObjectComm((PetscObject)ksp), PETSC_ERR_NOT_CONVERGED, "Reached happy break down, but convergence was not indicated. Residual norm = %g", (double)res_norm);
180:         ksp->reason = KSP_DIVERGED_BREAKDOWN;
181:         break;
182:       }
183:     }
184:   }
185:   /* END OF ITERATION LOOP */

187:   if (itcount) *itcount = loc_it;

189:   /*
190:     Down here we have to solve for the "best" coefficients of the Krylov
191:     columns, add the solution values together, and possibly unwind the
192:     preconditioning from the solution
193:    */

195:   /* Form the solution (or the solution so far) */
196:   /* Note: must pass in (loc_it-1) for iteration count so that KSPFGMRESBuildSoln
197:      properly navigates */

199:   PetscCall(KSPFGMRESBuildSoln(RS(0), ksp->vec_sol, ksp->vec_sol, ksp, loc_it - 1));

201:   /*  Monitor if we know that we will not return for a restart */
202:   if (ksp->reason == KSP_CONVERGED_ITERATING && ksp->its >= ksp->max_it) ksp->reason = KSP_DIVERGED_ITS;
203:   if (loc_it && ksp->reason) {
204:     PetscCall(KSPMonitor(ksp, ksp->its, res_norm));
205:     PetscCall(KSPLogResidualHistory(ksp, res_norm));
206:   }
207:   PetscFunctionReturn(PETSC_SUCCESS);
208: }

210: static PetscErrorCode KSPSolve_FGMRES(KSP ksp)
211: {
212:   PetscInt    cycle_its = 0; /* iterations done in a call to KSPFGMRESCycle */
213:   KSP_FGMRES *fgmres    = (KSP_FGMRES *)ksp->data;

215:   PetscFunctionBegin;
216:   PetscCall(PetscObjectSAWsTakeAccess((PetscObject)ksp));
217:   ksp->its = 0;
218:   PetscCall(PetscObjectSAWsGrantAccess((PetscObject)ksp));

220:   /* Compute the initial (NOT preconditioned) residual */
221:   if (!ksp->guess_zero) {
222:     PetscCall(KSPFGMRESResidual(ksp));
223:   } else { /* guess is 0 so residual is F (which is in ksp->vec_rhs) */
224:     PetscCall(VecCopy(ksp->vec_rhs, VEC_VV(0)));
225:   }
226:   /* This may be true only on a subset of MPI ranks; setting it here so it will be detected by the first norm computation in the Krylov method */
227:   PetscCall(VecFlag(VEC_VV(0), ksp->reason == KSP_DIVERGED_PC_FAILED));

229:   /* now the residual is in VEC_VV(0) - which is what
230:      KSPFGMRESCycle expects... */

232:   PetscCall(KSPFGMRESCycle(&cycle_its, ksp));
233:   while (!ksp->reason) {
234:     PetscCall(KSPFGMRESResidual(ksp));
235:     if (ksp->its >= ksp->max_it) break;
236:     PetscCall(KSPFGMRESCycle(&cycle_its, ksp));
237:   }
238:   /* mark lack of convergence */
239:   if (ksp->its >= ksp->max_it && !ksp->reason) ksp->reason = KSP_DIVERGED_ITS;
240:   PetscFunctionReturn(PETSC_SUCCESS);
241: }

243: extern PetscErrorCode KSPReset_FGMRES(KSP);

245: static PetscErrorCode KSPDestroy_FGMRES(KSP ksp)
246: {
247:   PetscFunctionBegin;
248:   PetscCall(KSPReset_FGMRES(ksp));
249:   PetscCall(PetscObjectComposeFunction((PetscObject)ksp, "KSPFlexibleSetModifyPC_C", NULL));
250:   PetscCall(KSPDestroy_GMRES(ksp));
251:   PetscFunctionReturn(PETSC_SUCCESS);
252: }

254: static PetscErrorCode KSPFGMRESBuildSoln(PetscScalar *nrs, Vec vguess, Vec vdest, KSP ksp, PetscInt it)
255: {
256:   PetscScalar tt;
257:   PetscInt    ii, k, j;
258:   KSP_FGMRES *fgmres = (KSP_FGMRES *)ksp->data;

260:   PetscFunctionBegin;
261:   /* Solve for solution vector that minimizes the residual */

263:   /* If it is < 0, no fgmres steps have been performed */
264:   if (it < 0) {
265:     PetscCall(VecCopy(vguess, vdest)); /* VecCopy() is smart, exists immediately if vguess == vdest */
266:     PetscFunctionReturn(PETSC_SUCCESS);
267:   }

269:   /* so fgmres steps HAVE been performed */

271:   /* solve the upper triangular system - RS is the right side and HH is
272:      the upper triangular matrix  - put soln in nrs */
273:   if (*HH(it, it) != 0.0) {
274:     nrs[it] = *RS(it) / *HH(it, it);
275:   } else {
276:     nrs[it] = 0.0;
277:   }
278:   for (ii = 1; ii <= it; ii++) {
279:     k  = it - ii;
280:     tt = *RS(k);
281:     for (j = k + 1; j <= it; j++) tt = tt - *HH(k, j) * nrs[j];
282:     nrs[k] = tt / *HH(k, k);
283:   }

285:   /* Accumulate the correction to the soln of the preconditioned prob. in
286:      VEC_TEMP - note that we use the preconditioned vectors  */
287:   PetscCall(VecMAXPBY(VEC_TEMP, it + 1, nrs, 0, &PREVEC(0)));

289:   /* put updated solution into vdest.*/
290:   if (vdest != vguess) {
291:     PetscCall(VecCopy(VEC_TEMP, vdest));
292:     PetscCall(VecAXPY(vdest, 1.0, vguess));
293:   } else { /* replace guess with solution */
294:     PetscCall(VecAXPY(vdest, 1.0, VEC_TEMP));
295:   }
296:   PetscFunctionReturn(PETSC_SUCCESS);
297: }

299: static PetscErrorCode KSPFGMRESUpdateHessenberg(KSP ksp, PetscInt it, PetscBool hapend, PetscReal *res)
300: {
301:   PetscScalar *hh, *cc, *ss, tt;
302:   KSP_FGMRES  *fgmres = (KSP_FGMRES *)ksp->data;

304:   PetscFunctionBegin;
305:   hh = HH(0, it); /* pointer to beginning of column to update - so
306:                       incrementing hh "steps down" the (it+1)th col of HH*/
307:   cc = CC(0);     /* beginning of cosine rotations */
308:   ss = SS(0);     /* beginning of sine rotations */

310:   /* Apply all the previously computed plane rotations to the new column
311:      of the Hessenberg matrix */
312:   /* Note: this uses the rotation [conj(c)  s ; -s   c], c= cos(theta), s= sin(theta),
313:      and some refs have [c   s ; -conj(s)  c] (don't be confused!) */

315:   for (PetscInt j = 1; j <= it; j++) {
316:     tt  = *hh;
317:     *hh = PetscConj(*cc) * tt + *ss * *(hh + 1);
318:     hh++;
319:     *hh = *cc++ * *hh - (*ss++ * tt);
320:     /* hh, cc, and ss have all been incremented one by end of loop */
321:   }

323:   /*
324:     compute the new plane rotation, and apply it to:
325:      1) the right-hand side of the Hessenberg system (RS)
326:         note: it affects RS(it) and RS(it+1)
327:      2) the new column of the Hessenberg matrix
328:         note: it affects HH(it,it) which is currently pointed to
329:         by hh and HH(it+1, it) (*(hh+1))
330:     thus obtaining the updated value of the residual...
331:   */

333:   /* compute new plane rotation */

335:   if (!hapend) {
336:     tt = PetscSqrtScalar(PetscConj(*hh) * *hh + PetscConj(*(hh + 1)) * *(hh + 1));
337:     if (tt == 0.0) {
338:       ksp->reason = KSP_DIVERGED_NULL;
339:       PetscFunctionReturn(PETSC_SUCCESS);
340:     }

342:     *cc = *hh / tt;       /* new cosine value */
343:     *ss = *(hh + 1) / tt; /* new sine value */

345:     /* apply to 1) and 2) */
346:     *RS(it + 1) = -(*ss * *RS(it));
347:     *RS(it)     = PetscConj(*cc) * *RS(it);
348:     *hh         = PetscConj(*cc) * *hh + *ss * *(hh + 1);

350:     /* residual is the last element (it+1) of right-hand side! */
351:     *res = PetscAbsScalar(*RS(it + 1));

353:   } else { /* happy breakdown: HH(it+1, it) = 0, therefore we don't need to apply
354:             another rotation matrix (so RH doesn't change).  The new residual is
355:             always the new sine term times the residual from last time (RS(it)),
356:             but now the new sine rotation would be zero...so the residual should
357:             be zero...so we will multiply "zero" by the last residual.  This might
358:             not be exactly what we want to do here -could just return "zero". */

360:     *res = 0.0;
361:   }
362:   PetscFunctionReturn(PETSC_SUCCESS);
363: }

365: static PetscErrorCode KSPFGMRESGetNewVectors(KSP ksp, PetscInt it)
366: {
367:   KSP_FGMRES *fgmres = (KSP_FGMRES *)ksp->data;
368:   PetscInt    nwork  = fgmres->nwork_alloc; /* number of work vector chunks allocated */
369:   PetscInt    nalloc;                       /* number to allocate */

371:   PetscFunctionBegin;
372:   nalloc = fgmres->delta_allocate; /* number of vectors to allocate
373:                                       in a single chunk */

375:   /* Adjust the number to allocate to make sure that we don't exceed the
376:      number of available slots (fgmres->vecs_allocated)*/
377:   if (it + VEC_OFFSET + nalloc >= fgmres->vecs_allocated) nalloc = fgmres->vecs_allocated - it - VEC_OFFSET;
378:   if (!nalloc) PetscFunctionReturn(PETSC_SUCCESS);

380:   fgmres->vv_allocated += nalloc; /* vv_allocated is the number of vectors allocated */

382:   /* work vectors */
383:   PetscCall(KSPCreateVecs(ksp, nalloc, &fgmres->user_work[nwork], 0, NULL));
384:   for (PetscInt k = 0; k < nalloc; k++) fgmres->vecs[it + VEC_OFFSET + k] = fgmres->user_work[nwork][k];
385:   /* specify size of chunk allocated */
386:   fgmres->mwork_alloc[nwork] = nalloc;

388:   /* preconditioned vectors */
389:   PetscCall(KSPCreateVecs(ksp, nalloc, &fgmres->prevecs_user_work[nwork], 0, NULL));
390:   for (PetscInt k = 0; k < nalloc; k++) fgmres->prevecs[it + k] = fgmres->prevecs_user_work[nwork][k];

392:   /* increment the number of work vector chunks */
393:   fgmres->nwork_alloc++;
394:   PetscFunctionReturn(PETSC_SUCCESS);
395: }

397: static PetscErrorCode KSPBuildSolution_FGMRES(KSP ksp, Vec ptr, Vec *result)
398: {
399:   KSP_FGMRES *fgmres = (KSP_FGMRES *)ksp->data;

401:   PetscFunctionBegin;
402:   if (!ptr) {
403:     if (!fgmres->sol_temp) PetscCall(VecDuplicate(ksp->vec_sol, &fgmres->sol_temp));
404:     ptr = fgmres->sol_temp;
405:   }
406:   if (!fgmres->nrs) {
407:     /* allocate the work area */
408:     PetscCall(PetscMalloc1(fgmres->max_k, &fgmres->nrs));
409:   }

411:   PetscCall(KSPFGMRESBuildSoln(fgmres->nrs, ksp->vec_sol, ptr, ksp, fgmres->it));
412:   if (result) *result = ptr;
413:   PetscFunctionReturn(PETSC_SUCCESS);
414: }

416: static PetscErrorCode KSPSetFromOptions_FGMRES(KSP ksp, PetscOptionItems PetscOptionsObject)
417: {
418:   PetscBool flg;

420:   PetscFunctionBegin;
421:   PetscCall(KSPSetFromOptions_GMRES(ksp, PetscOptionsObject));
422:   PetscOptionsHeadBegin(PetscOptionsObject, "KSP flexible GMRES Options");
423:   PetscCall(PetscOptionsBoolGroupBegin("-ksp_fgmres_modifypcnochange", "do not vary the preconditioner", "KSPFlexibleSetModifyPC", &flg));
424:   if (flg) PetscCall(KSPFlexibleSetModifyPC(ksp, KSPFlexibleModifyPCNoChange, NULL, NULL));
425:   PetscCall(PetscOptionsBoolGroupEnd("-ksp_fgmres_modifypcksp", "vary the KSP based preconditioner", "KSPFlexibleSetModifyPC", &flg));
426:   if (flg) PetscCall(KSPFlexibleSetModifyPC(ksp, KSPFlexibleModifyPCKSP, NULL, NULL));
427:   PetscOptionsHeadEnd();
428:   PetscFunctionReturn(PETSC_SUCCESS);
429: }

431: static PetscErrorCode KSPFlexibleSetModifyPC_FGMRES(KSP ksp, KSPFlexibleModifyPCFn *fcn, PetscCtx ctx, PetscCtxDestroyFn *d)
432: {
433:   PetscFunctionBegin;
435:   ((KSP_FGMRES *)ksp->data)->modifypc      = fcn;
436:   ((KSP_FGMRES *)ksp->data)->modifydestroy = d;
437:   ((KSP_FGMRES *)ksp->data)->modifyctx     = ctx;
438:   PetscFunctionReturn(PETSC_SUCCESS);
439: }

441: PetscErrorCode KSPReset_FGMRES(KSP ksp)
442: {
443:   KSP_FGMRES *fgmres = (KSP_FGMRES *)ksp->data;
444:   PetscInt    i;

446:   PetscFunctionBegin;
447:   PetscCall(PetscFree(fgmres->prevecs));
448:   if (fgmres->nwork_alloc > 0) {
449:     i = 0;
450:     /* In the first allocation we allocated VEC_OFFSET fewer vectors in prevecs */
451:     PetscCall(VecDestroyVecs(fgmres->mwork_alloc[i] - VEC_OFFSET, &fgmres->prevecs_user_work[i]));
452:     for (i = 1; i < fgmres->nwork_alloc; i++) PetscCall(VecDestroyVecs(fgmres->mwork_alloc[i], &fgmres->prevecs_user_work[i]));
453:   }
454:   PetscCall(PetscFree(fgmres->prevecs_user_work));
455:   if (fgmres->modifydestroy) PetscCall((*fgmres->modifydestroy)(&fgmres->modifyctx));
456:   PetscCall(KSPReset_GMRES(ksp));
457:   PetscFunctionReturn(PETSC_SUCCESS);
458: }

460: static PetscErrorCode KSPGMRESSetRestart_FGMRES(KSP ksp, PetscInt max_k)
461: {
462:   KSP_FGMRES *gmres = (KSP_FGMRES *)ksp->data;

464:   PetscFunctionBegin;
465:   PetscCheck(max_k >= 1, PetscObjectComm((PetscObject)ksp), PETSC_ERR_ARG_OUTOFRANGE, "Restart must be positive");
466:   if (!ksp->setupstage) {
467:     gmres->max_k = max_k;
468:   } else if (gmres->max_k != max_k) {
469:     gmres->max_k    = max_k;
470:     ksp->setupstage = KSP_SETUP_NEW;
471:     /* free the data structures, then create them again */
472:     PetscCall(KSPReset_FGMRES(ksp));
473:   }
474:   PetscFunctionReturn(PETSC_SUCCESS);
475: }

477: static PetscErrorCode KSPGMRESGetRestart_FGMRES(KSP ksp, PetscInt *max_k)
478: {
479:   KSP_FGMRES *gmres = (KSP_FGMRES *)ksp->data;

481:   PetscFunctionBegin;
482:   *max_k = gmres->max_k;
483:   PetscFunctionReturn(PETSC_SUCCESS);
484: }

486: /*MC
487:    KSPFGMRES - Implements the Flexible Generalized Minimal Residual method, flexible GMRES. [](sec_flexibleksp)

489:    Options Database Keys:
490: +   -ksp_gmres_restart restart                                                  - the number of Krylov directions to orthogonalize against
491: .   -ksp_gmres_haptol tol                                                       - sets the tolerance for "happy breakdown" (exact convergence)
492: .   -ksp_gmres_preallocate                                                      - preallocate all the Krylov search directions initially (otherwise groups of vectors are allocated as needed)
493: .   -ksp_gmres_krylov_monitor                                                   - plot the Krylov space generated
494: .   -ksp_fgmres_modifypcnochange                                                - do not change the preconditioner between iterations
495: -   -ksp_fgmres_modifypcksp                                                     - modify the preconditioner using `KSPFlexibleModifyPCKSP()`

497:    Level: beginner

499:    Notes:
500:    See `KSPFlexibleSetModifyPC()` for how to vary the preconditioner between iterations

502:    GMRES requires that the preconditioner used is a linear operator. Flexible GMRES allows the preconditioner to be a nonlinear operator. This
503:    allows, for example, Flexible GMRES to use GMRES solvers or other Krylov solvers (which are nonlinear operators in general) inside the preconditioner
504:    used by `KSPFGMRES`. For example, the options `-ksp_type fgmres -pc_type ksp -ksp_ksp_type bcgs -ksp_view -ksp_pc_type jacobi` make the preconditioner
505:    (or inner solver) be bi-CG-stab with a preconditioner of `PCJACOBI`. `KSPFCG` provides a flexible version of the preconditioned conjugate gradient method.

507:    Only right preconditioning is supported.

509:    The following options `-ksp_type fgmres -pc_type ksp -ksp_ksp_type bcgs -ksp_view -ksp_pc_type jacobi` make the preconditioner (or inner solver)
510:    be bi-CG-stab with a preconditioner of `PCJACOBI`

512:    Developer Note:
513:    This object is subclassed off of `KSPGMRES`, see the source code in src/ksp/ksp/impls/gmres for comments on the structure of the code

515:    Contributed by:
516:    Allison Baker

518: .seealso: [](ch_ksp), [](sec_flexibleksp), `KSPCreate()`, `KSPSetType()`, `KSPType`, `KSP`, `KSPGMRES`, `KSPLGMRES`, `KSPFCG`,
519:           `KSPGMRESSetRestart()`, `KSPGMRESSetHapTol()`, `KSPGMRESSetPreAllocateVectors()`, `KSPOrthogonalizationSet()`, `KSPOrthogonalizationGet()`,
520:           `KSPOrthogonalizationClassicalGramSchmidt()`, `KSPOrthogonalizationModifiedGramSchmidt()`,
521:           `KSPOrthogonalizationCGSRefinementType`, `KSPOrthogonalizationSetCGSRefinementType()`, `KSPOrthogonalizationGetCGSRefinementType()`, `KSPGMRESMonitorKrylov()`, `KSPFlexibleSetModifyPC()`,
522:           `KSPFlexibleModifyPCKSP()`
523: M*/

525: PETSC_EXTERN PetscErrorCode KSPCreate_FGMRES(KSP ksp)
526: {
527:   KSP_FGMRES *fgmres;

529:   PetscFunctionBegin;
530:   PetscCall(PetscNew(&fgmres));

532:   ksp->data                              = (void *)fgmres;
533:   ksp->ops->buildsolution                = KSPBuildSolution_FGMRES;
534:   ksp->ops->setup                        = KSPSetUp_FGMRES;
535:   ksp->ops->solve                        = KSPSolve_FGMRES;
536:   ksp->ops->reset                        = KSPReset_FGMRES;
537:   ksp->ops->destroy                      = KSPDestroy_FGMRES;
538:   ksp->ops->view                         = KSPView_GMRES;
539:   ksp->ops->setfromoptions               = KSPSetFromOptions_FGMRES;
540:   ksp->ops->computeextremesingularvalues = KSPComputeExtremeSingularValues_GMRES;
541:   ksp->ops->computeeigenvalues           = KSPComputeEigenvalues_GMRES;

543:   PetscCall(KSPSetSupportedNorm(ksp, KSP_NORM_UNPRECONDITIONED, PC_RIGHT, 3));
544:   PetscCall(KSPSetSupportedNorm(ksp, KSP_NORM_NONE, PC_RIGHT, 1));

546:   PetscCall(PetscObjectComposeFunction((PetscObject)ksp, "KSPGMRESSetPreAllocateVectors_C", KSPGMRESSetPreAllocateVectors_GMRES));
547:   PetscCall(PetscObjectComposeFunction((PetscObject)ksp, "KSPGMRESSetRestart_C", KSPGMRESSetRestart_FGMRES));
548:   PetscCall(PetscObjectComposeFunction((PetscObject)ksp, "KSPGMRESGetRestart_C", KSPGMRESGetRestart_FGMRES));
549:   PetscCall(PetscObjectComposeFunction((PetscObject)ksp, "KSPFlexibleSetModifyPC_C", KSPFlexibleSetModifyPC_FGMRES));

551:   fgmres->haptol         = 1.0e-30;
552:   fgmres->q_preallocate  = PETSC_FALSE;
553:   fgmres->delta_allocate = FGMRES_DELTA_DIRECTIONS;
554:   fgmres->nrs            = NULL;
555:   fgmres->sol_temp       = NULL;
556:   fgmres->max_k          = FGMRES_DEFAULT_MAXK;
557:   fgmres->Rsvd           = NULL;
558:   fgmres->modifypc       = KSPFlexibleModifyPCNoChange;
559:   fgmres->modifyctx      = NULL;
560:   fgmres->modifydestroy  = NULL;
561:   PetscFunctionReturn(PETSC_SUCCESS);
562: }