Date: 2015-10-02T22:21:15+00:00

Actual source code: fgmres.c
petsc-3.6.2 2015-10-02
Report Typos and Errors

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

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

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

     13:        Contributed by Allison Baker

     15: */

     17: #include <../src/ksp/ksp/impls/gmres/fgmres/fgmresimpl.h>       /*I  "petscksp.h"  I*/
     18: #define FGMRES_DELTA_DIRECTIONS 10
     19: #define FGMRES_DEFAULT_MAXK     30
     20: static PetscErrorCode KSPFGMRESGetNewVectors(KSP,PetscInt);
     21: static PetscErrorCode KSPFGMRESUpdateHessenberg(KSP,PetscInt,PetscBool,PetscReal*);
     22: static PetscErrorCode KSPFGMRESBuildSoln(PetscScalar*,Vec,Vec,KSP,PetscInt);

     24: /*

     26:     KSPSetUp_FGMRES - Sets up the workspace needed by fgmres.

     28:     This is called once, usually automatically by KSPSolve() or KSPSetUp(),
     29:     but can be called directly by KSPSetUp().

     31: */
     34: PetscErrorCode    KSPSetUp_FGMRES(KSP ksp)
     35: {
     37:   PetscInt       max_k,k;
     38:   KSP_FGMRES     *fgmres = (KSP_FGMRES*)ksp->data;

     41:   max_k = fgmres->max_k;

     43:   KSPSetUp_GMRES(ksp);

     45:   PetscMalloc1(VEC_OFFSET+2+max_k,&fgmres->prevecs);
     46:   PetscMalloc1(VEC_OFFSET+2+max_k,&fgmres->prevecs_user_work);
     47:   PetscLogObjectMemory((PetscObject)ksp,(VEC_OFFSET+2+max_k)*(2*sizeof(void*)));

     49:   KSPCreateVecs(ksp,fgmres->vv_allocated,&fgmres->prevecs_user_work[0],0,NULL);
     50:   PetscLogObjectParents(ksp,fgmres->vv_allocated,fgmres->prevecs_user_work[0]);
     51:   for (k=0; k < fgmres->vv_allocated; k++) {
     52:     fgmres->prevecs[k] = fgmres->prevecs_user_work[0][k];
     53:   }
     54:   return(0);
     55: }

     57: /*
     58:     KSPFGMRESResidual - This routine computes the initial residual (NOT PRECONDITIONED)
     59: */
     62: static PetscErrorCode KSPFGMRESResidual(KSP ksp)
     63: {
     64:   KSP_FGMRES     *fgmres = (KSP_FGMRES*)(ksp->data);
     65:   Mat            Amat,Pmat;

     69:   PCGetOperators(ksp->pc,&Amat,&Pmat);

     71:   /* put A*x into VEC_TEMP */
     72:   KSP_MatMult(ksp,Amat,ksp->vec_sol,VEC_TEMP);
     73:   /* now put residual (-A*x + f) into vec_vv(0) */
     74:   VecWAXPY(VEC_VV(0),-1.0,VEC_TEMP,ksp->vec_rhs);
     75:   return(0);
     76: }

     78: /*

     80:     KSPFGMRESCycle - Run fgmres, possibly with restart.  Return residual
     81:                   history if requested.

     83:     input parameters:
     84: .        fgmres  - structure containing parameters and work areas

     86:     output parameters:
     87: .        itcount - number of iterations used.  If null, ignored.
     88: .        converged - 0 if not converged

     91:     Notes:
     92:     On entry, the value in vector VEC_VV(0) should be
     93:     the initial residual.

     96:  */
     99: PetscErrorCode KSPFGMRESCycle(PetscInt *itcount,KSP ksp)
    100: {

    102:   KSP_FGMRES     *fgmres = (KSP_FGMRES*)(ksp->data);
    103:   PetscReal      res_norm;
    104:   PetscReal      hapbnd,tt;
    105:   PetscBool      hapend = PETSC_FALSE;  /* indicates happy breakdown ending */
    107:   PetscInt       loc_it;                /* local count of # of dir. in Krylov space */
    108:   PetscInt       max_k = fgmres->max_k; /* max # of directions Krylov space */
    109:   Mat            Amat,Pmat;

    112:   /* Number of pseudo iterations since last restart is the number
    113:      of prestart directions */
    114:   loc_it = 0;

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

    122:   /* initial residual is in VEC_VV(0)  - compute its norm*/
    123:   VecNorm(VEC_VV(0),NORM_2,&res_norm);

    125:   /* first entry in right-hand-side of hessenberg system is just
    126:      the initial residual norm */
    127:   *RS(0) = res_norm;

    129:   ksp->rnorm = res_norm;
    130:   KSPLogResidualHistory(ksp,res_norm);
    131:   KSPMonitor(ksp,ksp->its,res_norm);

    133:   /* check for the convergence - maybe the current guess is good enough */
    134:   (*ksp->converged)(ksp,ksp->its,res_norm,&ksp->reason,ksp->cnvP);
    135:   if (ksp->reason) {
    136:     if (itcount) *itcount = 0;
    137:     return(0);
    138:   }

    140:   /* scale VEC_VV (the initial residual) */
    141:   VecScale(VEC_VV(0),1.0/res_norm);

    143:   /* MAIN ITERATION LOOP BEGINNING*/
    144:   /* keep iterating until we have converged OR generated the max number
    145:      of directions OR reached the max number of iterations for the method */
    146:   while (!ksp->reason && loc_it < max_k && ksp->its < ksp->max_it) {
    147:     if (loc_it) {
    148:       KSPLogResidualHistory(ksp,res_norm);
    149:       KSPMonitor(ksp,ksp->its,res_norm);
    150:     }
    151:     fgmres->it = (loc_it - 1);

    153:     /* see if more space is needed for work vectors */
    154:     if (fgmres->vv_allocated <= loc_it + VEC_OFFSET + 1) {
    155:       KSPFGMRESGetNewVectors(ksp,loc_it+1);
    156:       /* (loc_it+1) is passed in as number of the first vector that should
    157:          be allocated */
    158:     }

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

    166:     /* apply PRECONDITIONER to direction vector and store with
    167:        preconditioned vectors in prevec */
    168:     KSP_PCApply(ksp,VEC_VV(loc_it),PREVEC(loc_it));

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

    175:     /* update hessenberg matrix and do Gram-Schmidt - new direction is in
    176:        VEC_VV(1+loc_it)*/
    177:     (*fgmres->orthog)(ksp,loc_it);

    179:     /* new entry in hessenburg is the 2-norm of our new direction */
    180:     VecNorm(VEC_VV(loc_it+1),NORM_2,&tt);

    182:     *HH(loc_it+1,loc_it)  = tt;
    183:     *HES(loc_it+1,loc_it) = tt;

    185:     /* Happy Breakdown Check */
    186:     hapbnd = PetscAbsScalar((tt) / *RS(loc_it));
    187:     /* RS(loc_it) contains the res_norm from the last iteration  */
    188:     hapbnd = PetscMin(fgmres->haptol,hapbnd);
    189:     if (tt > hapbnd) {
    190:       /* scale new direction by its norm */
    191:       VecScale(VEC_VV(loc_it+1),1.0/tt);
    192:     } else {
    193:       /* This happens when the solution is exactly reached. */
    194:       /* So there is no new direction... */
    195:       VecSet(VEC_TEMP,0.0);     /* set VEC_TEMP to 0 */
    196:       hapend = PETSC_TRUE;
    197:     }
    198:     /* note that for FGMRES we could get HES(loc_it+1, loc_it)  = 0 and the
    199:        current solution would not be exact if HES was singular.  Note that
    200:        HH non-singular implies that HES is no singular, and HES is guaranteed
    201:        to be nonsingular when PREVECS are linearly independent and A is
    202:        nonsingular (in GMRES, the nonsingularity of A implies the nonsingularity
    203:        of HES). So we should really add a check to verify that HES is nonsingular.*/

    206:     /* Now apply rotations to new col of hessenberg (and right side of system),
    207:        calculate new rotation, and get new residual norm at the same time*/
    208:     KSPFGMRESUpdateHessenberg(ksp,loc_it,hapend,&res_norm);
    209:     if (ksp->reason) break;

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

    214:     PetscObjectSAWsTakeAccess((PetscObject)ksp);
    215:     ksp->its++;
    216:     ksp->rnorm = res_norm;
    217:     PetscObjectSAWsGrantAccess((PetscObject)ksp);

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

    221:     /* Catch error in happy breakdown and signal convergence and break from loop */
    222:     if (hapend) {
    223:       if (!ksp->reason) {
    224:         if (ksp->errorifnotconverged) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_NOT_CONVERGED,"You reached the happy break down, but convergence was not indicated. Residual norm = %g",(double)res_norm);
    225:         else {
    226:           ksp->reason = KSP_DIVERGED_BREAKDOWN;
    227:           break;
    228:         }
    229:       }
    230:     }
    231:   }
    232:   /* END OF ITERATION LOOP */
    233:   KSPLogResidualHistory(ksp,res_norm);

    235:   /*
    236:      Monitor if we know that we will not return for a restart */
    237:   if (loc_it && (ksp->reason || ksp->its >= ksp->max_it)) {
    238:     KSPMonitor(ksp,ksp->its,res_norm);
    239:   }

    241:   if (itcount) *itcount = loc_it;

    243:   /*
    244:     Down here we have to solve for the "best" coefficients of the Krylov
    245:     columns, add the solution values together, and possibly unwind the
    246:     preconditioning from the solution
    247:    */

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

    253:   KSPFGMRESBuildSoln(RS(0),ksp->vec_sol,ksp->vec_sol,ksp,loc_it-1);
    254:   return(0);
    255: }

    257: /*
    258:     KSPSolve_FGMRES - This routine applies the FGMRES method.

    261:    Input Parameter:
    262: .     ksp - the Krylov space object that was set to use fgmres

    264:    Output Parameter:
    265: .     outits - number of iterations used

    267: */

    271: PetscErrorCode KSPSolve_FGMRES(KSP ksp)
    272: {
    274:   PetscInt       cycle_its = 0; /* iterations done in a call to KSPFGMRESCycle */
    275:   KSP_FGMRES     *fgmres   = (KSP_FGMRES*)ksp->data;
    276:   PetscBool      diagonalscale;

    279:   PCGetDiagonalScale(ksp->pc,&diagonalscale);
    280:   if (diagonalscale) SETERRQ1(PetscObjectComm((PetscObject)ksp),PETSC_ERR_SUP,"Krylov method %s does not support diagonal scaling",((PetscObject)ksp)->type_name);

    282:   PetscObjectSAWsTakeAccess((PetscObject)ksp);
    283:   ksp->its = 0;
    284:   PetscObjectSAWsGrantAccess((PetscObject)ksp);

    286:   /* Compute the initial (NOT preconditioned) residual */
    287:   if (!ksp->guess_zero) {
    288:     KSPFGMRESResidual(ksp);
    289:   } else { /* guess is 0 so residual is F (which is in ksp->vec_rhs) */
    290:     VecCopy(ksp->vec_rhs,VEC_VV(0));
    291:   }
    292:   /* now the residual is in VEC_VV(0) - which is what
    293:      KSPFGMRESCycle expects... */

    295:   KSPFGMRESCycle(&cycle_its,ksp);
    296:   while (!ksp->reason) {
    297:     KSPFGMRESResidual(ksp);
    298:     if (ksp->its >= ksp->max_it) break;
    299:     KSPFGMRESCycle(&cycle_its,ksp);
    300:   }
    301:   /* mark lack of convergence */
    302:   if (ksp->its >= ksp->max_it && !ksp->reason) ksp->reason = KSP_DIVERGED_ITS;
    303:   return(0);
    304: }

    306: extern PetscErrorCode KSPReset_FGMRES(KSP);
    307: /*

    309:    KSPDestroy_FGMRES - Frees all memory space used by the Krylov method.

    311: */
    314: PetscErrorCode KSPDestroy_FGMRES(KSP ksp)
    315: {

    319:   KSPReset_FGMRES(ksp);
    320:   PetscObjectComposeFunction((PetscObject)ksp,"KSPFGMRESSetModifyPC_C",NULL);
    321:   KSPDestroy_GMRES(ksp);
    322:   return(0);
    323: }

    325: /*
    326:     KSPFGMRESBuildSoln - create the solution from the starting vector and the
    327:                       current iterates.

    329:     Input parameters:
    330:         nrs - work area of size it + 1.
    331:         vguess  - index of initial guess
    332:         vdest - index of result.  Note that vguess may == vdest (replace
    333:                 guess with the solution).
    334:         it - HH upper triangular part is a block of size (it+1) x (it+1)

    336:      This is an internal routine that knows about the FGMRES internals.
    337:  */
    340: static PetscErrorCode KSPFGMRESBuildSoln(PetscScalar *nrs,Vec vguess,Vec vdest,KSP ksp,PetscInt it)
    341: {
    342:   PetscScalar    tt;
    344:   PetscInt       ii,k,j;
    345:   KSP_FGMRES     *fgmres = (KSP_FGMRES*)(ksp->data);

    348:   /* Solve for solution vector that minimizes the residual */

    350:   /* If it is < 0, no fgmres steps have been performed */
    351:   if (it < 0) {
    352:     VecCopy(vguess,vdest); /* VecCopy() is smart, exists immediately if vguess == vdest */
    353:     return(0);
    354:   }

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

    358:   /* solve the upper triangular system - RS is the right side and HH is
    359:      the upper triangular matrix  - put soln in nrs */
    360:   if (*HH(it,it) != 0.0) {
    361:     nrs[it] = *RS(it) / *HH(it,it);
    362:   } else {
    363:     nrs[it] = 0.0;
    364:   }
    365:   for (ii=1; ii<=it; ii++) {
    366:     k  = it - ii;
    367:     tt = *RS(k);
    368:     for (j=k+1; j<=it; j++) tt = tt - *HH(k,j) * nrs[j];
    369:     nrs[k] = tt / *HH(k,k);
    370:   }

    372:   /* Accumulate the correction to the soln of the preconditioned prob. in
    373:      VEC_TEMP - note that we use the preconditioned vectors  */
    374:   VecSet(VEC_TEMP,0.0); /* set VEC_TEMP components to 0 */
    375:   VecMAXPY(VEC_TEMP,it+1,nrs,&PREVEC(0));

    377:   /* put updated solution into vdest.*/
    378:   if (vdest != vguess) {
    379:     VecCopy(VEC_TEMP,vdest);
    380:     VecAXPY(vdest,1.0,vguess);
    381:   } else { /* replace guess with solution */
    382:     VecAXPY(vdest,1.0,VEC_TEMP);
    383:   }
    384:   return(0);
    385: }

    387: /*

    389:     KSPFGMRESUpdateHessenberg - Do the scalar work for the orthogonalization.
    390:                             Return new residual.

    392:     input parameters:

    394: .        ksp -    Krylov space object
    395: .        it  -    plane rotations are applied to the (it+1)th column of the
    396:                   modified hessenberg (i.e. HH(:,it))
    397: .        hapend - PETSC_FALSE not happy breakdown ending.

    399:     output parameters:
    400: .        res - the new residual

    402:  */
    405: static PetscErrorCode KSPFGMRESUpdateHessenberg(KSP ksp,PetscInt it,PetscBool hapend,PetscReal *res)
    406: {
    407:   PetscScalar *hh,*cc,*ss,tt;
    408:   PetscInt    j;
    409:   KSP_FGMRES  *fgmres = (KSP_FGMRES*)(ksp->data);

    412:   hh = HH(0,it);   /* pointer to beginning of column to update - so
    413:                       incrementing hh "steps down" the (it+1)th col of HH*/
    414:   cc = CC(0);      /* beginning of cosine rotations */
    415:   ss = SS(0);      /* beginning of sine rotations */

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

    422:   for (j=1; j<=it; j++) {
    423:     tt  = *hh;
    424:     *hh = PetscConj(*cc) * tt + *ss * *(hh+1);
    425:     hh++;
    426:     *hh = *cc++ * *hh - (*ss++ * tt);
    427:     /* hh, cc, and ss have all been incremented one by end of loop */
    428:   }

    430:   /*
    431:     compute the new plane rotation, and apply it to:
    432:      1) the right-hand-side of the Hessenberg system (RS)
    433:         note: it affects RS(it) and RS(it+1)
    434:      2) the new column of the Hessenberg matrix
    435:         note: it affects HH(it,it) which is currently pointed to
    436:         by hh and HH(it+1, it) (*(hh+1))
    437:     thus obtaining the updated value of the residual...
    438:   */

    440:   /* compute new plane rotation */

    442:   if (!hapend) {
    443:     tt = PetscSqrtScalar(PetscConj(*hh) * *hh + PetscConj(*(hh+1)) * *(hh+1));
    444:     if (tt == 0.0) {
    445:       ksp->reason = KSP_DIVERGED_NULL;
    446:       return(0);
    447:     }

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

    452:     /* apply to 1) and 2) */
    453:     *RS(it+1) = -(*ss * *RS(it));
    454:     *RS(it)   = PetscConj(*cc) * *RS(it);
    455:     *hh       = PetscConj(*cc) * *hh + *ss * *(hh+1);

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

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

    467:     *res = 0.0;
    468:   }
    469:   return(0);
    470: }

    472: /*

    474:    KSPFGMRESGetNewVectors - This routine allocates more work vectors, starting from
    475:                          VEC_VV(it), and more preconditioned work vectors, starting
    476:                          from PREVEC(i).

    478: */
    481: static PetscErrorCode KSPFGMRESGetNewVectors(KSP ksp,PetscInt it)
    482: {
    483:   KSP_FGMRES     *fgmres = (KSP_FGMRES*)ksp->data;
    484:   PetscInt       nwork   = fgmres->nwork_alloc; /* number of work vector chunks allocated */
    485:   PetscInt       nalloc;                      /* number to allocate */
    487:   PetscInt       k;

    490:   nalloc = fgmres->delta_allocate; /* number of vectors to allocate
    491:                                       in a single chunk */

    493:   /* Adjust the number to allocate to make sure that we don't exceed the
    494:      number of available slots (fgmres->vecs_allocated)*/
    495:   if (it + VEC_OFFSET + nalloc >= fgmres->vecs_allocated) {
    496:     nalloc = fgmres->vecs_allocated - it - VEC_OFFSET;
    497:   }
    498:   if (!nalloc) return(0);

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

    502:   /* work vectors */
    503:   KSPCreateVecs(ksp,nalloc,&fgmres->user_work[nwork],0,NULL);
    504:   PetscLogObjectParents(ksp,nalloc,fgmres->user_work[nwork]);
    505:   for (k=0; k < nalloc; k++) {
    506:     fgmres->vecs[it+VEC_OFFSET+k] = fgmres->user_work[nwork][k];
    507:   }
    508:   /* specify size of chunk allocated */
    509:   fgmres->mwork_alloc[nwork] = nalloc;

    511:   /* preconditioned vectors */
    512:   KSPCreateVecs(ksp,nalloc,&fgmres->prevecs_user_work[nwork],0,NULL);
    513:   PetscLogObjectParents(ksp,nalloc,fgmres->prevecs_user_work[nwork]);
    514:   for (k=0; k < nalloc; k++) {
    515:     fgmres->prevecs[it+VEC_OFFSET+k] = fgmres->prevecs_user_work[nwork][k];
    516:   }

    518:   /* increment the number of work vector chunks */
    519:   fgmres->nwork_alloc++;
    520:   return(0);
    521: }

    523: /*

    525:    KSPBuildSolution_FGMRES

    527:      Input Parameter:
    528: .     ksp - the Krylov space object
    529: .     ptr-

    531:    Output Parameter:
    532: .     result - the solution

    534:    Note: this calls KSPFGMRESBuildSoln - the same function that KSPFGMRESCycle
    535:    calls directly.

    537: */
    540: PetscErrorCode KSPBuildSolution_FGMRES(KSP ksp,Vec ptr,Vec *result)
    541: {
    542:   KSP_FGMRES     *fgmres = (KSP_FGMRES*)ksp->data;

    546:   if (!ptr) {
    547:     if (!fgmres->sol_temp) {
    548:       VecDuplicate(ksp->vec_sol,&fgmres->sol_temp);
    549:       PetscLogObjectParent((PetscObject)ksp,(PetscObject)fgmres->sol_temp);
    550:     }
    551:     ptr = fgmres->sol_temp;
    552:   }
    553:   if (!fgmres->nrs) {
    554:     /* allocate the work area */
    555:     PetscMalloc1(fgmres->max_k,&fgmres->nrs);
    556:     PetscLogObjectMemory((PetscObject)ksp,fgmres->max_k*sizeof(PetscScalar));
    557:   }

    559:   KSPFGMRESBuildSoln(fgmres->nrs,ksp->vec_sol,ptr,ksp,fgmres->it);
    560:   if (result) *result = ptr;
    561:   return(0);
    562: }

    566: PetscErrorCode KSPSetFromOptions_FGMRES(PetscOptions *PetscOptionsObject,KSP ksp)
    567: {
    569:   PetscBool      flg;

    572:   KSPSetFromOptions_GMRES(PetscOptionsObject,ksp);
    573:   PetscOptionsHead(PetscOptionsObject,"KSP flexible GMRES Options");
    574:   PetscOptionsBoolGroupBegin("-ksp_fgmres_modifypcnochange","do not vary the preconditioner","KSPFGMRESSetModifyPC",&flg);
    575:   if (flg) {KSPFGMRESSetModifyPC(ksp,KSPFGMRESModifyPCNoChange,0,0);}
    576:   PetscOptionsBoolGroupEnd("-ksp_fgmres_modifypcksp","vary the KSP based preconditioner","KSPFGMRESSetModifyPC",&flg);
    577:   if (flg) {KSPFGMRESSetModifyPC(ksp,KSPFGMRESModifyPCKSP,0,0);}
    578:   PetscOptionsTail();
    579:   return(0);
    580: }

    582: typedef PetscErrorCode (*FCN1)(KSP,PetscInt,PetscInt,PetscReal,void*); /* force argument to next function to not be extern C*/
    583: typedef PetscErrorCode (*FCN2)(void*);

    587: static PetscErrorCode  KSPFGMRESSetModifyPC_FGMRES(KSP ksp,FCN1 fcn,void *ctx,FCN2 d)
    588: {
    591:   ((KSP_FGMRES*)ksp->data)->modifypc      = fcn;
    592:   ((KSP_FGMRES*)ksp->data)->modifydestroy = d;
    593:   ((KSP_FGMRES*)ksp->data)->modifyctx     = ctx;
    594:   return(0);
    595: }

    600: PetscErrorCode KSPReset_FGMRES(KSP ksp)
    601: {
    602:   KSP_FGMRES     *fgmres = (KSP_FGMRES*)ksp->data;
    604:   PetscInt       i;

    607:   PetscFree (fgmres->prevecs);
    608:   for (i=0; i<fgmres->nwork_alloc; i++) {
    609:     VecDestroyVecs(fgmres->mwork_alloc[i],&fgmres->prevecs_user_work[i]);
    610:   }
    611:   PetscFree(fgmres->prevecs_user_work);
    612:   if (fgmres->modifydestroy) {
    613:     (*fgmres->modifydestroy)(fgmres->modifyctx);
    614:   }
    615:   KSPReset_GMRES(ksp);
    616:   return(0);
    617: }

    621: PetscErrorCode  KSPGMRESSetRestart_FGMRES(KSP ksp,PetscInt max_k)
    622: {
    623:   KSP_FGMRES     *gmres = (KSP_FGMRES*)ksp->data;

    627:   if (max_k < 1) SETERRQ(PetscObjectComm((PetscObject)ksp),PETSC_ERR_ARG_OUTOFRANGE,"Restart must be positive");
    628:   if (!ksp->setupstage) {
    629:     gmres->max_k = max_k;
    630:   } else if (gmres->max_k != max_k) {
    631:     gmres->max_k    = max_k;
    632:     ksp->setupstage = KSP_SETUP_NEW;
    633:     /* free the data structures, then create them again */
    634:     KSPReset_FGMRES(ksp);
    635:   }
    636:   return(0);
    637: }

    641: PetscErrorCode  KSPGMRESGetRestart_FGMRES(KSP ksp,PetscInt *max_k)
    642: {
    643:   KSP_FGMRES *gmres = (KSP_FGMRES*)ksp->data;

    646:   *max_k = gmres->max_k;
    647:   return(0);
    648: }

    650: /*MC
    651:      KSPFGMRES - Implements the Flexible Generalized Minimal Residual method.
    652:                 developed by Saad with restart

    655:    Options Database Keys:
    656: +   -ksp_gmres_restart <restart> - the number of Krylov directions to orthogonalize against
    657: .   -ksp_gmres_haptol <tol> - sets the tolerance for "happy ending" (exact convergence)
    658: .   -ksp_gmres_preallocate - preallocate all the Krylov search directions initially (otherwise groups of
    659:                              vectors are allocated as needed)
    660: .   -ksp_gmres_classicalgramschmidt - use classical (unmodified) Gram-Schmidt to orthogonalize against the Krylov space (fast) (the default)
    661: .   -ksp_gmres_modifiedgramschmidt - use modified Gram-Schmidt in the orthogonalization (more stable, but slower)
    662: .   -ksp_gmres_cgs_refinement_type <never,ifneeded,always> - determine if iterative refinement is used to increase the
    663:                                    stability of the classical Gram-Schmidt  orthogonalization.
    664: .   -ksp_gmres_krylov_monitor - plot the Krylov space generated
    665: .   -ksp_fgmres_modifypcnochange - do not change the preconditioner between iterations
    666: -   -ksp_fgmres_modifypcksp - modify the preconditioner using KSPFGMRESModifyPCKSP()

    668:    Level: beginner

    670:     Notes: See KSPFGMRESSetModifyPC() for how to vary the preconditioner between iterations
    671:            Only right preconditioning is supported.

    673:     Notes: 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)
    674:            be bi-CG-stab with a preconditioner of Jacobi.

    676:     Developer Notes: This object is subclassed off of KSPGMRES

    678: .seealso:  KSPCreate(), KSPSetType(), KSPType (for list of available types), KSP, KSPGMRES, KSPLGMRES,
    679:            KSPGMRESSetRestart(), KSPGMRESSetHapTol(), KSPGMRESSetPreAllocateVectors(), KSPGMRESSetOrthogonalization(), KSPGMRESGetOrthogonalization(),
    680:            KSPGMRESClassicalGramSchmidtOrthogonalization(), KSPGMRESModifiedGramSchmidtOrthogonalization(),
    681:            KSPGMRESCGSRefinementType, KSPGMRESSetCGSRefinementType(),  KSPGMRESGetCGSRefinementType(), KSPGMRESMonitorKrylov(), KSPFGMRESSetModifyPC(),
    682:            KSPFGMRESModifyPCKSP()

    684: M*/

    688: PETSC_EXTERN PetscErrorCode KSPCreate_FGMRES(KSP ksp)
    689: {
    690:   KSP_FGMRES     *fgmres;

    694:   PetscNewLog(ksp,&fgmres);

    696:   ksp->data                              = (void*)fgmres;
    697:   ksp->ops->buildsolution                = KSPBuildSolution_FGMRES;
    698:   ksp->ops->setup                        = KSPSetUp_FGMRES;
    699:   ksp->ops->solve                        = KSPSolve_FGMRES;
    700:   ksp->ops->reset                        = KSPReset_FGMRES;
    701:   ksp->ops->destroy                      = KSPDestroy_FGMRES;
    702:   ksp->ops->view                         = KSPView_GMRES;
    703:   ksp->ops->setfromoptions               = KSPSetFromOptions_FGMRES;
    704:   ksp->ops->computeextremesingularvalues = KSPComputeExtremeSingularValues_GMRES;
    705:   ksp->ops->computeeigenvalues           = KSPComputeEigenvalues_GMRES;

    707:   KSPSetSupportedNorm(ksp,KSP_NORM_UNPRECONDITIONED,PC_RIGHT,3);
    708:   KSPSetSupportedNorm(ksp,KSP_NORM_NONE,PC_LEFT,0);

    710:   PetscObjectComposeFunction((PetscObject)ksp,"KSPGMRESSetPreAllocateVectors_C",KSPGMRESSetPreAllocateVectors_GMRES);
    711:   PetscObjectComposeFunction((PetscObject)ksp,"KSPGMRESSetOrthogonalization_C",KSPGMRESSetOrthogonalization_GMRES);
    712:   PetscObjectComposeFunction((PetscObject)ksp,"KSPGMRESGetOrthogonalization_C",KSPGMRESGetOrthogonalization_GMRES);
    713:   PetscObjectComposeFunction((PetscObject)ksp,"KSPGMRESSetRestart_C",KSPGMRESSetRestart_FGMRES);
    714:   PetscObjectComposeFunction((PetscObject)ksp,"KSPGMRESGetRestart_C",KSPGMRESGetRestart_FGMRES);
    715:   PetscObjectComposeFunction((PetscObject)ksp,"KSPFGMRESSetModifyPC_C",KSPFGMRESSetModifyPC_FGMRES);
    716:   PetscObjectComposeFunction((PetscObject)ksp,"KSPGMRESSetCGSRefinementType_C",KSPGMRESSetCGSRefinementType_GMRES);
    717:   PetscObjectComposeFunction((PetscObject)ksp,"KSPGMRESGetCGSRefinementType_C",KSPGMRESGetCGSRefinementType_GMRES);

    720:   fgmres->haptol         = 1.0e-30;
    721:   fgmres->q_preallocate  = 0;
    722:   fgmres->delta_allocate = FGMRES_DELTA_DIRECTIONS;
    723:   fgmres->orthog         = KSPGMRESClassicalGramSchmidtOrthogonalization;
    724:   fgmres->nrs            = 0;
    725:   fgmres->sol_temp       = 0;
    726:   fgmres->max_k          = FGMRES_DEFAULT_MAXK;
    727:   fgmres->Rsvd           = 0;
    728:   fgmres->orthogwork     = 0;
    729:   fgmres->modifypc       = KSPFGMRESModifyPCNoChange;
    730:   fgmres->modifyctx      = NULL;
    731:   fgmres->modifydestroy  = NULL;
    732:   fgmres->cgstype        = KSP_GMRES_CGS_REFINE_NEVER;
    733:   return(0);
    734: }