Actual source code: lgmres.c

 2:  #include lgmresp.h

  4: #define LGMRES_DELTA_DIRECTIONS 10
  5: #define LGMRES_DEFAULT_MAXK     30
  6: #define LGMRES_DEFAULT_AUGDIM   2 /*default number of augmentation vectors */ 
  7: static PetscErrorCode    LGMRESGetNewVectors(KSP,PetscInt);
  8: static PetscErrorCode    LGMRESUpdateHessenberg(KSP,PetscInt,PetscTruth,PetscReal *);
  9: static PetscErrorCode    BuildLgmresSoln(PetscScalar*,Vec,Vec,KSP,PetscInt);

 13: PetscErrorCode KSPLGMRESSetAugDim(KSP ksp, PetscInt dim)
 14: {

 18:   PetscTryMethod((ksp),KSPLGMRESSetAugDim_C,(KSP,PetscInt),(ksp,dim));
 19:   return(0);
 20: }

 24: PetscErrorCode KSPLGMRESSetConstant(KSP ksp)
 25: {

 29:   PetscTryMethod((ksp),KSPLGMRESSetConstant_C,(KSP),(ksp));
 30:   return(0);
 31: }

 33: /*
 34:     KSPSetUp_LGMRES - Sets up the workspace needed by lgmres.

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

 39: */
 42: PetscErrorCode    KSPSetUp_LGMRES(KSP ksp)
 43: {
 44:   PetscInt       size,hh,hes,rs,cc;
 46:   PetscInt       max_k,k, aug_dim;
 47:   KSP_LGMRES     *lgmres = (KSP_LGMRES *)ksp->data;

 50:   if (ksp->pc_side == PC_SYMMETRIC) {
 51:     SETERRQ(2,"no symmetric preconditioning for KSPLGMRES");
 52:   }
 53:   max_k         = lgmres->max_k;
 54:   aug_dim       = lgmres->aug_dim;
 55:   hh            = (max_k + 2) * (max_k + 1);
 56:   hes           = (max_k + 1) * (max_k + 1);
 57:   rs            = (max_k + 2);
 58:   cc            = (max_k + 1);  /* SS and CC are the same size */
 59:   size          = (hh + hes + rs + 2*cc) * sizeof(PetscScalar);

 61:   /* Allocate space and set pointers to beginning */
 62:   PetscMalloc(size,&lgmres->hh_origin);
 63:   PetscMemzero(lgmres->hh_origin,size);
 64:   PetscLogObjectMemory(ksp,size);                      /* HH - modified (by plane 
 65:                                                       rotations) hessenburg */
 66:   lgmres->hes_origin = lgmres->hh_origin + hh;     /* HES - unmodified hessenburg */
 67:   lgmres->rs_origin  = lgmres->hes_origin + hes;   /* RS - the right-hand-side of the 
 68:                                                       Hessenberg system */
 69:   lgmres->cc_origin  = lgmres->rs_origin + rs;     /* CC - cosines for rotations */
 70:   lgmres->ss_origin  = lgmres->cc_origin + cc;     /* SS - sines for rotations */

 72:   if (ksp->calc_sings) {
 73:     /* Allocate workspace to hold Hessenberg matrix needed by Eispack */
 74:     size = (max_k + 3)*(max_k + 9)*sizeof(PetscScalar);
 75:     PetscMalloc(size,&lgmres->Rsvd);
 76:     PetscMalloc(5*(max_k+2)*sizeof(PetscReal),&lgmres->Dsvd);
 77:     PetscLogObjectMemory(ksp,size+5*(max_k+2)*sizeof(PetscReal));
 78:   }

 80:   /* Allocate array to hold pointers to user vectors.  Note that we need
 81:   we need it+1 vectors, and it <= max_k)  - vec_offset indicates some initial work vectors*/
 82:   PetscMalloc((VEC_OFFSET+2+max_k)*sizeof(void*),&lgmres->vecs);
 83:   lgmres->vecs_allocated = VEC_OFFSET + 2 + max_k;
 84:   PetscMalloc((VEC_OFFSET+2+max_k)*sizeof(void*),&lgmres->user_work);
 85:   PetscMalloc((VEC_OFFSET+2+max_k)*sizeof(PetscInt),&lgmres->mwork_alloc);
 86:   PetscLogObjectMemory(ksp,(VEC_OFFSET+2+max_k)*(2*sizeof(void*)+sizeof(PetscInt)));

 88:   /* LGMRES_MOD: need array of pointers to augvecs*/
 89:   PetscMalloc((2 * aug_dim + AUG_OFFSET)*sizeof(void*),&lgmres->augvecs);
 90:   lgmres->aug_vecs_allocated = 2 *aug_dim + AUG_OFFSET;
 91:   PetscMalloc((2* aug_dim + AUG_OFFSET)*sizeof(void*),&lgmres->augvecs_user_work);
 92:   PetscMalloc(aug_dim*sizeof(PetscInt),&lgmres->aug_order);
 93:   PetscLogObjectMemory(ksp,(aug_dim)*(4*sizeof(void*) + sizeof(PetscInt)) + AUG_OFFSET*2*sizeof(void*) );

 95: 
 96:  /* if q_preallocate = 0 then only allocate one "chunk" of space (for 
 97:      5 vectors) - additional will then be allocated from LGMREScycle() 
 98:      as needed.  Otherwise, allocate all of the space that could be needed */
 99:   if (lgmres->q_preallocate) {
100:     lgmres->vv_allocated   = VEC_OFFSET + 2 + max_k;
101:     KSPGetVecs(ksp,lgmres->vv_allocated,&lgmres->user_work[0]);
102:     PetscLogObjectParents(ksp,lgmres->vv_allocated,lgmres->user_work[0]);
103:     lgmres->mwork_alloc[0] = lgmres->vv_allocated;
104:     lgmres->nwork_alloc    = 1;
105:     for (k=0; k<lgmres->vv_allocated; k++) {
106:       lgmres->vecs[k] = lgmres->user_work[0][k];
107:     }
108:   } else {
109:     lgmres->vv_allocated    = 5;
110:     KSPGetVecs(ksp,5,&lgmres->user_work[0]);
111:     PetscLogObjectParents(ksp,5,lgmres->user_work[0]);
112:     lgmres->mwork_alloc[0]  = 5;
113:     lgmres->nwork_alloc     = 1;
114:     for (k=0; k<lgmres->vv_allocated; k++) {
115:       lgmres->vecs[k] = lgmres->user_work[0][k];
116:     }
117:   }
118:   /* LGMRES_MOD - for now we will preallocate the augvecs - because aug_dim << restart
119:      ... also keep in mind that we need to keep augvecs from cycle to cycle*/
120:   lgmres->aug_vv_allocated = 2* aug_dim + AUG_OFFSET;
121:   lgmres->augwork_alloc =  2* aug_dim + AUG_OFFSET;
122:   KSPGetVecs(ksp,lgmres->aug_vv_allocated,&lgmres->augvecs_user_work[0]);
123:   PetscLogObjectParents(ksp,lgmres->aug_vv_allocated,lgmres->augvecs_user_work[0]);
124:   for (k=0; k<lgmres->aug_vv_allocated; k++) {
125:       lgmres->augvecs[k] = lgmres->augvecs_user_work[0][k];
126:     }

128:   return(0);
129: }


132: /*

134:     LGMRESCycle - Run lgmres, possibly with restart.  Return residual 
135:                   history if requested.

137:     input parameters:
138: .         lgmres  - structure containing parameters and work areas

140:     output parameters:
141: .        nres    - residuals (from preconditioned system) at each step.
142:                   If restarting, consider passing nres+it.  If null, 
143:                   ignored
144: .        itcount - number of iterations used.   nres[0] to nres[itcount]
145:                   are defined.  If null, ignored.  If null, ignored.
146: .        converged - 0 if not converged

148:                   
149:     Notes:
150:     On entry, the value in vector VEC_VV(0) should be 
151:     the initial residual.


154:  */
157: PetscErrorCode LGMREScycle(PetscInt *itcount,KSP ksp)
158: {

160:   KSP_LGMRES     *lgmres = (KSP_LGMRES *)(ksp->data);
161:   PetscReal      res_norm, res;
162:   PetscReal      hapbnd, tt;
163:   PetscScalar    zero = 0.0;
164:   PetscScalar    tmp;
165:   PetscTruth     hapend = PETSC_FALSE;  /* indicates happy breakdown ending */
167:   PetscInt       loc_it;                /* local count of # of dir. in Krylov space */
168:   PetscInt       max_k = lgmres->max_k; /* max approx space size */
169:   PetscInt       max_it = ksp->max_it;  /* max # of overall iterations for the method */
170:   /* LGMRES_MOD - new variables*/
171:   PetscInt       aug_dim = lgmres->aug_dim;
172:   PetscInt       spot = 0;
173:   PetscInt       order = 0;
174:   PetscInt       it_arnoldi;             /* number of arnoldi steps to take */
175:   PetscInt       it_total;               /* total number of its to take (=approx space size)*/
176:   PetscInt       ii, jj;
177:   PetscReal      tmp_norm;
178:   PetscScalar    inv_tmp_norm;
179:   PetscScalar    *avec;

182:   /* Number of pseudo iterations since last restart is the number 
183:      of prestart directions */
184:   loc_it = 0;

186:   /* LGMRES_MOD: determine number of arnoldi steps to take */
187:   /* if approx_constant then we keep the space the same size even if 
188:      we don't have the full number of aug vectors yet*/
189:   if (lgmres->approx_constant) {
190:      it_arnoldi = max_k - lgmres->aug_ct;
191:   } else {
192:       it_arnoldi = max_k - aug_dim;
193:   }

195:   it_total =  it_arnoldi + lgmres->aug_ct;

197:   /* initial residual is in VEC_VV(0)  - compute its norm*/
198:   VecNorm(VEC_VV(0),NORM_2,&res_norm);
199:   res    = res_norm;
200: 
201:   /* first entry in right-hand-side of hessenberg system is just 
202:      the initial residual norm */
203:   *GRS(0) = res_norm;

205:  /* check for the convergence */
206:   if (!res) {
207:      if (itcount) *itcount = 0;
208:      ksp->reason = KSP_CONVERGED_ATOL;
209:      PetscLogInfo(ksp,"GMRESCycle: Converged due to zero residual norm on entry\n");
210:      return(0);
211:   }

213:   /* scale VEC_VV (the initial residual) */
214:   tmp = 1.0/res_norm; VecScale(&tmp,VEC_VV(0));

216:   /* FYI: AMS calls are for memory snooper */
217:   PetscObjectTakeAccess(ksp);
218:   ksp->rnorm = res;
219:   PetscObjectGrantAccess(ksp);


222:   /* note: (lgmres->it) is always set one less than (loc_it) It is used in 
223:      KSPBUILDSolution_LGMRES, where it is passed to BuildLgmresSoln.  
224:      Note that when BuildLgmresSoln is called from this function, 
225:      (loc_it -1) is passed, so the two are equivalent */
226:   lgmres->it = (loc_it - 1);

228: 
229:   /* MAIN ITERATION LOOP BEGINNING*/


232:   /* keep iterating until we have converged OR generated the max number
233:      of directions OR reached the max number of iterations for the method */
234:   (*ksp->converged)(ksp,ksp->its,res,&ksp->reason,ksp->cnvP);
235: 
236:   while (!ksp->reason && loc_it < it_total && ksp->its < max_it) { /* LGMRES_MOD: changed to it_total */
237:      KSPLogResidualHistory(ksp,res);
238:      lgmres->it = (loc_it - 1);
239:      KSPMonitor(ksp,ksp->its,res);

241:     /* see if more space is needed for work vectors */
242:     if (lgmres->vv_allocated <= loc_it + VEC_OFFSET + 1) {
243:        LGMRESGetNewVectors(ksp,loc_it+1);
244:       /* (loc_it+1) is passed in as number of the first vector that should
245:          be allocated */
246:     }

248:     /*LGMRES_MOD: decide whether this is an arnoldi step or an aug step */
249:     if (loc_it < it_arnoldi) { /* Arnoldi */
250:        KSP_PCApplyBAorAB(ksp,VEC_VV(loc_it),VEC_VV(1+loc_it),VEC_TEMP_MATOP);
251:     } else { /*aug step */
252:        order = loc_it - it_arnoldi + 1; /* which aug step */
253:        for (ii=0; ii<aug_dim; ii++) {
254:            if (lgmres->aug_order[ii] == order) {
255:               spot = ii;
256:               break; /* must have this because there will be duplicates before aug_ct = aug_dim */
257:             }
258:         }

260:        VecCopy(A_AUGVEC(spot), VEC_VV(1+loc_it));
261:        /*note: an alternate implementation choice would be to only save the AUGVECS and
262:          not A_AUGVEC and then apply the PC here to the augvec */
263:     }

265:     /* update hessenberg matrix and do Gram-Schmidt - new direction is in
266:        VEC_VV(1+loc_it)*/
267:     (*lgmres->orthog)(ksp,loc_it);

269:     /* new entry in hessenburg is the 2-norm of our new direction */
270:     VecNorm(VEC_VV(loc_it+1),NORM_2,&tt);
271:     *HH(loc_it+1,loc_it)   = tt;
272:     *HES(loc_it+1,loc_it)  = tt;


275:     /* check for the happy breakdown */
276:     hapbnd  = PetscAbsScalar(tt / *GRS(loc_it));/* GRS(loc_it) contains the res_norm from the last iteration  */
277:     if (hapbnd > lgmres->haptol) hapbnd = lgmres->haptol;
278:     if (tt > hapbnd) {
279:        tmp = 1.0/tt;
280:        VecScale(&tmp,VEC_VV(loc_it+1)); /* scale new direction by its norm */
281:     } else {
282:        PetscLogInfo(ksp,"Detected happy breakdown, current hapbnd = %g tt = %g\n",hapbnd,tt);
283:        hapend = PETSC_TRUE;
284:     }

286:     /* Now apply rotations to new col of hessenberg (and right side of system), 
287:        calculate new rotation, and get new residual norm at the same time*/
288:     LGMRESUpdateHessenberg(ksp,loc_it,hapend,&res);
289:     if (ksp->reason) break;

291:     loc_it++;
292:     lgmres->it  = (loc_it-1);  /* Add this here in case it has converged */
293: 
294:     PetscObjectTakeAccess(ksp);
295:     ksp->its++;
296:     ksp->rnorm = res;
297:     PetscObjectGrantAccess(ksp);

299:     (*ksp->converged)(ksp,ksp->its,res,&ksp->reason,ksp->cnvP);

301:     /* Catch error in happy breakdown and signal convergence and break from loop */
302:     if (hapend) {
303:       if (!ksp->reason) {
304:         SETERRQ1(0,"You reached the happy break down,but convergence was not indicated. Residual norm = %g",res);
305:       }
306:       break;
307:     }
308:   }
309:   /* END OF ITERATION LOOP */

311:   KSPLogResidualHistory(ksp,res);

313:   /* Monitor if we know that we will not return for a restart */
314:   if (ksp->reason || ksp->its >= max_it) {
315:     KSPMonitor(ksp, ksp->its, res);
316:   }

318:   if (itcount) *itcount    = loc_it;

320:   /*
321:     Down here we have to solve for the "best" coefficients of the Krylov
322:     columns, add the solution values together, and possibly unwind the
323:     preconditioning from the solution
324:    */
325: 
326:   /* Form the solution (or the solution so far) */
327:   /* Note: must pass in (loc_it-1) for iteration count so that BuildLgmresSoln
328:      properly navigates */

330:   BuildLgmresSoln(GRS(0),ksp->vec_sol,ksp->vec_sol,ksp,loc_it-1);


333:   /* LGMRES_MOD collect aug vector and A*augvector for future restarts -
334:      only if we will be restarting (i.e. this cycle performed it_total
335:      iterations)  */
336:   if (!ksp->reason && ksp->its < max_it && aug_dim > 0) {

338:      /*AUG_TEMP contains the new augmentation vector (assigned in  BuildLgmresSoln) */
339:     if (!lgmres->aug_ct) {
340:         spot = 0;
341:         lgmres->aug_ct++;
342:      } else if (lgmres->aug_ct < aug_dim) {
343:         spot = lgmres->aug_ct;
344:         lgmres->aug_ct++;
345:      } else { /* truncate */
346:         for (ii=0; ii<aug_dim; ii++) {
347:            if (lgmres->aug_order[ii] == aug_dim) {
348:               spot = ii;
349:             }
350:         }
351:      }

353: 

355:      VecCopy(AUG_TEMP, AUGVEC(spot));
356:      /*need to normalize */
357:      VecNorm(AUGVEC(spot), NORM_2, &tmp_norm);
358:      inv_tmp_norm = 1.0/tmp_norm;
359:      VecScale(&inv_tmp_norm, AUGVEC(spot));

361:      /*set new aug vector to order 1  - move all others back one */
362:      for (ii=0; ii < aug_dim; ii++) {
363:         AUG_ORDER(ii)++;
364:      }
365:      AUG_ORDER(spot) = 1;

367:      /*now add the A*aug vector to A_AUGVEC(spot)  - this is independ. of preconditioning type*/
368:      /* want V*H*y - y is in GRS, V is in VEC_VV and H is in HES */

370: 
371:      /* first do H+*y */
372:      VecSet(&zero, AUG_TEMP);
373:      VecGetArray(AUG_TEMP, &avec);
374:      for (ii=0; ii < it_total + 1; ii++) {
375:         for (jj=0; jj <= ii+1; jj++) {
376:            avec[jj] += *HES(jj ,ii) * *GRS(ii);
377:         }
378:      }

380:      /*now multiply result by V+ */
381:      VecSet(&zero, VEC_TEMP);
382:      VecMAXPY(it_total+1, avec, VEC_TEMP, &VEC_VV(0)); /*answer is in VEC_TEMP*/
383:      VecRestoreArray(AUG_TEMP, &avec);
384: 
385:      /*copy answer to aug location  and scale*/
386:      VecCopy(VEC_TEMP,  A_AUGVEC(spot));
387:      VecScale(&inv_tmp_norm, A_AUGVEC(spot));


390:   }
391:   return(0);
392: }

394: /*  
395:     KSPSolve_LGMRES - This routine applies the LGMRES method.


398:    Input Parameter:
399: .     ksp - the Krylov space object that was set to use lgmres

401:    Output Parameter:
402: .     outits - number of iterations used

404: */

408: PetscErrorCode KSPSolve_LGMRES(KSP ksp)
409: {
411:   PetscInt       cycle_its; /* iterations done in a call to LGMREScycle */
412:   PetscInt       itcount;   /* running total of iterations, incl. those in restarts */
413:   KSP_LGMRES     *lgmres = (KSP_LGMRES *)ksp->data;
414:   PetscTruth     guess_zero = ksp->guess_zero;
415:   PetscInt       ii;        /*LGMRES_MOD variable */

418:   if (ksp->calc_sings && !lgmres->Rsvd) {
419:      SETERRQ(PETSC_ERR_ORDER,"Must call KSPSetComputeSingularValues() before KSPSetUp() is called");
420:   }
421:   PetscObjectTakeAccess(ksp);
422:   ksp->its        = 0;
423:   lgmres->aug_ct  = 0;
424:   lgmres->matvecs = 0;
425:   PetscObjectGrantAccess(ksp);

427:   /* initialize */
428:   itcount  = 0;
429:   ksp->reason = KSP_CONVERGED_ITERATING;
430:   /*LGMRES_MOD*/
431:   for (ii=0; ii<lgmres->aug_dim; ii++) {
432:      lgmres->aug_order[ii] = 0;
433:   }

435:   while (!ksp->reason) {
436:      /* calc residual - puts in VEC_VV(0) */
437:     KSPInitialResidual(ksp,ksp->vec_sol,VEC_TEMP,VEC_TEMP_MATOP,VEC_VV(0),ksp->vec_rhs);
438:     LGMREScycle(&cycle_its,ksp);
439:     itcount += cycle_its;
440:     if (itcount >= ksp->max_it) {
441:       ksp->reason = KSP_DIVERGED_ITS;
442:       break;
443:     }
444:     ksp->guess_zero = PETSC_FALSE; /* every future call to KSPInitialResidual() will have nonzero guess */
445:   }
446:   ksp->guess_zero = guess_zero; /* restore if user provided nonzero initial guess */
447:   return(0);
448: }

450: /*

452:    KSPDestroy_LGMRES - Frees all memory space used by the Krylov method.

454: */
457: PetscErrorCode KSPDestroy_LGMRES(KSP ksp)
458: {
459:   KSP_LGMRES     *lgmres = (KSP_LGMRES*)ksp->data;
461:   PetscInt       i;

464:   /* Free the Hessenberg matrices */
465:   if (lgmres->hh_origin) {PetscFree(lgmres->hh_origin);}

467:   /* Free pointers to user variables */
468:   if (lgmres->vecs) {PetscFree(lgmres->vecs);}

470:   /*LGMRES_MOD - free pointers for extra vectors */
471:   if (lgmres->augvecs) {PetscFree(lgmres->augvecs);}

473:   /* free work vectors */
474:   for (i=0; i < lgmres->nwork_alloc; i++) {
475:     VecDestroyVecs(lgmres->user_work[i],lgmres->mwork_alloc[i]);
476:   }
477:   if (lgmres->user_work)  {PetscFree(lgmres->user_work);}

479:   /*LGMRES_MOD - free aug work vectors also */
480:   /*this was all allocated as one "chunk" */
481:   VecDestroyVecs(lgmres->augvecs_user_work[0],lgmres->augwork_alloc);
482:   if (lgmres->augvecs_user_work)  {PetscFree(lgmres->augvecs_user_work);}
483:   if (lgmres->aug_order) {PetscFree(lgmres->aug_order);}

485:   if (lgmres->mwork_alloc) {PetscFree(lgmres->mwork_alloc);}
486:   if (lgmres->nrs) {PetscFree(lgmres->nrs);}
487:   if (lgmres->sol_temp) {VecDestroy(lgmres->sol_temp);}
488:   if (lgmres->Rsvd) {PetscFree(lgmres->Rsvd);}
489:   if (lgmres->Dsvd) {PetscFree(lgmres->Dsvd);}
490:   PetscFree(lgmres);
491:   return(0);
492: }

494: /*
495:     BuildLgmresSoln - create the solution from the starting vector and the
496:                       current iterates.

498:     Input parameters:
499:         nrs - work area of size it + 1.
500:         vguess  - index of initial guess
501:         vdest - index of result.  Note that vguess may == vdest (replace
502:                 guess with the solution).
503:         it - HH upper triangular part is a block of size (it+1) x (it+1)  

505:      This is an internal routine that knows about the LGMRES internals.
506:  */
509: static PetscErrorCode BuildLgmresSoln(PetscScalar* nrs,Vec vguess,Vec vdest,KSP ksp,PetscInt it)
510: {
511:   PetscScalar    tt,zero = 0.0,one = 1.0;
513:   PetscInt       ii,k,j;
514:   KSP_LGMRES     *lgmres = (KSP_LGMRES *)(ksp->data);
515:   /*LGMRES_MOD */
516:   PetscInt       it_arnoldi, it_aug;
517:   PetscInt       jj, spot = 0;

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

522:   /* If it is < 0, no lgmres steps have been performed */
523:   if (it < 0) {
524:     if (vdest != vguess) {
525:       VecCopy(vguess,vdest);
526:     }
527:     return(0);
528:   }

530:   /* so (it+1) lgmres steps HAVE been performed */

532:   /* LGMRES_MOD - determine if we need to use augvecs for the soln  - do not assume that
533:      this is called after the total its allowed for an approx space */
534:    if (lgmres->approx_constant) {
535:      it_arnoldi = lgmres->max_k - lgmres->aug_ct;
536:    } else {
537:      it_arnoldi = lgmres->max_k - lgmres->aug_dim;
538:    }
539:    if (it_arnoldi >= it +1) {
540:       it_aug = 0;
541:       it_arnoldi = it+1;
542:    } else {
543:       it_aug = (it + 1) - it_arnoldi;
544:    }

546:   /* now it_arnoldi indicates the number of matvecs that took place */
547:   lgmres->matvecs += it_arnoldi;

549: 
550:   /* solve the upper triangular system - GRS is the right side and HH is 
551:      the upper triangular matrix  - put soln in nrs */
552:   if (*HH(it,it) == 0.0) SETERRQ2(PETSC_ERR_CONV_FAILED,"HH(it,it) is identically zero; it = %D GRS(it) = %g",it,PetscAbsScalar(*GRS(it)));
553:   if (*HH(it,it) != 0.0) {
554:      nrs[it] = *GRS(it) / *HH(it,it);
555:   } else {
556:      nrs[it] = 0.0;
557:   }

559:   for (ii=1; ii<=it; ii++) {
560:     k   = it - ii;
561:     tt  = *GRS(k);
562:     for (j=k+1; j<=it; j++) tt  = tt - *HH(k,j) * nrs[j];
563:     nrs[k]   = tt / *HH(k,k);
564:   }

566:   /* Accumulate the correction to the soln of the preconditioned prob. in VEC_TEMP */
567:   VecSet(&zero,VEC_TEMP); /* set VEC_TEMP components to 0 */

569:   /*LGMRES_MOD - if augmenting has happened we need to form the solution 
570:     using the augvecs */
571:   if (!it_aug) { /* all its are from arnoldi */
572:      VecMAXPY(it+1,nrs,VEC_TEMP,&VEC_VV(0));
573:   } else { /*use aug vecs */
574:      /*first do regular krylov directions */
575:      VecMAXPY(it_arnoldi,nrs,VEC_TEMP,&VEC_VV(0));
576:      /*now add augmented portions - add contribution of aug vectors one at a time*/


579:      for (ii=0; ii<it_aug; ii++) {
580:         for (jj=0; jj<lgmres->aug_dim; jj++) {
581:            if (lgmres->aug_order[jj] == (ii+1)) {
582:               spot = jj;
583:               break; /* must have this because there will be duplicates before aug_ct = aug_dim */
584:             }
585:         }
586:         VecAXPY(&nrs[it_arnoldi+ii],AUGVEC(spot),VEC_TEMP);
587:       }
588:   }
589:   /* now VEC_TEMP is what we want to keep for augmenting purposes - grab before the
590:      preconditioner is "unwound" from right-precondtioning*/
591:   VecCopy(VEC_TEMP, AUG_TEMP);

593:   KSPUnwindPreconditioner(ksp,VEC_TEMP,VEC_TEMP_MATOP);

595:   /* add solution to previous solution */
596:   /* put updated solution into vdest.*/
597:   if (vdest != vguess) {
598:     VecCopy(VEC_TEMP,vdest);
599:   }
600:   VecAXPY(&one,VEC_TEMP,vdest);

602:   return(0);
603: }

605: /*

607:     LGMRESUpdateHessenberg - Do the scalar work for the orthogonalization.  
608:                             Return new residual.

610:     input parameters:

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

617:     output parameters:
618: .        res - the new residual
619:         
620:  */
623: static PetscErrorCode LGMRESUpdateHessenberg(KSP ksp,PetscInt it,PetscTruth hapend,PetscReal *res)
624: {
625:   PetscScalar   *hh,*cc,*ss,tt;
626:   PetscInt      j;
627:   KSP_LGMRES    *lgmres = (KSP_LGMRES *)(ksp->data);

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

635:   /* Apply all the previously computed plane rotations to the new column
636:      of the Hessenberg matrix */
637:   /* Note: this uses the rotation [conj(c)  s ; -s   c], c= cos(theta), s= sin(theta) */

639:   for (j=1; j<=it; j++) {
640:     tt  = *hh;
641: #if defined(PETSC_USE_COMPLEX)
642:     *hh = PetscConj(*cc) * tt + *ss * *(hh+1);
643: #else
644:     *hh = *cc * tt + *ss * *(hh+1);
645: #endif
646:     hh++;
647:     *hh = *cc++ * *hh - (*ss++ * tt);
648:     /* hh, cc, and ss have all been incremented one by end of loop */
649:   }

651:   /*
652:     compute the new plane rotation, and apply it to:
653:      1) the right-hand-side of the Hessenberg system (GRS)
654:         note: it affects GRS(it) and GRS(it+1)
655:      2) the new column of the Hessenberg matrix
656:         note: it affects HH(it,it) which is currently pointed to 
657:         by hh and HH(it+1, it) (*(hh+1))  
658:     thus obtaining the updated value of the residual...
659:   */

661:   /* compute new plane rotation */

663:   if (!hapend) {
664: #if defined(PETSC_USE_COMPLEX)
665:     tt        = PetscSqrtScalar(PetscConj(*hh) * *hh + PetscConj(*(hh+1)) * *(hh+1));
666: #else
667:     tt        = PetscSqrtScalar(*hh * *hh + *(hh+1) * *(hh+1));
668: #endif
669:     if (tt == 0.0) {
670:       ksp->reason = KSP_DIVERGED_NULL;
671:       return(0);
672:     }
673:     *cc       = *hh / tt;   /* new cosine value */
674:     *ss       = *(hh+1) / tt;  /* new sine value */

676:     /* apply to 1) and 2) */
677:     *GRS(it+1) = - (*ss * *GRS(it));
678: #if defined(PETSC_USE_COMPLEX)
679:     *GRS(it)   = PetscConj(*cc) * *GRS(it);
680:     *hh        = PetscConj(*cc) * *hh + *ss * *(hh+1);
681: #else
682:     *GRS(it)   = *cc * *GRS(it);
683:     *hh        = *cc * *hh + *ss * *(hh+1);
684: #endif

686:     /* residual is the last element (it+1) of right-hand side! */
687:     *res      = PetscAbsScalar(*GRS(it+1));

689:   } else { /* happy breakdown: HH(it+1, it) = 0, therfore we don't need to apply 
690:             another rotation matrix (so RH doesn't change).  The new residual is 
691:             always the new sine term times the residual from last time (GRS(it)), 
692:             but now the new sine rotation would be zero...so the residual should
693:             be zero...so we will multiply "zero" by the last residual.  This might
694:             not be exactly what we want to do here -could just return "zero". */
695: 
696:     *res = 0.0;
697:   }
698:   return(0);
699: }

701: /*

703:    LGMRESGetNewVectors - This routine allocates more work vectors, starting from 
704:                          VEC_VV(it) 
705:                          
706: */
709: static PetscErrorCode LGMRESGetNewVectors(KSP ksp,PetscInt it)
710: {
711:   KSP_LGMRES     *lgmres = (KSP_LGMRES *)ksp->data;
712:   PetscInt       nwork = lgmres->nwork_alloc; /* number of work vector chunks allocated */
713:   PetscInt       nalloc;                      /* number to allocate */
715:   PetscInt       k;
716: 
718:   nalloc = lgmres->delta_allocate; /* number of vectors to allocate 
719:                                       in a single chunk */

721:   /* Adjust the number to allocate to make sure that we don't exceed the
722:      number of available slots (lgmres->vecs_allocated)*/
723:   if (it + VEC_OFFSET + nalloc >= lgmres->vecs_allocated){
724:     nalloc = lgmres->vecs_allocated - it - VEC_OFFSET;
725:   }
726:   if (!nalloc) return(0);

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

730:   /* work vectors */
731:   KSPGetVecs(ksp,nalloc,&lgmres->user_work[nwork]);
732:   PetscLogObjectParents(ksp,nalloc,lgmres->user_work[nwork]);
733:   /* specify size of chunk allocated */
734:   lgmres->mwork_alloc[nwork] = nalloc;

736:   for (k=0; k < nalloc; k++) {
737:     lgmres->vecs[it+VEC_OFFSET+k] = lgmres->user_work[nwork][k];
738:   }
739: 

741:   /* LGMRES_MOD - for now we are preallocating the augmentation vectors */
742: 

744:   /* increment the number of work vector chunks */
745:   lgmres->nwork_alloc++;
746:   return(0);
747: }

749: /* 

751:    KSPBuildSolution_LGMRES

753:      Input Parameter:
754: .     ksp - the Krylov space object
755: .     ptr-

757:    Output Parameter:
758: .     result - the solution

760:    Note: this calls BuildLgmresSoln - the same function that LGMREScycle
761:    calls directly.  

763: */
766: PetscErrorCode KSPBuildSolution_LGMRES(KSP ksp,Vec ptr,Vec *result)
767: {
768:   KSP_LGMRES     *lgmres = (KSP_LGMRES *)ksp->data;

772:   if (!ptr) {
773:     if (!lgmres->sol_temp) {
774:       VecDuplicate(ksp->vec_sol,&lgmres->sol_temp);
775:       PetscLogObjectParent(ksp,lgmres->sol_temp);
776:     }
777:     ptr = lgmres->sol_temp;
778:   }
779:   if (!lgmres->nrs) {
780:     /* allocate the work area */
781:     PetscMalloc(lgmres->max_k*sizeof(PetscScalar),&lgmres->nrs);
782:     PetscLogObjectMemory(ksp,lgmres->max_k*sizeof(PetscScalar));
783:   }
784: 
785:   BuildLgmresSoln(lgmres->nrs,ksp->vec_sol,ptr,ksp,lgmres->it);
786:   *result = ptr;
787: 
788:   return(0);
789: }

791: /*

793:    KSPView_LGMRES -Prints information about the current Krylov method 
794:                   being used.

796:  */
799: PetscErrorCode KSPView_LGMRES(KSP ksp,PetscViewer viewer)
800: {
801:   KSP_LGMRES     *lgmres = (KSP_LGMRES *)ksp->data;
802:   const char     *cstr;
804:   PetscTruth     iascii,isstring;

807:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_ASCII,&iascii);
808:   PetscTypeCompare((PetscObject)viewer,PETSC_VIEWER_STRING,&isstring);
809:   if (lgmres->orthog == KSPGMRESClassicalGramSchmidtOrthogonalization) {
810:     if (lgmres->cgstype == KSP_GMRES_CGS_REFINE_NEVER) {
811:       cstr = "Classical (unmodified) Gram-Schmidt Orthogonalization with no iterative refinement";
812:     } else if (lgmres->cgstype == KSP_GMRES_CGS_REFINE_ALWAYS) {
813:       cstr = "Classical (unmodified) Gram-Schmidt Orthogonalization with one step of iterative refinement";
814:     } else {
815:       cstr = "Classical (unmodified) Gram-Schmidt Orthogonalization with one step of iterative refinement when needed";
816:     }
817:   } else if (lgmres->orthog == KSPGMRESModifiedGramSchmidtOrthogonalization) {
818:     cstr = "Modified Gram-Schmidt Orthogonalization";
819:   } else {
820:     cstr = "unknown orthogonalization";
821:   }
822:   if (iascii) {
823:     PetscViewerASCIIPrintf(viewer,"  LGMRES: restart=%D, using %s\n",lgmres->max_k,cstr);
824:     /*LGMRES_MOD */
825:     PetscViewerASCIIPrintf(viewer,"  LGMRES: aug. dimension=%D\n",lgmres->aug_dim);
826:     if (lgmres->approx_constant) {
827:        PetscViewerASCIIPrintf(viewer,"  LGMRES: approx. space size was kept constant.\n");
828:     }
829:     PetscViewerASCIIPrintf(viewer,"  LGMRES: number of matvecs=%D\n",lgmres->matvecs);

831:     PetscViewerASCIIPrintf(viewer,"  LGMRES: happy breakdown tolerance %g\n",lgmres->haptol);
832:   } else if (isstring) {
833:     PetscViewerStringSPrintf(viewer,"%s restart %D",cstr,lgmres->max_k);
834:   } else {
835:     SETERRQ1(PETSC_ERR_SUP,"Viewer type %s not supported for KSP LGMRES",((PetscObject)viewer)->type_name);
836:   }
837:   return(0);


840: }

844: PetscErrorCode KSPSetFromOptions_LGMRES(KSP ksp)
845: {
847:   PetscInt       restart, aug,indx;
848:   PetscReal      haptol;
849:   KSP_LGMRES     *lgmres = (KSP_LGMRES*) ksp->data;
850:   PetscTruth     flg;
851:   const char     *types[] = {"never","ifneeded","always"};

854:   PetscOptionsHead("KSP LGMRES Options");

856: 

858:     PetscOptionsInt("-ksp_gmres_restart","For LGMRES, this is the maximum size of the approximation space","KSPGMRESSetRestart",lgmres->max_k,&restart,&flg);
859:     if (flg) { KSPGMRESSetRestart(ksp,restart); }
860:     PetscOptionsReal("-ksp_gmres_haptol","Tolerance for declaring exact convergence (happy ending)","KSPGMRESSetHapTol",lgmres->haptol,&haptol,&flg);
861:     if (flg) { KSPGMRESSetHapTol(ksp,haptol); }
862:     PetscOptionsName("-ksp_gmres_preallocate","Preallocate all Krylov vectors","KSPGMRESSetPreAllocateVectors",&flg);
863:     if (flg) {KSPGMRESSetPreAllocateVectors(ksp);}
864:     PetscOptionsLogicalGroupBegin("-ksp_gmres_classicalgramschmidt","Use classical (unmodified) Gram-Schmidt (fast)","KSPGMRESSetOrthogonalization",&flg);
865:     if (flg) {KSPGMRESSetOrthogonalization(ksp,KSPGMRESClassicalGramSchmidtOrthogonalization);}
866:     PetscOptionsLogicalGroup("-ksp_gmres_modifiedgramschmidt","Use modified Gram-Schmidt (slow but more stable)","KSPGMRESSetOrthogonalization",&flg);
867:     if (flg) {KSPGMRESSetOrthogonalization(ksp,KSPGMRESModifiedGramSchmidtOrthogonalization);}
868:     PetscOptionsEList("-ksp_gmres_cgs_refinement_type","Type of iterative refinement for classical (unmodified) Gram-Schmidt","KSPGMRESSetCGSRefinementType()",types,3,types[lgmres->cgstype],&indx,&flg);
869:     if (flg) {
870:       KSPGMRESSetCGSRefinementType(ksp,(KSPGMRESCGSRefinementType)indx);
871:     }

873:     PetscOptionsName("-ksp_gmres_krylov_monitor","Graphically plot the Krylov directions","KSPSetMonitor",&flg);
874:     if (flg) {
875:       PetscViewers viewers;
876:       PetscViewersCreate(ksp->comm,&viewers);
877:       KSPSetMonitor(ksp,KSPGMRESKrylovMonitor,viewers,(PetscErrorCode (*)(void*))PetscViewersDestroy);
878:     }

880: /* LGMRES_MOD - specify number of augmented vectors and whether the space should be a constant size*/
881:      PetscOptionsName("-ksp_lgmres_constant","Use constant approx. space size","KSPGMRESSetConstant",&flg);
882:     /*if (flg) {KSPGMRESSetConstant(ksp);}*/ /*<--doesn't like this */
883:     if (flg) { lgmres->approx_constant = 1; }                     /* in favor of this line....*/

885:     PetscOptionsInt("-ksp_lgmres_augment","Number of error approximations to augment the Krylov space with","KSPLGMRESSetAugDim",lgmres->aug_dim,&aug,&flg);
886:     if (flg) { KSPLGMRESSetAugDim(ksp,aug); }



890:   PetscOptionsTail();
891:   return(0);
892: }


895: EXTERN PetscErrorCode KSPComputeExtremeSingularValues_GMRES(KSP,PetscReal *,PetscReal *);
896: EXTERN PetscErrorCode KSPComputeEigenvalues_GMRES(KSP,PetscInt,PetscReal *,PetscReal *,PetscInt *);

898: /*functions for extra lgmres options here*/
902: PetscErrorCode KSPLGMRESSetConstant_LGMRES(KSP ksp)
903: {
904:   KSP_LGMRES *lgmres = (KSP_LGMRES *)ksp->data;
906:   lgmres->approx_constant = 1;
907: 
908:   return(0);
909: }

915: PetscErrorCode KSPLGMRESSetAugDim_LGMRES(KSP ksp,PetscInt aug_dim)
916: {
917:   KSP_LGMRES *lgmres = (KSP_LGMRES *)ksp->data;

920:   if (aug_dim < 0) SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Augmentation dimension must be positive");
921:   if (aug_dim > (lgmres->max_k -1))  SETERRQ(PETSC_ERR_ARG_OUTOFRANGE,"Augmentation dimension must be <= (restart size-1)");
922:   lgmres->aug_dim = aug_dim;
923:   return(0);
924: }


928: /* end new lgmres functions */


931: /* use these options from gmres */
933: EXTERN PetscErrorCode KSPGMRESSetHapTol_GMRES(KSP,double);
934: EXTERN PetscErrorCode KSPGMRESSetPreAllocateVectors_GMRES(KSP);
935: EXTERN PetscErrorCode KSPGMRESSetRestart_GMRES(KSP,PetscInt);
936: EXTERN PetscErrorCode KSPGMRESSetOrthogonalization_GMRES(KSP,PetscErrorCode (*)(KSP,PetscInt));
937: EXTERN PetscErrorCode KSPGMRESSetCGSRefinementType_GMRES(KSP,KSPGMRESCGSRefinementType);

940: /*MC
941:      KSPLGMRES - Augments the standard GMRES approximation space with approximation to
942:                  the error from previous restart cycles.

944:    Options Database Keys:
945: +   -ksp_gmres_restart <restart> - the number of Krylov directions to orthogonalize against
946: .   -ksp_gmres_haptol <tol> - sets the tolerance for "happy ending" (exact convergence)
947: .   -ksp_gmres_preallocate - preallocate all the Krylov search directions initially (otherwise groups of 
948:                              vectors are allocated as needed)
949: .   -ksp_gmres_classicalgramschmidt - use classical (unmodified) Gram-Schmidt to orthogonalize against the Krylov space (fast) (the default)
950: .   -ksp_gmres_modifiedgramschmidt - use modified Gram-Schmidt in the orthogonalization (more stable, but slower)
951: .   -ksp_gmres_cgs_refinement_type <never,ifneeded,always> - determine if iterative refinement is used to increase the 
952:                                    stability of the classical Gram-Schmidt  orthogonalization.
953: .   -ksp_gmres_krylov_monitor - plot the Krylov space generated
954: .   -ksp_lgmres_constant - Use constant approx. space size
955: -   -ksp_lgmres_augment <n> - Number of error approximations to augment the Krylov space with

957:     Described in:
958:      A. H. Baker, E.R. Jessup, and T.A. Manteuffel. A technique for
959:      accelerating the convergence of restarted GMRES. Submitted to SIAM
960:      Journal on Matrix Analysis and Applications. Also available as
961:      Technical Report #CU-CS-945-03, University of Colorado, Department of
962:      Computer Science, January, 2003. 

964:    Level: beginner

966:    Contributed by: Allison Baker

968: .seealso:  KSPCreate(), KSPSetType(), KSPType (for list of available types), KSP, KSPFGMRES, KSPGMRES,
969:            KSPGMRESSetRestart(), KSPGMRESSetHapTol(), KSPGMRESSetPreAllocateVectors(), KSPGMRESSetOrthogonalization()
970:            KSPGMRESClassicalGramSchmidtOrthogonalization(), KSPGMRESModifiedGramSchmidtOrthogonalization(),
971:            KSPGMRESCGSRefinementType, KSPGMRESSetCGSRefinementType(), KSPGMRESKrylovMonitor(), KSPLGMRESSetAugDim(),
972:            KSPGMRESSetConstant()

974: M*/

979: PetscErrorCode KSPCreate_LGMRES(KSP ksp)
980: {
981:   KSP_LGMRES     *lgmres;

985:   PetscNew(KSP_LGMRES,&lgmres);
986:   PetscMemzero(lgmres,sizeof(KSP_LGMRES));
987:   PetscLogObjectMemory(ksp,sizeof(KSP_LGMRES));
988:   ksp->data                              = (void*)lgmres;
989:   ksp->ops->buildsolution                = KSPBuildSolution_LGMRES;

991:   ksp->ops->setup                        = KSPSetUp_LGMRES;
992:   ksp->ops->solve                        = KSPSolve_LGMRES;
993:   ksp->ops->destroy                      = KSPDestroy_LGMRES;
994:   ksp->ops->view                         = KSPView_LGMRES;
995:   ksp->ops->setfromoptions               = KSPSetFromOptions_LGMRES;
996:   ksp->ops->computeextremesingularvalues = KSPComputeExtremeSingularValues_GMRES;
997:   ksp->ops->computeeigenvalues           = KSPComputeEigenvalues_GMRES;

999:   PetscObjectComposeFunctionDynamic((PetscObject)ksp,"KSPGMRESSetPreAllocateVectors_C",
1000:                                     "KSPGMRESSetPreAllocateVectors_GMRES",
1001:                                      KSPGMRESSetPreAllocateVectors_GMRES);
1002:   PetscObjectComposeFunctionDynamic((PetscObject)ksp,"KSPGMRESSetOrthogonalization_C",
1003:                                     "KSPGMRESSetOrthogonalization_GMRES",
1004:                                      KSPGMRESSetOrthogonalization_GMRES);
1005:   PetscObjectComposeFunctionDynamic((PetscObject)ksp,"KSPGMRESSetRestart_C",
1006:                                     "KSPGMRESSetRestart_GMRES",
1007:                                      KSPGMRESSetRestart_GMRES);
1008:   PetscObjectComposeFunctionDynamic((PetscObject)ksp,"KSPGMRESSetHapTol_C",
1009:                                     "KSPGMRESSetHapTol_GMRES",
1010:                                      KSPGMRESSetHapTol_GMRES);
1011:   PetscObjectComposeFunctionDynamic((PetscObject)ksp,"KSPGMRESSetCGSRefinementType_C",
1012:                                     "KSPGMRESSetCGSRefinementType_GMRES",
1013:                                      KSPGMRESSetCGSRefinementType_GMRES);

1015:   /*LGMRES_MOD add extra functions here - like the one to set num of aug vectors */
1016:    PetscObjectComposeFunctionDynamic((PetscObject)ksp,"KSPLGMRESSetConstant_C",
1017:                                      "KSPLGMRESSetConstant_LGMRES",
1018:                                       KSPLGMRESSetConstant_LGMRES);

1020:   PetscObjectComposeFunctionDynamic((PetscObject)ksp,"KSPLGMRESSetAugDim_C",
1021:                                     "KSPLGMRESSetAugDim_LGMRES",
1022:                                      KSPLGMRESSetAugDim_LGMRES);
1023: 

1025:   /*defaults */
1026:   lgmres->haptol              = 1.0e-30;
1027:   lgmres->q_preallocate       = 0;
1028:   lgmres->delta_allocate      = LGMRES_DELTA_DIRECTIONS;
1029:   lgmres->orthog              = KSPGMRESClassicalGramSchmidtOrthogonalization;
1030:   lgmres->nrs                 = 0;
1031:   lgmres->sol_temp            = 0;
1032:   lgmres->max_k               = LGMRES_DEFAULT_MAXK;
1033:   lgmres->Rsvd                = 0;
1034:   lgmres->cgstype             = KSP_GMRES_CGS_REFINE_NEVER;
1035:   /*LGMRES_MOD - new defaults */
1036:   lgmres->aug_dim             = LGMRES_DEFAULT_AUGDIM;
1037:   lgmres->aug_ct              = 0; /* start with no aug vectors */
1038:   lgmres->approx_constant     = 0;
1039:   lgmres->matvecs             = 0;

1041:   return(0);
1042: }