Actual source code: asa.c

  2: /*  -------------------------------------------------------------------- 

  4:       Contributed by Arvid Bessen, Columbia University, June 2007
  5:      
  6:      This file implements a ASA preconditioner in PETSc as part of PC.

  8:      The adaptive smoothed aggregation algorithm is described in the paper
  9:      "Adaptive Smoothed Aggregation (ASA)", M. Brezina, R. Falgout, S. MacLachlan,
 10:      T. Manteuffel, S. McCormick, and J. Ruge, SIAM Journal on Scientific Computing,
 11:      SISC Volume 25 Issue 6, Pages 1896-1920.

 13:      For an example usage of this preconditioner, see, e.g.
 14:      $PETSC_DIR/src/ksp/ksp/examples/tutorials/ex38.c ex39.c
 15:      and other files in that directory.

 17:      This code is still somewhat experimental. A number of improvements would be
 18:      - keep vectors allocated on each level, instead of destroying them
 19:        (see mainly PCApplyVcycleOnLevel_ASA)
 20:      - in PCCreateTransferOp_ASA we get all of the submatrices at once, this could
 21:        be optimized by differentiating between local and global matrices
 22:      - the code does not handle it gracefully if there is just one level
 23:      - if relaxation is sufficient, exit of PCInitializationStage_ASA is not
 24:        completely clean
 25:      - default values could be more reasonable, especially for parallel solves,
 26:        where we need a parallel LU or similar
 27:      - the richardson scaling parameter is somewhat special, should be treated in a
 28:        good default way
 29:      - a number of parameters for smoother (sor_omega, etc.) that we store explicitly
 30:        could be kept in the respective smoothers themselves
 31:      - some parameters have to be set via command line options, there are no direct
 32:        function calls available
 33:      - numerous other stuff

 35:      Example runs in parallel would be with parameters like
 36:      mpiexec ./program -pc_asa_coarse_pc_factor_mat_solver_package mumps -pc_asa_direct_solver 200
 37:      -pc_asa_max_cand_vecs 4 -pc_asa_mu_initial 50 -pc_asa_richardson_scale 1.0
 38:      -pc_asa_rq_improve 0.9 -asa_smoother_pc_type asm -asa_smoother_sub_pc_type sor

 40:     -------------------------------------------------------------------- */

 42: /*
 43:   This defines the data structures for the smoothed aggregation procedure
 44: */
 45: #include <../src/ksp/pc/impls/asa/asa.h>
 46: #include <petscblaslapack.h>

 48: /* -------------------------------------------------------------------------- */

 50: /* Event logging */

 52: PetscLogEvent PC_InitializationStage_ASA, PC_GeneralSetupStage_ASA;
 53: PetscLogEvent PC_CreateTransferOp_ASA, PC_CreateVcycle_ASA;
 54: PetscBool  asa_events_registered = PETSC_FALSE;


 59: /*@C
 60:     PCASASetDM - Sets the coarse grid information for the grids

 62:     Collective on PC

 64:     Input Parameter:
 65: +   pc - the context
 66: -   dm - the DM object

 68:     Level: advanced

 70: @*/
 71: PetscErrorCode  PCASASetDM(PC pc,DM dm)
 72: {

 77:   PetscTryMethod(pc,"PCASASetDM_C",(PC,DM),(pc,dm));
 78:   return(0);
 79: }

 84: PetscErrorCode  PCASASetDM_ASA(PC pc, DM dm)
 85: {
 87:   PC_ASA         *asa = (PC_ASA *) pc->data;

 90:   PetscObjectReference((PetscObject)dm);
 91:   asa->dm = dm;
 92:   return(0);
 93: }

 98: /*@C
 99:     PCASASetTolerances - Sets the convergence thresholds for ASA algorithm

101:     Collective on PC

103:     Input Parameter:
104: +   pc - the context
105: .   rtol - the relative convergence tolerance
106:     (relative decrease in the residual norm)
107: .   abstol - the absolute convergence tolerance 
108:     (absolute size of the residual norm)
109: .   dtol - the divergence tolerance
110:     (amount residual can increase before KSPDefaultConverged()
111:     concludes that the method is diverging)
112: -   maxits - maximum number of iterations to use

114:     Notes:
115:     Use PETSC_DEFAULT to retain the default value of any of the tolerances.

117:     Level: advanced
118: @*/
119: PetscErrorCode  PCASASetTolerances(PC pc, PetscReal rtol, PetscReal abstol,PetscReal dtol, PetscInt maxits)
120: {

125:   PetscTryMethod(pc,"PCASASetTolerances_C",(PC,PetscReal,PetscReal,PetscReal,PetscInt),(pc,rtol,abstol,dtol,maxits));
126:   return(0);
127: }

132: PetscErrorCode  PCASASetTolerances_ASA(PC pc, PetscReal rtol, PetscReal abstol,PetscReal dtol, PetscInt maxits)
133: {
134:   PC_ASA         *asa = (PC_ASA *) pc->data;

138:   if (rtol != PETSC_DEFAULT)   asa->rtol   = rtol;
139:   if (abstol != PETSC_DEFAULT)   asa->abstol   = abstol;
140:   if (dtol != PETSC_DEFAULT)   asa->divtol = dtol;
141:   if (maxits != PETSC_DEFAULT) asa->max_it = maxits;
142:   return(0);
143: }

148: /*
149:    PCCreateLevel_ASA - Creates one level for the ASA algorithm

151:    Input Parameters:
152: +  level - current level
153: .  comm - MPI communicator object
154: .  next - pointer to next level
155: .  prev - pointer to previous level
156: .  ksptype - the KSP type for the smoothers on this level
157: -  pctype - the PC type for the smoothers on this level

159:    Output Parameters:
160: .  new_asa_lev - the newly created level

162: .keywords: ASA, create, levels, multigrid
163: */
164: PetscErrorCode  PCCreateLevel_ASA(PC_ASA_level **new_asa_lev, int level,MPI_Comm comm, PC_ASA_level *prev,
165:                                                     PC_ASA_level *next,KSPType ksptype, PCType pctype)
166: {
168:   PC_ASA_level   *asa_lev;
169: 
171:   PetscMalloc(sizeof(PC_ASA_level), &asa_lev);

173:   asa_lev->level = level;
174:   asa_lev->size  = 0;

176:   asa_lev->A = 0;
177:   asa_lev->B = 0;
178:   asa_lev->x = 0;
179:   asa_lev->b = 0;
180:   asa_lev->r = 0;
181: 
182:   asa_lev->dm           = 0;
183:   asa_lev->aggnum       = 0;
184:   asa_lev->agg          = 0;
185:   asa_lev->loc_agg_dofs = 0;
186:   asa_lev->agg_corr     = 0;
187:   asa_lev->bridge_corr  = 0;
188: 
189:   asa_lev->P = 0;
190:   asa_lev->Pt = 0;
191:   asa_lev->smP = 0;
192:   asa_lev->smPt = 0;

194:   asa_lev->comm = comm;

196:   asa_lev->smoothd = 0;
197:   asa_lev->smoothu = 0;

199:   asa_lev->prev = prev;
200:   asa_lev->next = next;
201: 
202:   *new_asa_lev = asa_lev;
203:   return(0);
204: }

208: PetscErrorCode PrintResNorm(Mat A, Vec x, Vec b, Vec r)
209: {
211:   PetscBool      destroyr = PETSC_FALSE;
212:   PetscReal      resnorm;
213:   MPI_Comm       Acomm;

216:   if (!r) {
217:     MatGetVecs(A, PETSC_NULL, &r);
218:     destroyr = PETSC_TRUE;
219:   }
220:   MatMult(A, x, r);
221:   VecAYPX(r, -1.0, b);
222:   VecNorm(r, NORM_2, &resnorm);
223:   PetscObjectGetComm((PetscObject) A, &Acomm);
224:   PetscPrintf(Acomm, "Residual norm is %f.\n", resnorm);

226:   if (destroyr) {
227:     VecDestroy(&r);
228:   }
229: 
230:   return(0);
231: }

235: PetscErrorCode PrintEnergyNormOfDiff(Mat A, Vec x, Vec y)
236: {
238:   Vec            vecdiff, Avecdiff;
239:   PetscScalar    dotprod;
240:   PetscReal      dotabs;
241:   MPI_Comm       Acomm;

244:   VecDuplicate(x, &vecdiff);
245:   VecWAXPY(vecdiff, -1.0, x, y);
246:   MatGetVecs(A, PETSC_NULL, &Avecdiff);
247:   MatMult(A, vecdiff, Avecdiff);
248:   VecDot(vecdiff, Avecdiff, &dotprod);
249:   dotabs = PetscAbsScalar(dotprod);
250:   PetscObjectGetComm((PetscObject) A, &Acomm);
251:   PetscPrintf(Acomm, "Energy norm %f.\n", dotabs);
252:   VecDestroy(&vecdiff);
253:   VecDestroy(&Avecdiff);
254:   return(0);
255: }

257: /* -------------------------------------------------------------------------- */
258: /*
259:    PCDestroyLevel_ASA - Destroys one level of the ASA preconditioner

261:    Input Parameter:
262: .  asa_lev - pointer to level that should be destroyed

264: */
267: PetscErrorCode PCDestroyLevel_ASA(PC_ASA_level *asa_lev)
268: {

272:   MatDestroy(&(asa_lev->A));
273:   MatDestroy(&(asa_lev->B));
274:   VecDestroy(&(asa_lev->x));
275:   VecDestroy(&(asa_lev->b));
276:   VecDestroy(&(asa_lev->r));

278:   if (asa_lev->dm) {DMDestroy(&asa_lev->dm);}

280:   MatDestroy(&(asa_lev->agg));
281:   PetscFree(asa_lev->loc_agg_dofs);
282:   MatDestroy(&(asa_lev->agg_corr));
283:   MatDestroy(&(asa_lev->bridge_corr));

285:   MatDestroy(&(asa_lev->P));
286:   MatDestroy(&(asa_lev->Pt));
287:   MatDestroy(&(asa_lev->smP));
288:   MatDestroy(&(asa_lev->smPt));

290:   if (asa_lev->smoothd != asa_lev->smoothu) {
291:     if (asa_lev->smoothd) {KSPDestroy(&asa_lev->smoothd);}
292:   }
293:   if (asa_lev->smoothu) {KSPDestroy(&asa_lev->smoothu);}

295:   PetscFree(asa_lev);
296:   return(0);
297: }

299: /* -------------------------------------------------------------------------- */
300: /*
301:    PCComputeSpectralRadius_ASA - Computes the spectral radius of asa_lev->A
302:    and stores it it asa_lev->spec_rad

304:    Input Parameters:
305: .  asa_lev - the level we are treating

307:    Compute spectral radius with  sqrt(||A||_1 ||A||_inf) >= ||A||_2 >= rho(A) 

309: */
312: PetscErrorCode PCComputeSpectralRadius_ASA(PC_ASA_level *asa_lev)
313: {
315:   PetscReal      norm_1, norm_inf;

318:   MatNorm(asa_lev->A, NORM_1, &norm_1);
319:   MatNorm(asa_lev->A, NORM_INFINITY, &norm_inf);
320:   asa_lev->spec_rad = PetscSqrtReal(norm_1*norm_inf);
321:   return(0);
322: }

326: PetscErrorCode PCSetRichardsonScale_ASA(KSP ksp, PetscReal spec_rad, PetscReal richardson_scale) {
328:   PC             pc;
329:   PetscBool      flg;
330:   PetscReal      spec_rad_inv;

333:   KSPSetInitialGuessNonzero(ksp, PETSC_TRUE);
334:   if (richardson_scale != PETSC_DECIDE) {
335:     KSPRichardsonSetScale(ksp, richardson_scale);
336:   } else {
337:     KSPGetPC(ksp, &pc);
338:     PetscTypeCompare((PetscObject)(pc), PCNONE, &flg);
339:     if (flg) {
340:       /* WORK: this is just an educated guess. Any number between 0 and 2/rho(A)
341:          should do. asa_lev->spec_rad has to be an upper bound on rho(A). */
342:       spec_rad_inv = 1.0/spec_rad;
343:       KSPRichardsonSetScale(ksp, spec_rad_inv);
344:     } else {
345:       SETERRQ(((PetscObject)ksp)->comm,PETSC_ERR_SUP, "Unknown PC type for smoother. Please specify scaling factor with -pc_asa_richardson_scale\n");
346:     }
347:   }
348:   return(0);
349: }

353: PetscErrorCode PCSetSORomega_ASA(PC pc, PetscReal sor_omega)
354: {

358:   PCSORSetSymmetric(pc, SOR_SYMMETRIC_SWEEP);
359:   if (sor_omega != PETSC_DECIDE) {
360:     PCSORSetOmega(pc, sor_omega);
361:   }
362:   return(0);
363: }


366: /* -------------------------------------------------------------------------- */
367: /*
368:    PCSetupSmoothersOnLevel_ASA - Creates the smoothers of the level.
369:    We assume that asa_lev->A and asa_lev->spec_rad are correctly computed

371:    Input Parameters:
372: +  asa - the data structure for the ASA preconditioner
373: .  asa_lev - the level we are treating
374: -  maxits - maximum number of iterations to use
375: */
378: PetscErrorCode PCSetupSmoothersOnLevel_ASA(PC_ASA *asa, PC_ASA_level *asa_lev, PetscInt maxits)
379: {
380:   PetscErrorCode    ierr;
381:   PetscBool         flg;
382:   PC                pc;

385:   /* destroy old smoothers */
386:   if (asa_lev->smoothu && asa_lev->smoothu != asa_lev->smoothd) {
387:     KSPDestroy(&asa_lev->smoothu);
388:   }
389:   asa_lev->smoothu = 0;
390:   if (asa_lev->smoothd) {
391:     KSPDestroy(&asa_lev->smoothd);
392:   }
393:   asa_lev->smoothd = 0;
394:   /* create smoothers */
395:   KSPCreate(asa_lev->comm,&asa_lev->smoothd);
396:   KSPSetType(asa_lev->smoothd, asa->ksptype_smooth);
397:   KSPGetPC(asa_lev->smoothd,&pc);
398:   PCSetType(pc,asa->pctype_smooth);

400:   /* set up problems for smoothers */
401:   KSPSetOperators(asa_lev->smoothd, asa_lev->A, asa_lev->A, DIFFERENT_NONZERO_PATTERN);
402:   KSPSetTolerances(asa_lev->smoothd, asa->smoother_rtol, asa->smoother_abstol, asa->smoother_dtol, maxits);
403:   PetscTypeCompare((PetscObject)(asa_lev->smoothd), KSPRICHARDSON, &flg);
404:   if (flg) {
405:     /* special parameters for certain smoothers */
406:     KSPSetInitialGuessNonzero(asa_lev->smoothd, PETSC_TRUE);
407:     KSPGetPC(asa_lev->smoothd, &pc);
408:     PetscTypeCompare((PetscObject)pc, PCSOR, &flg);
409:     if (flg) {
410:       PCSetSORomega_ASA(pc, asa->sor_omega);
411:     } else {
412:       /* just set asa->richardson_scale to get some very basic smoother */
413:       PCSetRichardsonScale_ASA(asa_lev->smoothd, asa_lev->spec_rad, asa->richardson_scale);
414:     }
415:     /* this would be the place to add support for other preconditioners */
416:   }
417:   KSPSetOptionsPrefix(asa_lev->smoothd, "asa_smoother_");
418:   KSPSetFromOptions(asa_lev->smoothd);
419:   /* set smoothu equal to smoothd, this could change later */
420:   asa_lev->smoothu = asa_lev->smoothd;
421:   return(0);
422: }

424: /* -------------------------------------------------------------------------- */
425: /*
426:    PCSetupDirectSolversOnLevel_ASA - Creates the direct solvers on the coarsest level.
427:    We assume that asa_lev->A and asa_lev->spec_rad are correctly computed

429:    Input Parameters:
430: +  asa - the data structure for the ASA preconditioner
431: .  asa_lev - the level we are treating
432: -  maxits - maximum number of iterations to use
433: */
436: PetscErrorCode PCSetupDirectSolversOnLevel_ASA(PC_ASA *asa, PC_ASA_level *asa_lev, PetscInt maxits)
437: {
438:   PetscErrorCode    ierr;
439:   PetscBool         flg;
440:   PetscMPIInt       comm_size;
441:   PC                pc;

444:   if (asa_lev->smoothu && asa_lev->smoothu != asa_lev->smoothd) {
445:     KSPDestroy(&asa_lev->smoothu);
446:   }
447:   asa_lev->smoothu = 0;
448:   if (asa_lev->smoothd) {
449:     KSPDestroy(&asa_lev->smoothd);
450:     asa_lev->smoothd = 0;
451:   }
452:   PetscStrcmp(asa->ksptype_direct, KSPPREONLY, &flg);
453:   if (flg) {
454:     PetscStrcmp(asa->pctype_direct, PCLU, &flg);
455:     if (flg) {
456:       MPI_Comm_size(asa_lev->comm, &comm_size);
457:       if (comm_size > 1) {
458:         /* the LU PC will call MatSolve, we may have to set the correct type for the matrix
459:            to have support for this in parallel */
460:         MatConvert(asa_lev->A, asa->coarse_mat_type, MAT_REUSE_MATRIX, &(asa_lev->A));
461:       }
462:     }
463:   }
464:   /* create new solvers */
465:   KSPCreate(asa_lev->comm,&asa_lev->smoothd);
466:   KSPSetType(asa_lev->smoothd, asa->ksptype_direct);
467:   KSPGetPC(asa_lev->smoothd,&pc);
468:   PCSetType(pc,asa->pctype_direct);
469:   /* set up problems for direct solvers */
470:   KSPSetOperators(asa_lev->smoothd, asa_lev->A, asa_lev->A, DIFFERENT_NONZERO_PATTERN);
471:   KSPSetTolerances(asa_lev->smoothd, asa->direct_rtol, asa->direct_abstol, asa->direct_dtol, maxits);
472:   /* user can set any option by using -pc_asa_direct_xxx */
473:   KSPSetOptionsPrefix(asa_lev->smoothd, "asa_coarse_");
474:   KSPSetFromOptions(asa_lev->smoothd);
475:   /* set smoothu equal to 0, not used */
476:   asa_lev->smoothu = 0;
477:   return(0);
478: }

480: /* -------------------------------------------------------------------------- */
481: /*
482:    PCCreateAggregates_ASA - Creates the aggregates

484:    Input Parameters:
485: .  asa_lev - the level for which we should create the projection matrix

487: */
490: PetscErrorCode PCCreateAggregates_ASA(PC_ASA_level *asa_lev)
491: {
492:   PetscInt          m,n, m_loc,n_loc;
493:   PetscInt          m_loc_s, m_loc_e;
494:   const PetscScalar one = 1.0;
495:   PetscErrorCode    ierr;

498:   /* Create nodal aggregates A_i^l */
499:   /* we use the DM grid information for that */
500:   if (asa_lev->dm) {
501:     /* coarsen DM and get the restriction matrix */
502:     DMCoarsen(asa_lev->dm, PETSC_NULL, &(asa_lev->next->dm));
503:     DMGetAggregates(asa_lev->next->dm, asa_lev->dm, &(asa_lev->agg));
504:     MatGetSize(asa_lev->agg, &m, &n);
505:     MatGetLocalSize(asa_lev->agg, &m_loc, &n_loc);
506:     if (n!=asa_lev->size) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"DM interpolation matrix has incorrect size!\n");
507:     asa_lev->next->size = m;
508:     asa_lev->aggnum     = m;
509:     /* create the correlators, right now just identity matrices */
510:     MatCreateMPIAIJ(asa_lev->comm, n_loc, n_loc, n, n, 1, PETSC_NULL, 1, PETSC_NULL,&(asa_lev->agg_corr));
511:     MatGetOwnershipRange(asa_lev->agg_corr, &m_loc_s, &m_loc_e);
512:     for (m=m_loc_s; m<m_loc_e; m++) {
513:       MatSetValues(asa_lev->agg_corr, 1, &m, 1, &m, &one, INSERT_VALUES);
514:     }
515:     MatAssemblyBegin(asa_lev->agg_corr, MAT_FINAL_ASSEMBLY);
516:     MatAssemblyEnd(asa_lev->agg_corr, MAT_FINAL_ASSEMBLY);
517: /*     MatShift(asa_lev->agg_corr, 1.0); */
518:   } else {
519:     /* somehow define the aggregates without knowing the geometry */
520:     /* future WORK */
521:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "Currently pure algebraic coarsening is not supported!");
522:   }
523:   return(0);
524: }

526: /* -------------------------------------------------------------------------- */
527: /*
528:    PCCreateTransferOp_ASA - Creates the transfer operator P_{l+1}^l for current level

530:    Input Parameters:
531: +  asa_lev - the level for which should create the transfer operator
532: -  construct_bridge - true, if we should construct a bridge operator, false for normal prolongator

534:    If we add a second, third, ... candidate vector (i.e. more than one column in B), we
535:    have to relate the additional dimensions to the original aggregates. This is done through
536:    the "aggregate correlators" agg_corr and bridge_corr.
537:    The aggregate that is used in the construction is then given by
538:    asa_lev->agg * asa_lev->agg_corr
539:    for the regular prolongator construction and
540:    asa_lev->agg * asa_lev->bridge_corr
541:    for the bridging prolongator constructions.
542: */
545: PetscErrorCode PCCreateTransferOp_ASA(PC_ASA_level *asa_lev, PetscBool  construct_bridge)
546: {

549:   const PetscReal Ca = 1e-3;
550:   PetscReal      cutoff;
551:   PetscInt       nodes_on_lev;

553:   Mat            logical_agg;
554:   PetscInt       mat_agg_loc_start, mat_agg_loc_end, mat_agg_loc_size;
555:   PetscInt       a;
556:   const PetscInt *agg = 0;
557:   PetscInt       **agg_arr = 0;

559:   IS             *idxm_is_B_arr = 0;
560:   PetscInt       *idxn_B = 0;
561:   IS             idxn_is_B, *idxn_is_B_arr = 0;

563:   Mat            *b_submat_arr = 0;

565:   PetscScalar    *b_submat = 0, *b_submat_tp = 0;
566:   PetscInt       *idxm = 0, *idxn = 0;
567:   PetscInt       cand_vecs_num;
568:   PetscInt       *cand_vec_length = 0;
569:   PetscInt       max_cand_vec_length = 0;
570:   PetscScalar    **b_orth_arr = 0;

572:   PetscInt       i,j;

574:   PetscScalar    *tau = 0, *work = 0;
575:   PetscBLASInt   info,b1,b2;

577:   PetscInt       max_cand_vecs_to_add;
578:   PetscInt       *new_loc_agg_dofs = 0;

580:   PetscInt       total_loc_cols = 0;
581:   PetscReal      norm;

583:   PetscInt       a_loc_m, a_loc_n;
584:   PetscInt       mat_loc_col_start, mat_loc_col_end, mat_loc_col_size;
585:   PetscInt       loc_agg_dofs_sum;
586:   PetscInt       row, col;
587:   PetscScalar    val;
588:   PetscMPIInt    comm_size, comm_rank;
589:   PetscInt       *loc_cols = 0;

592:   PetscLogEventBegin(PC_CreateTransferOp_ASA,0,0,0,0);

594:   MatGetSize(asa_lev->B, &nodes_on_lev, PETSC_NULL);

596:   /* If we add another candidate vector, we want to be able to judge, how much the new candidate
597:      improves our current projection operators and whether it is worth adding it.
598:      This is the precomputation necessary for implementing Notes (4.1) to (4.7).
599:      We require that all candidate vectors x stored in B are normalized such that
600:      <A x, x> = 1 and we thus do not have to compute this.
601:      For each aggregate A we can now test condition (4.5) and (4.6) by computing
602:      || quantity to check ||_{A}^2 <= cutoff * card(A)/N_l */
603:   cutoff = Ca/(asa_lev->spec_rad);

605:   /* compute logical aggregates by using the correlators */
606:   if (construct_bridge) {
607:     /* construct bridging operator */
608:     MatMatMult(asa_lev->agg, asa_lev->bridge_corr, MAT_INITIAL_MATRIX, 1.0, &logical_agg);
609:   } else {
610:     /* construct "regular" prolongator */
611:     MatMatMult(asa_lev->agg, asa_lev->agg_corr, MAT_INITIAL_MATRIX, 1.0, &logical_agg);
612:   }

614:   /* destroy correlator matrices for next level, these will be rebuilt in this routine */
615:   if (asa_lev->next) {
616:     MatDestroy(&(asa_lev->next->agg_corr));
617:     MatDestroy(&(asa_lev->next->bridge_corr));
618:   }

620:   /* find out the correct local row indices */
621:   MatGetOwnershipRange(logical_agg, &mat_agg_loc_start, &mat_agg_loc_end);
622:   mat_agg_loc_size = mat_agg_loc_end-mat_agg_loc_start;
623: 
624:   cand_vecs_num = asa_lev->cand_vecs;

626:   /* construct column indices idxn_B for reading from B */
627:   PetscMalloc(sizeof(PetscInt)*(cand_vecs_num), &idxn_B);
628:   for (i=0; i<cand_vecs_num; i++) {
629:     idxn_B[i] = i;
630:   }
631:   ISCreateGeneral(asa_lev->comm, asa_lev->cand_vecs, idxn_B,PETSC_COPY_VALUES, &idxn_is_B);
632:   PetscFree(idxn_B);
633:   PetscMalloc(sizeof(IS)*mat_agg_loc_size, &idxn_is_B_arr);
634:   for (a=0; a<mat_agg_loc_size; a++) {
635:     idxn_is_B_arr[a] = idxn_is_B;
636:   }
637:   /* allocate storage for row indices idxm_B */
638:   PetscMalloc(sizeof(IS)*mat_agg_loc_size, &idxm_is_B_arr);

640:   /* Storage for the orthogonalized  submatrices of B and their sizes */
641:   PetscMalloc(sizeof(PetscInt)*mat_agg_loc_size, &cand_vec_length);
642:   PetscMalloc(sizeof(PetscScalar*)*mat_agg_loc_size, &b_orth_arr);
643:   /* Storage for the information about each aggregate */
644:   PetscMalloc(sizeof(PetscInt*)*mat_agg_loc_size, &agg_arr);
645:   /* Storage for the number of candidate vectors that are orthonormal and used in each submatrix */
646:   PetscMalloc(sizeof(PetscInt)*mat_agg_loc_size, &new_loc_agg_dofs);

648:   /* loop over local aggregates */
649:   for (a=0; a<mat_agg_loc_size; a++) {
650:        /* get info about current aggregate, this gives the rows we have to get from B */
651:        MatGetRow(logical_agg, a+mat_agg_loc_start, &cand_vec_length[a], &agg, 0);
652:        /* copy aggregate information */
653:        PetscMalloc(sizeof(PetscInt)*cand_vec_length[a], &(agg_arr[a]));
654:        PetscMemcpy(agg_arr[a], agg, sizeof(PetscInt)*cand_vec_length[a]);
655:        /* restore row */
656:        MatRestoreRow(logical_agg, a+mat_agg_loc_start, &cand_vec_length[a], &agg, 0);
657: 
658:        /* create index sets */
659:        ISCreateGeneral(PETSC_COMM_SELF, cand_vec_length[a], agg_arr[a],PETSC_COPY_VALUES, &(idxm_is_B_arr[a]));
660:        /* maximum candidate vector length */
661:        if (cand_vec_length[a] > max_cand_vec_length) { max_cand_vec_length = cand_vec_length[a]; }
662:   }
663:   /* destroy logical_agg, no longer needed */
664:   MatDestroy(&logical_agg);

666:   /* get the entries for aggregate from B */
667:   MatGetSubMatrices(asa_lev->B, mat_agg_loc_size, idxm_is_B_arr, idxn_is_B_arr, MAT_INITIAL_MATRIX, &b_submat_arr);
668: 
669:   /* clean up all the index sets */
670:   for (a=0; a<mat_agg_loc_size; a++) { ISDestroy(&idxm_is_B_arr[a]); }
671:   PetscFree(idxm_is_B_arr);
672:   ISDestroy(&idxn_is_B);
673:   PetscFree(idxn_is_B_arr);
674: 
675:   /* storage for the values from each submatrix */
676:   PetscMalloc(sizeof(PetscScalar)*max_cand_vec_length*cand_vecs_num, &b_submat);
677:   PetscMalloc(sizeof(PetscScalar)*max_cand_vec_length*cand_vecs_num, &b_submat_tp);
678:   PetscMalloc(sizeof(PetscInt)*max_cand_vec_length, &idxm);
679:   for (i=0; i<max_cand_vec_length; i++) { idxm[i] = i; }
680:   PetscMalloc(sizeof(PetscInt)*cand_vecs_num, &idxn);
681:   for (i=0; i<cand_vecs_num; i++) { idxn[i] = i; }
682:   /* work storage for QR algorithm */
683:   PetscMalloc(sizeof(PetscScalar)*max_cand_vec_length, &tau);
684:   PetscMalloc(sizeof(PetscScalar)*cand_vecs_num, &work);

686:   /* orthogonalize all submatrices and store them in b_orth_arr */
687:   for (a=0; a<mat_agg_loc_size; a++) {
688:        /* Get the entries for aggregate from B. This is row ordered (although internally
689:           it is column ordered and we will waste some energy transposing it).
690:           WORK: use something like MatGetArray(b_submat_arr[a], &b_submat) but be really
691:           careful about all the different matrix types */
692:        MatGetValues(b_submat_arr[a], cand_vec_length[a], idxm, cand_vecs_num, idxn, b_submat);

694:        if (construct_bridge) {
695:          /* if we are constructing a bridging restriction/interpolation operator, we have
696:             to use the same number of dofs as in our previous construction */
697:          max_cand_vecs_to_add = asa_lev->loc_agg_dofs[a];
698:        } else {
699:          /* for a normal restriction/interpolation operator, we should make sure that we
700:             do not create linear dependence by accident */
701:          max_cand_vecs_to_add = PetscMin(cand_vec_length[a], cand_vecs_num);
702:        }

704:        /* We use LAPACK to compute the QR decomposition of b_submat. For LAPACK we have to
705:           transpose the matrix. We might throw out some column vectors during this process.
706:           We are keeping count of the number of column vectors that we use (and therefore the
707:           number of dofs on the lower level) in new_loc_agg_dofs[a]. */
708:        new_loc_agg_dofs[a] = 0;
709:        for (j=0; j<max_cand_vecs_to_add; j++) {
710:          /* check for condition (4.5) */
711:          norm = 0.0;
712:          for (i=0; i<cand_vec_length[a]; i++) {
713:            norm += PetscRealPart(b_submat[i*cand_vecs_num+j])*PetscRealPart(b_submat[i*cand_vecs_num+j])
714:              + PetscImaginaryPart(b_submat[i*cand_vecs_num+j])*PetscImaginaryPart(b_submat[i*cand_vecs_num+j]);
715:          }
716:          /* only add candidate vector if bigger than cutoff or first candidate */
717:          if ((!j) || (norm > cutoff*((PetscReal) cand_vec_length[a])/((PetscReal) nodes_on_lev))) {
718:            /* passed criterion (4.5), we have not implemented criterion (4.6) yet */
719:            for (i=0; i<cand_vec_length[a]; i++) {
720:              b_submat_tp[new_loc_agg_dofs[a]*cand_vec_length[a]+i] = b_submat[i*cand_vecs_num+j];
721:            }
722:            new_loc_agg_dofs[a]++;
723:          }
724:          /* #ifdef PCASA_VERBOSE */
725:          else {
726:            PetscPrintf(asa_lev->comm, "Cutoff criteria invoked\n");
727:          }
728:          /* #endif */
729:        }

731:        CHKMEMQ;
732:        /* orthogonalize b_submat_tp using the QR algorithm from LAPACK */
733:        b1 = PetscBLASIntCast(*(cand_vec_length+a));
734:        b2 = PetscBLASIntCast(*(new_loc_agg_dofs+a));
735:        LAPACKgeqrf_(&b1, &b2, b_submat_tp, &b1, tau, work, &b2, &info);
736:        if (info) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB, "LAPACKgeqrf_ LAPACK routine failed");
737: #if !defined(PETSC_MISSING_LAPACK_ORGQR) 
738:        LAPACKungqr_(&b1, &b2, &b2, b_submat_tp, &b1, tau, work, &b2, &info);
739: #else
740:        SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"ORGQR - Lapack routine is unavailable\nIf linking with ESSL you MUST also link with full LAPACK, for example\nuse ./configure with --with-blas-lib=libessl.a --with-lapack-lib=/usr/local/lib/liblapack.a'");
741: #endif
742:        if (info) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_LIB, "LAPACKungqr_ LAPACK routine failed");

744:        /* Transpose b_submat_tp and store it in b_orth_arr[a]. If we are constructing a
745:           bridging restriction/interpolation operator, we could end up with less dofs than
746:           we previously had. We fill those up with zeros. */
747:        if (!construct_bridge) {
748:          PetscMalloc(sizeof(PetscScalar)*cand_vec_length[a]*new_loc_agg_dofs[a], b_orth_arr+a);
749:          for (j=0; j<new_loc_agg_dofs[a]; j++) {
750:            for (i=0; i<cand_vec_length[a]; i++) {
751:              b_orth_arr[a][i*new_loc_agg_dofs[a]+j] = b_submat_tp[j*cand_vec_length[a]+i];
752:            }
753:          }
754:        } else {
755:          /* bridge, might have to fill up */
756:          PetscMalloc(sizeof(PetscScalar)*cand_vec_length[a]*max_cand_vecs_to_add, b_orth_arr+a);
757:          for (j=0; j<new_loc_agg_dofs[a]; j++) {
758:            for (i=0; i<cand_vec_length[a]; i++) {
759:              b_orth_arr[a][i*max_cand_vecs_to_add+j] = b_submat_tp[j*cand_vec_length[a]+i];
760:            }
761:          }
762:          for (j=new_loc_agg_dofs[a]; j<max_cand_vecs_to_add; j++) {
763:            for (i=0; i<cand_vec_length[a]; i++) {
764:              b_orth_arr[a][i*max_cand_vecs_to_add+j] = 0.0;
765:            }
766:          }
767:          new_loc_agg_dofs[a] = max_cand_vecs_to_add;
768:        }
769:        /* the number of columns in asa_lev->P that are local to this process */
770:        total_loc_cols += new_loc_agg_dofs[a];
771:   } /* end of loop over local aggregates */

773:   /* destroy the submatrices, also frees all allocated space */
774:   MatDestroyMatrices(mat_agg_loc_size, &b_submat_arr);
775:   /* destroy all other workspace */
776:   PetscFree(b_submat);
777:   PetscFree(b_submat_tp);
778:   PetscFree(idxm);
779:   PetscFree(idxn);
780:   PetscFree(tau);
781:   PetscFree(work);

783:   /* destroy old matrix P, Pt */
784:   MatDestroy(&(asa_lev->P));
785:   MatDestroy(&(asa_lev->Pt));

787:   MatGetLocalSize(asa_lev->A, &a_loc_m, &a_loc_n);

789:   /* determine local range */
790:   MPI_Comm_size(asa_lev->comm, &comm_size);
791:   MPI_Comm_rank(asa_lev->comm, &comm_rank);
792:   PetscMalloc(comm_size*sizeof(PetscInt), &loc_cols);
793:   MPI_Allgather(&total_loc_cols, 1, MPIU_INT, loc_cols, 1, MPIU_INT, asa_lev->comm);
794:   mat_loc_col_start = 0;
795:   for (i=0;i<comm_rank;i++) {
796:     mat_loc_col_start += loc_cols[i];
797:   }
798:   mat_loc_col_end = mat_loc_col_start + loc_cols[i];
799:   mat_loc_col_size = mat_loc_col_end-mat_loc_col_start;
800:   if (mat_loc_col_size != total_loc_cols) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_COR, "Local size does not match matrix size");
801:   PetscFree(loc_cols);

803:   /* we now have enough information to create asa_lev->P */
804:   MatCreateMPIAIJ(asa_lev->comm, a_loc_n,  total_loc_cols, asa_lev->size, PETSC_DETERMINE,
805:                          cand_vecs_num, PETSC_NULL, cand_vecs_num, PETSC_NULL, &(asa_lev->P));
806:   /* create asa_lev->Pt */
807:   MatCreateMPIAIJ(asa_lev->comm, total_loc_cols, a_loc_n, PETSC_DETERMINE, asa_lev->size,
808:                          max_cand_vec_length, PETSC_NULL, max_cand_vec_length, PETSC_NULL, &(asa_lev->Pt));
809:   if (asa_lev->next) {
810:     /* create correlator for aggregates of next level */
811:     MatCreateMPIAIJ(asa_lev->comm, mat_agg_loc_size, total_loc_cols, PETSC_DETERMINE, PETSC_DETERMINE,
812:                            cand_vecs_num, PETSC_NULL, cand_vecs_num, PETSC_NULL, &(asa_lev->next->agg_corr));
813:     /* create asa_lev->next->bridge_corr matrix */
814:     MatCreateMPIAIJ(asa_lev->comm, mat_agg_loc_size, total_loc_cols, PETSC_DETERMINE, PETSC_DETERMINE,
815:                            cand_vecs_num, PETSC_NULL, cand_vecs_num, PETSC_NULL, &(asa_lev->next->bridge_corr));
816:   }

818:   /* this is my own hack, but it should give the columns that we should write to */
819:   MatGetOwnershipRangeColumn(asa_lev->P, &mat_loc_col_start, &mat_loc_col_end);
820:   mat_loc_col_size = mat_loc_col_end-mat_loc_col_start;
821:   if (mat_loc_col_size != total_loc_cols) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ, "The number of local columns in asa_lev->P assigned to this processor does not match the local vector size");

823:   loc_agg_dofs_sum = 0;
824:   /* construct P, Pt, agg_corr, bridge_corr */
825:   for (a=0; a<mat_agg_loc_size; a++) {
826:     /* store b_orth_arr[a] in P */
827:     for (i=0; i<cand_vec_length[a]; i++) {
828:       row = agg_arr[a][i];
829:       for (j=0; j<new_loc_agg_dofs[a]; j++) {
830:         col = mat_loc_col_start + loc_agg_dofs_sum + j;
831:         val = b_orth_arr[a][i*new_loc_agg_dofs[a] + j];
832:         MatSetValues(asa_lev->P, 1, &row, 1, &col, &val, INSERT_VALUES);
833:         val = PetscConj(val);
834:         MatSetValues(asa_lev->Pt, 1, &col, 1, &row, &val, INSERT_VALUES);
835:       }
836:     }

838:     /* compute aggregate correlation matrices */
839:     if (asa_lev->next) {
840:       row = a+mat_agg_loc_start;
841:       for (i=0; i<new_loc_agg_dofs[a]; i++) {
842:         col = mat_loc_col_start + loc_agg_dofs_sum + i;
843:         val = 1.0;
844:         MatSetValues(asa_lev->next->agg_corr, 1, &row, 1, &col, &val, INSERT_VALUES);
845:         /* for the bridge operator we leave out the newest candidates, i.e.
846:            we set bridge_corr to 1.0 for all columns up to asa_lev->loc_agg_dofs[a] and to
847:            0.0 between asa_lev->loc_agg_dofs[a] and new_loc_agg_dofs[a] */
848:         if (!(asa_lev->loc_agg_dofs && (i >= asa_lev->loc_agg_dofs[a]))) {
849:           MatSetValues(asa_lev->next->bridge_corr, 1, &row, 1, &col, &val, INSERT_VALUES);
850:         }
851:       }
852:     }

854:     /* move to next entry point col */
855:     loc_agg_dofs_sum += new_loc_agg_dofs[a];
856:   } /* end of loop over local aggregates */

858:   MatAssemblyBegin(asa_lev->P,MAT_FINAL_ASSEMBLY);
859:   MatAssemblyEnd(asa_lev->P,MAT_FINAL_ASSEMBLY);
860:   MatAssemblyBegin(asa_lev->Pt,MAT_FINAL_ASSEMBLY);
861:   MatAssemblyEnd(asa_lev->Pt,MAT_FINAL_ASSEMBLY);
862:   if (asa_lev->next) {
863:     MatAssemblyBegin(asa_lev->next->agg_corr,MAT_FINAL_ASSEMBLY);
864:     MatAssemblyEnd(asa_lev->next->agg_corr,MAT_FINAL_ASSEMBLY);
865:     MatAssemblyBegin(asa_lev->next->bridge_corr,MAT_FINAL_ASSEMBLY);
866:     MatAssemblyEnd(asa_lev->next->bridge_corr,MAT_FINAL_ASSEMBLY);
867:   }

869:   /* if we are not constructing a bridging operator, switch asa_lev->loc_agg_dofs
870:      and new_loc_agg_dofs */
871:   if (construct_bridge) {
872:     PetscFree(new_loc_agg_dofs);
873:   } else {
874:     if (asa_lev->loc_agg_dofs) {
875:       PetscFree(asa_lev->loc_agg_dofs);
876:     }
877:     asa_lev->loc_agg_dofs = new_loc_agg_dofs;
878:   }

880:   /* clean up */
881:   for (a=0; a<mat_agg_loc_size; a++) {
882:     PetscFree(b_orth_arr[a]);
883:     PetscFree(agg_arr[a]);
884:   }
885:   PetscFree(cand_vec_length);
886:   PetscFree(b_orth_arr);
887:   PetscFree(agg_arr);

889:   PetscLogEventEnd(PC_CreateTransferOp_ASA, 0,0,0,0);
890:   return(0);
891: }

893: /* -------------------------------------------------------------------------- */
894: /*
895:    PCSmoothProlongator_ASA - Computes the smoothed prolongators I and It on the level

897:    Input Parameters:
898: .  asa_lev - the level for which the smoothed prolongator is constructed
899: */
902: PetscErrorCode PCSmoothProlongator_ASA(PC_ASA_level *asa_lev)
903: {

907:   MatDestroy(&(asa_lev->smP));
908:   MatDestroy(&(asa_lev->smPt));
909:   /* compute prolongator I_{l+1}^l = S_l P_{l+1}^l */
910:   /* step 1: compute I_{l+1}^l = A_l P_{l+1}^l */
911:   MatMatMult(asa_lev->A, asa_lev->P, MAT_INITIAL_MATRIX, 1, &(asa_lev->smP));
912:   MatMatMult(asa_lev->Pt, asa_lev->A, MAT_INITIAL_MATRIX, 1, &(asa_lev->smPt));
913:   /* step 2: shift and scale to get I_{l+1}^l = P_{l+1}^l - 4/(3/rho) A_l P_{l+1}^l */
914:   MatAYPX(asa_lev->smP, -4./(3.*(asa_lev->spec_rad)), asa_lev->P, SUBSET_NONZERO_PATTERN);
915:   MatAYPX(asa_lev->smPt, -4./(3.*(asa_lev->spec_rad)), asa_lev->Pt, SUBSET_NONZERO_PATTERN);

917:   return(0);
918: }


921: /* -------------------------------------------------------------------------- */
922: /*
923:    PCCreateVcycle_ASA - Creates the V-cycle, when aggregates are already defined

925:    Input Parameters:
926: .  asa - the preconditioner context
927: */
930: PetscErrorCode PCCreateVcycle_ASA(PC_ASA *asa)
931: {
933:   PC_ASA_level   *asa_lev, *asa_next_lev;
934:   Mat            AI;

937:   PetscLogEventBegin(PC_CreateVcycle_ASA, 0,0,0,0);

939:   if (!asa) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL, "asa pointer is NULL");
940:   if (!(asa->levellist)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL, "no levels found");
941:   asa_lev = asa->levellist;
942:   PCComputeSpectralRadius_ASA(asa_lev);
943:   PCSetupSmoothersOnLevel_ASA(asa, asa_lev, asa->nu);

945:   while(asa_lev->next) {
946:     asa_next_lev = asa_lev->next;
947:     /* (a) aggregates are already constructed */

949:     /* (b) construct B_{l+1} and P_{l+1}^l using (2.11) */
950:     /* construct P_{l+1}^l */
951:     PCCreateTransferOp_ASA(asa_lev, PETSC_FALSE);

953:     /* construct B_{l+1} */
954:     MatDestroy(&(asa_next_lev->B));
955:     MatMatMult(asa_lev->Pt, asa_lev->B, MAT_INITIAL_MATRIX, 1, &(asa_next_lev->B));
956:     asa_next_lev->cand_vecs = asa_lev->cand_vecs;

958:     /* (c) construct smoothed prolongator */
959:     PCSmoothProlongator_ASA(asa_lev);
960: 
961:     /* (d) construct coarse matrix */
962:     /* Define coarse matrix A_{l+1} = (I_{l+1}^l)^T A_l I_{l+1}^l */
963:     MatDestroy(&(asa_next_lev->A));
964:        MatMatMult(asa_lev->A, asa_lev->smP, MAT_INITIAL_MATRIX, 1.0, &AI);
965:      MatMatMult(asa_lev->smPt, AI, MAT_INITIAL_MATRIX, 1.0, &(asa_next_lev->A));
966:      MatDestroy(&AI);
967:     /*     MatPtAP(asa_lev->A, asa_lev->smP, MAT_INITIAL_MATRIX, 1, &(asa_next_lev->A)); */
968:     MatGetSize(asa_next_lev->A, PETSC_NULL, &(asa_next_lev->size));
969:     PCComputeSpectralRadius_ASA(asa_next_lev);
970:     PCSetupSmoothersOnLevel_ASA(asa, asa_next_lev, asa->nu);
971:     /* create corresponding vectors x_{l+1}, b_{l+1}, r_{l+1} */
972:     VecDestroy(&(asa_next_lev->x));
973:     VecDestroy(&(asa_next_lev->b));
974:     VecDestroy(&(asa_next_lev->r));
975:     MatGetVecs(asa_next_lev->A, &(asa_next_lev->x), &(asa_next_lev->b));
976:     MatGetVecs(asa_next_lev->A, PETSC_NULL, &(asa_next_lev->r));

978:     /* go to next level */
979:     asa_lev = asa_lev->next;
980:   } /* end of while loop over the levels */
981:   /* asa_lev now points to the coarsest level, set up direct solver there */
982:   PCComputeSpectralRadius_ASA(asa_lev);
983:   PCSetupDirectSolversOnLevel_ASA(asa, asa_lev, asa->nu);

985:   PetscLogEventEnd(PC_CreateVcycle_ASA, 0,0,0,0);
986:   return(0);
987: }

989: /* -------------------------------------------------------------------------- */
990: /*
991:    PCAddCandidateToB_ASA - Inserts a candidate vector in B

993:    Input Parameters:
994: +  B - the matrix to insert into
995: .  col_idx - the column we should insert to
996: .  x - the vector to insert
997: -  A - system matrix

999:    Function will insert normalized x into B, such that <A x, x> = 1
1000:    (x itself is not changed). If B is projected down then this property
1001:    is kept. If <A_l x_l, x_l> = 1 and the next level is defined by
1002:    x_{l+1} = Pt x_l  and  A_{l+1} = Pt A_l P then
1003:    <A_{l+1} x_{l+1}, x_l> = <Pt A_l P Pt x_l, Pt x_l>
1004:    = <A_l P Pt x_l, P Pt x_l> = <A_l x_l, x_l> = 1
1005:    because of the definition of P in (2.11).
1006: */
1009: PetscErrorCode PCAddCandidateToB_ASA(Mat B, PetscInt col_idx, Vec x, Mat A)
1010: {
1012:   Vec            Ax;
1013:   PetscScalar    dotprod;
1014:   PetscReal      norm;
1015:   PetscInt       i, loc_start, loc_end;
1016:   PetscScalar    val, *vecarray;

1019:   MatGetVecs(A, PETSC_NULL, &Ax);
1020:   MatMult(A, x, Ax);
1021:   VecDot(Ax, x, &dotprod);
1022:   norm = PetscSqrtReal(PetscAbsScalar(dotprod));
1023:   VecGetOwnershipRange(x, &loc_start, &loc_end);
1024:   VecGetArray(x, &vecarray);
1025:   for (i=loc_start; i<loc_end; i++) {
1026:     val = vecarray[i-loc_start]/norm;
1027:     MatSetValues(B, 1, &i, 1, &col_idx, &val, INSERT_VALUES);
1028:   }
1029:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1030:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1031:   VecRestoreArray(x, &vecarray);
1032:   VecDestroy(&Ax);
1033:   return(0);
1034: }

1036: /* -------------------------------------------------------------------------- */
1037: /*
1038: -  x - a starting guess for a hard to approximate vector, if PETSC_NULL, will be generated
1039: */
1042: PetscErrorCode PCInitializationStage_ASA(PC_ASA *asa, Vec x)
1043: {
1045:   PetscInt       l;
1046:   PC_ASA_level   *asa_lev, *asa_next_lev;
1047:   PetscRandom    rctx;     /* random number generator context */

1049:   Vec            ax;
1050:   PetscScalar    tmp;
1051:   PetscReal      prevnorm, norm;

1053:   PetscBool      skip_steps_f_i = PETSC_FALSE;
1054:   PetscBool      sufficiently_coarsened = PETSC_FALSE;

1056:   PetscInt       vec_size, vec_loc_size;
1057:   PetscInt       loc_vec_low, loc_vec_high;
1058:   PetscInt       i,j;

1060: /*   Vec            xhat = 0; */

1062:   Mat            AI;

1064:   Vec            cand_vec, cand_vec_new;
1065:   PetscBool      isrichardson;
1066:   PC             coarse_pc;

1069:   PetscLogEventBegin(PC_InitializationStage_ASA,0,0,0,0);
1070:   l=1;
1071:   /* create first level */
1072:   PCCreateLevel_ASA(&(asa->levellist), l, asa->comm, 0, 0, asa->ksptype_smooth, asa->pctype_smooth);
1073:   asa_lev = asa->levellist;

1075:   /* Set matrix */
1076:   asa_lev->A = asa->A;
1077:   MatGetSize(asa_lev->A, &i, &j);
1078:   asa_lev->size = i;
1079:   PCComputeSpectralRadius_ASA(asa_lev);
1080:   PCSetupSmoothersOnLevel_ASA(asa, asa_lev, asa->mu_initial);

1082:   /* Set DM */
1083:   asa_lev->dm = asa->dm;
1084:   PetscObjectReference((PetscObject)asa->dm);

1086:   PetscPrintf(asa_lev->comm, "Initialization stage\n");

1088:   if (x) {
1089:     /* use starting guess */
1090:     VecDestroy(&(asa_lev->x));
1091:     VecDuplicate(x, &(asa_lev->x));
1092:     VecCopy(x, asa_lev->x);
1093:   } else {
1094:     /* select random starting vector */
1095:     VecDestroy(&(asa_lev->x));
1096:     MatGetVecs(asa_lev->A, &(asa_lev->x), 0);
1097:     PetscRandomCreate(asa_lev->comm,&rctx);
1098:     PetscRandomSetFromOptions(rctx);
1099:     VecSetRandom(asa_lev->x, rctx);
1100:     PetscRandomDestroy(&rctx);
1101:   }

1103:   /* create right hand side */
1104:   VecDestroy(&(asa_lev->b));
1105:   MatGetVecs(asa_lev->A, &(asa_lev->b), 0);
1106:   VecSet(asa_lev->b, 0.0);

1108:   /* relax and check whether that's enough already */
1109:   /* compute old norm */
1110:   MatGetVecs(asa_lev->A, 0, &ax);
1111:   MatMult(asa_lev->A, asa_lev->x, ax);
1112:   VecDot(asa_lev->x, ax, &tmp);
1113:   prevnorm = PetscAbsScalar(tmp);
1114:   PetscPrintf(asa_lev->comm, "Residual norm of starting guess: %f\n", prevnorm);

1116:   /* apply mu_initial relaxations */
1117:   KSPSolve(asa_lev->smoothd, asa_lev->b, asa_lev->x);
1118:   /* compute new norm */
1119:   MatMult(asa_lev->A, asa_lev->x, ax);
1120:   VecDot(asa_lev->x, ax, &tmp);
1121:   norm = PetscAbsScalar(tmp);
1122:   VecDestroy(&(ax));
1123:   PetscPrintf(asa_lev->comm, "Residual norm of relaxation after %g %D relaxations: %g %g\n", asa->epsilon,asa->mu_initial, norm,prevnorm);

1125:   /* Check if it already converges by itself */
1126:   if (norm/prevnorm <= pow(asa->epsilon, asa->mu_initial)) {
1127:     /* converges by relaxation alone */
1128:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP, "Relaxation should be sufficient to treat this problem. "
1129:             "Use relaxation or decrease epsilon with -pc_asa_epsilon");
1130:   } else {
1131:     /* set the number of relaxations to asa->mu from asa->mu_initial */
1132:     PCSetupSmoothersOnLevel_ASA(asa, asa_lev, asa->mu);

1134:     /* Let's do some multigrid ! */
1135:     sufficiently_coarsened = PETSC_FALSE;

1137:     /* do the whole initialization stage loop */
1138:     while (!sufficiently_coarsened) {
1139:       PetscPrintf(asa_lev->comm, "Initialization stage: creating level %D\n", asa_lev->level+1);

1141:       /* (a) Set candidate matrix B_l = x_l */
1142:       /* get the correct vector sizes and data */
1143:       VecGetSize(asa_lev->x, &vec_size);
1144:       VecGetOwnershipRange(asa_lev->x, &loc_vec_low, &loc_vec_high);
1145:       vec_loc_size = loc_vec_high - loc_vec_low;

1147:       /* create matrix for candidates */
1148:       MatCreateMPIDense(asa_lev->comm, vec_loc_size, PETSC_DECIDE, vec_size, asa->max_cand_vecs, PETSC_NULL, &(asa_lev->B));
1149:       /* set the first column */
1150:       PCAddCandidateToB_ASA(asa_lev->B, 0, asa_lev->x, asa_lev->A);
1151:       asa_lev->cand_vecs = 1;

1153:       /* create next level */
1154:       PCCreateLevel_ASA(&(asa_lev->next), asa_lev->level+1,  asa_lev->comm, asa_lev, PETSC_NULL, asa->ksptype_smooth, asa->pctype_smooth);
1155:       asa_next_lev = asa_lev->next;

1157:       /* (b) Create nodal aggregates A_i^l */
1158:       PCCreateAggregates_ASA(asa_lev);
1159: 
1160:       /* (c) Define tentatative prolongator P_{l+1}^l and candidate matrix B_{l+1}
1161:              using P_{l+1}^l B_{l+1} = B_l and (P_{l+1}^l)^T P_{l+1}^l = I */
1162:       PCCreateTransferOp_ASA(asa_lev, PETSC_FALSE);

1164:       /* future WORK: set correct fill ratios for all the operations below */
1165:       MatMatMult(asa_lev->Pt, asa_lev->B, MAT_INITIAL_MATRIX, 1, &(asa_next_lev->B));
1166:       asa_next_lev->cand_vecs = asa_lev->cand_vecs;

1168:       /* (d) Define prolongator I_{l+1}^l = S_l P_{l+1}^l */
1169:       PCSmoothProlongator_ASA(asa_lev);

1171:       /* (e) Define coarse matrix A_{l+1} = (I_{l+1}^l)^T A_l I_{l+1}^l */
1172:             MatMatMult(asa_lev->A, asa_lev->smP, MAT_INITIAL_MATRIX, 1.0, &AI);
1173:       MatMatMult(asa_lev->smPt, AI, MAT_INITIAL_MATRIX, 1.0, &(asa_next_lev->A));
1174:       MatDestroy(&AI);
1175:       /*      MatPtAP(asa_lev->A, asa_lev->smP, MAT_INITIAL_MATRIX, 1, &(asa_next_lev->A)); */
1176:       MatGetSize(asa_next_lev->A, PETSC_NULL, &(asa_next_lev->size));
1177:       PCComputeSpectralRadius_ASA(asa_next_lev);
1178:       PCSetupSmoothersOnLevel_ASA(asa, asa_next_lev, asa->mu);

1180:       /* coarse enough for direct solver? */
1181:       MatGetSize(asa_next_lev->A, &i, &j);
1182:       if (PetscMax(i,j) <= asa->direct_solver) {
1183:         PetscPrintf(asa_lev->comm, "Level %D can be treated directly.\n"
1184:                            "Algorithm will use %D levels.\n", asa_next_lev->level,
1185:                            asa_next_lev->level);
1186:         break; /* go to step 5 */
1187:       }

1189:       if (!skip_steps_f_i) {
1190:         /* (f) Set x_{l+1} = B_{l+1}, we just compute it again */
1191:         VecDestroy(&(asa_next_lev->x));
1192:         MatGetVecs(asa_lev->P, &(asa_next_lev->x), 0);
1193:         MatMult(asa_lev->Pt, asa_lev->x, asa_next_lev->x);

1195: /*         /\* (g) Make copy \hat{x}_{l+1} = x_{l+1} *\/ */
1196: /*         VecDuplicate(asa_next_lev->x, &xhat); */
1197: /*         VecCopy(asa_next_lev->x, xhat); */
1198: 
1199:         /* Create b_{l+1} */
1200:         VecDestroy(&(asa_next_lev->b));
1201:         MatGetVecs(asa_next_lev->A, &(asa_next_lev->b), 0);
1202:         VecSet(asa_next_lev->b, 0.0);

1204:         /* (h) Relax mu times on A_{l+1} x = 0 */
1205:         /* compute old norm */
1206:         MatGetVecs(asa_next_lev->A, 0, &ax);
1207:         MatMult(asa_next_lev->A, asa_next_lev->x, ax);
1208:         VecDot(asa_next_lev->x, ax, &tmp);
1209:         prevnorm = PetscAbsScalar(tmp);
1210:         PetscPrintf(asa_next_lev->comm, "Residual norm of starting guess on level %D: %f\n", asa_next_lev->level, prevnorm);
1211:         /* apply mu relaxations: WORK, make sure that mu is set correctly */
1212:         KSPSolve(asa_next_lev->smoothd, asa_next_lev->b, asa_next_lev->x);
1213:         /* compute new norm */
1214:         MatMult(asa_next_lev->A, asa_next_lev->x, ax);
1215:         VecDot(asa_next_lev->x, ax, &tmp);
1216:         norm = PetscAbsScalar(tmp);
1217:         VecDestroy(&(ax));
1218:         PetscPrintf(asa_next_lev->comm, "Residual norm after Richardson iteration  on level %D: %f\n", asa_next_lev->level, norm);
1219:         /* (i) Check if it already converges by itself */
1220:         if (norm/prevnorm <= pow(asa->epsilon, asa->mu)) {
1221:           /* relaxation reduces error sufficiently */
1222:           skip_steps_f_i = PETSC_TRUE;
1223:         }
1224:       }
1225:       /* (j) go to next coarser level */
1226:       l++;
1227:       asa_lev = asa_next_lev;
1228:     }
1229:     /* Step 5. */
1230:     asa->levels = asa_next_lev->level; /* WORK: correct? */

1232:     /* Set up direct solvers on coarsest level */
1233:     if (asa_next_lev->smoothd != asa_next_lev->smoothu) {
1234:       if (asa_next_lev->smoothu) { KSPDestroy(&asa_next_lev->smoothu); }
1235:     }
1236:     KSPSetType(asa_next_lev->smoothd, asa->ksptype_direct);
1237:     PetscTypeCompare((PetscObject)(asa_next_lev->smoothd), KSPRICHARDSON, &isrichardson);
1238:     if (isrichardson) {
1239:       KSPSetInitialGuessNonzero(asa_next_lev->smoothd, PETSC_TRUE);
1240:     } else {
1241:       KSPSetInitialGuessNonzero(asa_next_lev->smoothd, PETSC_FALSE);
1242:     }
1243:     KSPGetPC(asa_next_lev->smoothd, &coarse_pc);
1244:     PCSetType(coarse_pc, asa->pctype_direct);
1245:     asa_next_lev->smoothu = asa_next_lev->smoothd;
1246:     PCSetupDirectSolversOnLevel_ASA(asa, asa_next_lev, asa->nu);

1248:     /* update finest-level candidate matrix B_1 = I_2^1 I_3^2 ... I_{L-1}^{L-2} x_{L-1} */
1249:     if (!asa_lev->prev) {
1250:       /* just one relaxation level */
1251:       VecDuplicate(asa_lev->x, &cand_vec);
1252:       VecCopy(asa_lev->x, cand_vec);
1253:     } else {
1254:       /* interpolate up the chain */
1255:       cand_vec = asa_lev->x;
1256:       asa_lev->x = 0;
1257:       while(asa_lev->prev) {
1258:         /* interpolate to higher level */
1259:         MatGetVecs(asa_lev->prev->smP, 0, &cand_vec_new);
1260:         MatMult(asa_lev->prev->smP, cand_vec, cand_vec_new);
1261:         VecDestroy(&(cand_vec));
1262:         cand_vec = cand_vec_new;
1263: 
1264:         /* destroy all working vectors on the way */
1265:         VecDestroy(&(asa_lev->x));
1266:         VecDestroy(&(asa_lev->b));

1268:         /* move to next higher level */
1269:         asa_lev = asa_lev->prev;
1270:       }
1271:     }
1272:     /* set the first column of B1 */
1273:     PCAddCandidateToB_ASA(asa_lev->B, 0, cand_vec, asa_lev->A);
1274:     VecDestroy(&(cand_vec));

1276:     /* Step 6. Create V-cycle */
1277:     PCCreateVcycle_ASA(asa);
1278:   }
1279:   PetscLogEventEnd(PC_InitializationStage_ASA,0,0,0,0);
1280:   return(0);
1281: }

1283: /* -------------------------------------------------------------------------- */
1284: /*
1285:    PCApplyVcycleOnLevel_ASA - Applies current V-cycle

1287:    Input Parameters:
1288: +  asa_lev - the current level we should recurse on
1289: -  gamma - the number of recursive cycles we should run

1291: */
1294: PetscErrorCode PCApplyVcycleOnLevel_ASA(PC_ASA_level *asa_lev, PetscInt gamma)
1295: {
1297:   PC_ASA_level   *asa_next_lev;
1298:   PetscInt       g;

1301:   if (!asa_lev) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL, "Level is empty in PCApplyVcycleOnLevel_ASA");
1302:   asa_next_lev = asa_lev->next;

1304:   if (asa_next_lev) {
1305:     /* 1. Presmoothing */
1306:     KSPSolve(asa_lev->smoothd, asa_lev->b, asa_lev->x);
1307:     /* 2. Coarse grid corrections */
1308: /*     MatGetVecs(asa_lev->A, 0, &tmp); */
1309: /*     MatGetVecs(asa_lev->smP, &(asa_next_lev->b), 0); */
1310: /*     MatGetVecs(asa_next_lev->A, &(asa_next_lev->x), 0); */
1311:     for (g=0; g<gamma; g++) {
1312:       /* (a) get coarsened b_{l+1} = (I_{l+1}^l)^T (b_l - A_l x_l) */
1313:       MatMult(asa_lev->A, asa_lev->x, asa_lev->r);
1314:       VecAYPX(asa_lev->r, -1.0, asa_lev->b);
1315:       MatMult(asa_lev->smPt, asa_lev->r, asa_next_lev->b);

1317:       /* (b) Set x_{l+1} = 0 and recurse */
1318:       VecSet(asa_next_lev->x, 0.0);
1319:       PCApplyVcycleOnLevel_ASA(asa_next_lev, gamma);

1321:       /* (c) correct solution x_l = x_l + I_{l+1}^l x_{l+1} */
1322:       MatMultAdd(asa_lev->smP, asa_next_lev->x, asa_lev->x, asa_lev->x);
1323:     }
1324: /*     VecDestroy(&(asa_lev->r)); */
1325: /*     /\* discard x_{l+1}, b_{l+1} *\/ */
1326: /*     VecDestroy(&(asa_next_lev->x)); */
1327: /*     VecDestroy(&(asa_next_lev->b)); */
1328: 
1329:     /* 3. Postsmoothing */
1330:     KSPSolve(asa_lev->smoothu, asa_lev->b, asa_lev->x);
1331:   } else {
1332:     /* Base case: solve directly */
1333:     KSPSolve(asa_lev->smoothd, asa_lev->b, asa_lev->x);
1334:   }
1335:   return(0);
1336: }


1339: /* -------------------------------------------------------------------------- */
1340: /*
1341:    PCGeneralSetupStage_ASA - Applies the ASA preconditioner to a vector. Algorithm
1342:                              4 from the ASA paper

1344:    Input Parameters:
1345: +  asa - the data structure for the ASA algorithm
1346: -  cand - a possible candidate vector, if PETSC_NULL, will be constructed randomly

1348:    Output Parameters:
1349: .  cand_added - PETSC_TRUE, if new candidate vector added, PETSC_FALSE otherwise
1350: */
1353: PetscErrorCode PCGeneralSetupStage_ASA(PC_ASA *asa, Vec cand, PetscBool  *cand_added)
1354: {
1356:   PC_ASA_level   *asa_lev, *asa_next_lev;

1358:   PetscRandom    rctx;     /* random number generator context */
1359:   PetscReal      r;
1360:   PetscScalar    rs;
1361:   PetscBool      nd_fast;

1363:   Vec            ax;
1364:   PetscScalar    tmp;
1365:   PetscReal      norm, prevnorm = 0.0;
1366:   PetscInt       c;

1368:   PetscInt       loc_vec_low, loc_vec_high;
1369:   PetscInt       i;

1371:   PetscBool      skip_steps_d_j = PETSC_FALSE;

1373:   PetscInt       *idxm, *idxn;
1374:   PetscScalar    *v;

1376:   Mat            AI;

1378:   Vec            cand_vec, cand_vec_new;

1381:   *cand_added = PETSC_FALSE;
1382: 
1383:   asa_lev = asa->levellist;
1384:   if (asa_lev == 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL, "No levels found in PCGeneralSetupStage_ASA");
1385:   asa_next_lev = asa_lev->next;
1386:   if (asa_next_lev == 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL, "Just one level, not implemented yet");
1387: 
1388:   PetscPrintf(asa_lev->comm, "General setup stage\n");

1390:   PetscLogEventBegin(PC_GeneralSetupStage_ASA,0,0,0,0);

1392:   /* 1. If max. dof per node on level 2 equals K, stop */
1393:   if (asa_next_lev->cand_vecs >= asa->max_dof_lev_2) {
1394:     PetscPrintf(PETSC_COMM_WORLD,
1395:                        "Maximum dof on level 2 reached: %D\n"
1396:                        "Consider increasing this limit by setting it with -pc_asa_max_dof_lev_2\n",
1397:                        asa->max_dof_lev_2);
1398:     return(0);
1399:   }

1401:   /* 2. Create copy of B_1 (skipped, we just replace the last column in step 8.) */
1402: 
1403:   if (!cand) {
1404:     /* 3. Select a random x_1 */
1405:     VecDestroy(&(asa_lev->x));
1406:     MatGetVecs(asa_lev->A, &(asa_lev->x), 0);
1407:     PetscRandomCreate(asa_lev->comm,&rctx);
1408:     PetscRandomSetFromOptions(rctx);
1409:     VecGetOwnershipRange(asa_lev->x, &loc_vec_low, &loc_vec_high);
1410:     for (i=loc_vec_low; i<loc_vec_high; i++) {
1411:       PetscRandomGetValueReal(rctx, &r);
1412:       rs = r;
1413:       VecSetValues(asa_lev->x, 1, &i, &rs, INSERT_VALUES);
1414:     }
1415:     VecAssemblyBegin(asa_lev->x);
1416:     VecAssemblyEnd(asa_lev->x);
1417:     PetscRandomDestroy(&rctx);
1418:   } else {
1419:     VecDestroy(&(asa_lev->x));
1420:     VecDuplicate(cand, &(asa_lev->x));
1421:     VecCopy(cand, asa_lev->x);
1422:   }

1424:   /* create right hand side */
1425:   VecDestroy(&(asa_lev->b));
1426:   MatGetVecs(asa_lev->A, &(asa_lev->b), 0);
1427:   VecSet(asa_lev->b, 0.0);
1428: 
1429:   /* Apply mu iterations of current V-cycle */
1430:   nd_fast = PETSC_FALSE;
1431:   MatGetVecs(asa_lev->A, 0, &ax);
1432:   for (c=0; c<asa->mu; c++) {
1433:     PCApplyVcycleOnLevel_ASA(asa_lev, asa->gamma);
1434: 
1435:     MatMult(asa_lev->A, asa_lev->x, ax);
1436:     VecDot(asa_lev->x, ax, &tmp);
1437:     norm = PetscAbsScalar(tmp);
1438:     if (c>0) {
1439:       if (norm/prevnorm < asa->epsilon) {
1440:         nd_fast = PETSC_TRUE;
1441:         break;
1442:       }
1443:     }
1444:     prevnorm = norm;
1445:   }
1446:   VecDestroy(&(ax));

1448:   /* 4. If energy norm decreases sufficiently fast, then stop */
1449:   if (nd_fast) {
1450:     PetscPrintf(asa_lev->comm, "nd_fast is true\n");
1451:     return(0);
1452:   }

1454:   /* 5. Update B_1, by adding new column x_1 */
1455:   if (asa_lev->cand_vecs >= asa->max_cand_vecs) {
1456:     SETERRQ(PETSC_COMM_SELF,PETSC_ERR_MEM, "Number of candidate vectors will exceed allocated storage space");
1457:   } else {
1458:     PetscPrintf(asa_lev->comm, "Adding candidate vector %D\n", asa_lev->cand_vecs+1);
1459:   }
1460:   PCAddCandidateToB_ASA(asa_lev->B, asa_lev->cand_vecs, asa_lev->x, asa_lev->A);
1461:   *cand_added = PETSC_TRUE;
1462:   asa_lev->cand_vecs++;

1464:   /* 6. loop over levels */
1465:   while(asa_next_lev && asa_next_lev->next) {
1466:     PetscPrintf(asa_lev->comm, "General setup stage: processing level %D\n", asa_next_lev->level);
1467:     /* (a) define B_{l+1} and P_{l+1}^L */
1468:     /* construct P_{l+1}^l */
1469:     PCCreateTransferOp_ASA(asa_lev, PETSC_FALSE);

1471:     /* construct B_{l+1} */
1472:     MatDestroy(&(asa_next_lev->B));
1473:     MatMatMult(asa_lev->Pt, asa_lev->B, MAT_INITIAL_MATRIX, 1.0, &(asa_next_lev->B));
1474:     /* do not increase asa_next_lev->cand_vecs until step (j) */
1475: 
1476:     /* (b) construct prolongator I_{l+1}^l = S_l P_{l+1}^l */
1477:     PCSmoothProlongator_ASA(asa_lev);
1478: 
1479:     /* (c) construct coarse matrix A_{l+1} = (I_{l+1}^l)^T A_l I_{l+1}^l */
1480:     MatDestroy(&(asa_next_lev->A));
1481:        MatMatMult(asa_lev->A, asa_lev->smP, MAT_INITIAL_MATRIX, 1.0, &AI);
1482:     MatMatMult(asa_lev->smPt, AI, MAT_INITIAL_MATRIX, 1.0, &(asa_next_lev->A));
1483:     MatDestroy(&AI);
1484:                                  /* MatPtAP(asa_lev->A, asa_lev->smP, MAT_INITIAL_MATRIX, 1, &(asa_next_lev->A)); */
1485:     MatGetSize(asa_next_lev->A, PETSC_NULL, &(asa_next_lev->size));
1486:     PCComputeSpectralRadius_ASA(asa_next_lev);
1487:     PCSetupSmoothersOnLevel_ASA(asa, asa_next_lev, asa->mu);

1489:     if (! skip_steps_d_j) {
1490:       /* (d) get vector x_{l+1} from last column in B_{l+1} */
1491:       VecDestroy(&(asa_next_lev->x));
1492:       MatGetVecs(asa_next_lev->B, 0, &(asa_next_lev->x));

1494:       VecGetOwnershipRange(asa_next_lev->x, &loc_vec_low, &loc_vec_high);
1495:       PetscMalloc(sizeof(PetscInt)*(loc_vec_high-loc_vec_low), &idxm);
1496:       for (i=loc_vec_low; i<loc_vec_high; i++)
1497:         idxm[i-loc_vec_low] = i;
1498:       PetscMalloc(sizeof(PetscInt)*1, &idxn);
1499:       idxn[0] = asa_next_lev->cand_vecs;

1501:       PetscMalloc(sizeof(PetscScalar)*(loc_vec_high-loc_vec_low), &v);
1502:       MatGetValues(asa_next_lev->B, loc_vec_high-loc_vec_low, idxm, 1, idxn, v);

1504:       VecSetValues(asa_next_lev->x, loc_vec_high-loc_vec_low, idxm, v, INSERT_VALUES);
1505:       VecAssemblyBegin(asa_next_lev->x);
1506:       VecAssemblyEnd(asa_next_lev->x);

1508:       PetscFree(v);
1509:       PetscFree(idxm);
1510:       PetscFree(idxn);
1511: 
1512:       /* (e) create bridge transfer operator P_{l+2}^{l+1}, by using the previously
1513:          computed candidates */
1514:       PCCreateTransferOp_ASA(asa_next_lev, PETSC_TRUE);

1516:       /* (f) construct bridging prolongator I_{l+2}^{l+1} = S_{l+1} P_{l+2}^{l+1} */
1517:       PCSmoothProlongator_ASA(asa_next_lev);

1519:       /* (g) compute <A_{l+1} x_{l+1}, x_{l+1}> and save it */
1520:       MatGetVecs(asa_next_lev->A, 0, &ax);
1521:       MatMult(asa_next_lev->A, asa_next_lev->x, ax);
1522:       VecDot(asa_next_lev->x, ax, &tmp);
1523:       prevnorm = PetscAbsScalar(tmp);
1524:       VecDestroy(&(ax));

1526:       /* (h) apply mu iterations of current V-cycle */
1527:       /* set asa_next_lev->b */
1528:       VecDestroy(&(asa_next_lev->b));
1529:       VecDestroy(&(asa_next_lev->r));
1530:       MatGetVecs(asa_next_lev->A, &(asa_next_lev->b), &(asa_next_lev->r));
1531:       VecSet(asa_next_lev->b, 0.0);
1532:       /* apply V-cycle */
1533:       for (c=0; c<asa->mu; c++) {
1534:         PCApplyVcycleOnLevel_ASA(asa_next_lev, asa->gamma);
1535:       }

1537:       /* (i) check convergence */
1538:       /* compute <A_{l+1} x_{l+1}, x_{l+1}> and save it */
1539:       MatGetVecs(asa_next_lev->A, 0, &ax);
1540:       MatMult(asa_next_lev->A, asa_next_lev->x, ax);
1541:       VecDot(asa_next_lev->x, ax, &tmp);
1542:       norm = PetscAbsScalar(tmp);
1543:       VecDestroy(&(ax));

1545:       if (norm/prevnorm <= pow(asa->epsilon, asa->mu)) skip_steps_d_j = PETSC_TRUE;
1546: 
1547:       /* (j) update candidate B_{l+1} */
1548:       PCAddCandidateToB_ASA(asa_next_lev->B, asa_next_lev->cand_vecs, asa_next_lev->x, asa_next_lev->A);
1549:       asa_next_lev->cand_vecs++;
1550:     }
1551:     /* go to next level */
1552:     asa_lev = asa_lev->next;
1553:     asa_next_lev = asa_next_lev->next;
1554:   }

1556:   /* 7. update the fine-level candidate */
1557:   if (! asa_lev->prev) {
1558:     /* just one coarsening level */
1559:     VecDuplicate(asa_lev->x, &cand_vec);
1560:     VecCopy(asa_lev->x, cand_vec);
1561:   } else {
1562:     cand_vec = asa_lev->x;
1563:     asa_lev->x = 0;
1564:     while(asa_lev->prev) {
1565:       /* interpolate to higher level */
1566:       MatGetVecs(asa_lev->prev->smP, 0, &cand_vec_new);
1567:       MatMult(asa_lev->prev->smP, cand_vec, cand_vec_new);
1568:       VecDestroy(&(cand_vec));
1569:       cand_vec = cand_vec_new;

1571:       /* destroy all working vectors on the way */
1572:       VecDestroy(&(asa_lev->x));
1573:       VecDestroy(&(asa_lev->b));

1575:       /* move to next higher level */
1576:       asa_lev = asa_lev->prev;
1577:     }
1578:   }
1579:   /* 8. update B_1 by setting the last column of B_1 */
1580:   PCAddCandidateToB_ASA(asa_lev->B, asa_lev->cand_vecs-1, cand_vec, asa_lev->A);
1581:   VecDestroy(&(cand_vec));

1583:   /* 9. create V-cycle */
1584:   PCCreateVcycle_ASA(asa);
1585: 
1586:   PetscLogEventEnd(PC_GeneralSetupStage_ASA,0,0,0,0);
1587:   return(0);
1588: }

1590: /* -------------------------------------------------------------------------- */
1591: /*
1592:    PCConstructMultigrid_ASA - creates the multigrid preconditionier, this is a fairly
1593:    involved process, which runs extensive testing to compute good candidate vectors

1595:    Input Parameters:
1596: .  pc - the preconditioner context

1598:  */
1601: PetscErrorCode PCConstructMultigrid_ASA(PC pc)
1602: {
1604:   PC_ASA         *asa = (PC_ASA*)pc->data;
1605:   PC_ASA_level   *asa_lev;
1606:   PetscInt       i, ls, le;
1607:   PetscScalar    *d;
1608:   PetscBool      zeroflag = PETSC_FALSE;
1609:   PetscReal      rnorm, rnorm_start;
1610:   PetscReal      rq, rq_prev;
1611:   PetscScalar    rq_nom, rq_denom;
1612:   PetscBool      cand_added;
1613:   PetscRandom    rctx;


1617:   /* check if we should scale with diagonal */
1618:   if (asa->scale_diag) {
1619:     /* Get diagonal scaling factors */
1620:     MatGetVecs(pc->pmat,&(asa->invsqrtdiag),0);
1621:     MatGetDiagonal(pc->pmat,asa->invsqrtdiag);
1622:     /* compute (inverse) sqrt of diagonal */
1623:     VecGetOwnershipRange(asa->invsqrtdiag, &ls, &le);
1624:     VecGetArray(asa->invsqrtdiag, &d);
1625:     for (i=0; i<le-ls; i++) {
1626:       if (d[i] == 0.0) {
1627:         d[i]     = 1.0;
1628:         zeroflag = PETSC_TRUE;
1629:       } else {
1630:         d[i] = 1./PetscSqrtReal(PetscAbsScalar(d[i]));
1631:       }
1632:     }
1633:     VecRestoreArray(asa->invsqrtdiag,&d);
1634:     VecAssemblyBegin(asa->invsqrtdiag);
1635:     VecAssemblyEnd(asa->invsqrtdiag);
1636:     if (zeroflag) {
1637:       PetscInfo(pc,"Zero detected in diagonal of matrix, using 1 at those locations\n");
1638:     }
1639: 
1640:     /* scale the matrix and store it: D^{-1/2} A D^{-1/2} */
1641:     MatDuplicate(pc->pmat, MAT_COPY_VALUES, &(asa->A)); /* probably inefficient */
1642:     MatDiagonalScale(asa->A, asa->invsqrtdiag, asa->invsqrtdiag);
1643:   } else {
1644:     /* don't scale */
1645:     asa->A = pc->pmat;
1646:   }
1647:   /* Initialization stage */
1648:   PCInitializationStage_ASA(asa, PETSC_NULL);
1649: 
1650:   /* get first level */
1651:   asa_lev = asa->levellist;

1653:   PetscRandomCreate(asa->comm,&rctx);
1654:   PetscRandomSetFromOptions(rctx);
1655:   VecSetRandom(asa_lev->x,rctx);

1657:   /* compute starting residual */
1658:   VecDestroy(&(asa_lev->r));
1659:   MatGetVecs(asa_lev->A, PETSC_NULL, &(asa_lev->r));
1660:   MatMult(asa_lev->A, asa_lev->x, asa_lev->r);
1661:   /* starting residual norm */
1662:   VecNorm(asa_lev->r, NORM_2, &rnorm_start);
1663:   /* compute Rayleigh quotients */
1664:   VecDot(asa_lev->x, asa_lev->r, &rq_nom);
1665:   VecDot(asa_lev->x, asa_lev->x, &rq_denom);
1666:   rq_prev = PetscAbsScalar(rq_nom / rq_denom);

1668:   /* check if we have to add more candidates */
1669:   for (i=0; i<asa->max_it; i++) {
1670:     if (asa_lev->cand_vecs >= asa->max_cand_vecs) {
1671:       /* reached limit for candidate vectors */
1672:       break;
1673:     }
1674:     /* apply V-cycle */
1675:     PCApplyVcycleOnLevel_ASA(asa_lev, asa->gamma);
1676:     /* check convergence */
1677:     MatMult(asa_lev->A, asa_lev->x, asa_lev->r);
1678:     VecNorm(asa_lev->r, NORM_2, &rnorm);
1679:     PetscPrintf(asa->comm, "After %D iterations residual norm is %f\n", i+1, rnorm);
1680:     if (rnorm < rnorm_start*(asa->rtol) || rnorm < asa->abstol) {
1681:       /* convergence */
1682:       break;
1683:     }
1684:     /* compute new Rayleigh quotient */
1685:     VecDot(asa_lev->x, asa_lev->r, &rq_nom);
1686:     VecDot(asa_lev->x, asa_lev->x, &rq_denom);
1687:     rq = PetscAbsScalar(rq_nom / rq_denom);
1688:     PetscPrintf(asa->comm, "After %D iterations Rayleigh quotient of residual is %f\n", i+1, rq);
1689:     /* test Rayleigh quotient decrease and add more candidate vectors if necessary */
1690:     if (i && (rq > asa->rq_improve*rq_prev)) {
1691:       /* improve interpolation by adding another candidate vector */
1692:       PCGeneralSetupStage_ASA(asa, asa_lev->r, &cand_added);
1693:       if (!cand_added) {
1694:         /* either too many candidates for storage or cycle is already effective */
1695:         PetscPrintf(asa->comm, "either too many candidates for storage or cycle is already effective\n");
1696:         break;
1697:       }
1698:       VecSetRandom(asa_lev->x, rctx);
1699:       rq_prev = rq*10000.; /* give the new V-cycle some grace period */
1700:     } else {
1701:       rq_prev = rq;
1702:     }
1703:   }

1705:   VecDestroy(&(asa_lev->x));
1706:   VecDestroy(&(asa_lev->b));
1707:   PetscRandomDestroy(&rctx);
1708:   asa->multigrid_constructed = PETSC_TRUE;
1709:   return(0);
1710: }

1712: /* -------------------------------------------------------------------------- */
1713: /*
1714:    PCApply_ASA - Applies the ASA preconditioner to a vector.

1716:    Input Parameters:
1717: .  pc - the preconditioner context
1718: .  x - input vector

1720:    Output Parameter:
1721: .  y - output vector

1723:    Application Interface Routine: PCApply()
1724:  */
1727: PetscErrorCode PCApply_ASA(PC pc,Vec x,Vec y)
1728: {
1729:   PC_ASA         *asa = (PC_ASA*)pc->data;
1730:   PC_ASA_level   *asa_lev;

1735:   if (!asa->multigrid_constructed) {
1736:     PCConstructMultigrid_ASA(pc);
1737:   }

1739:   /* get first level */
1740:   asa_lev = asa->levellist;

1742:   /* set the right hand side */
1743:   VecDuplicate(x, &(asa->b));
1744:   VecCopy(x, asa->b);
1745:   /* set starting vector */
1746:   VecDestroy(&(asa->x));
1747:   MatGetVecs(asa->A, &(asa->x), PETSC_NULL);
1748:   VecSet(asa->x, 0.0);
1749: 
1750:   /* set vectors */
1751:   asa_lev->x = asa->x;
1752:   asa_lev->b = asa->b;

1754:   PCApplyVcycleOnLevel_ASA(asa_lev, asa->gamma);
1755: 
1756:   /* Return solution */
1757:   VecCopy(asa->x, y);

1759:   /* delete working vectors */
1760:   VecDestroy(&(asa->x));
1761:   VecDestroy(&(asa->b));
1762:   asa_lev->x = PETSC_NULL;
1763:   asa_lev->b = PETSC_NULL;

1765:   return(0);
1766: }

1768: /* -------------------------------------------------------------------------- */
1769: /*
1770:    PCApplyRichardson_ASA - Applies the ASA iteration to solve a linear system

1772:    Input Parameters:
1773: .  pc - the preconditioner context
1774: .  b - the right hand side

1776:    Output Parameter:
1777: .  x - output vector

1779:   DOES NOT WORK!!!!!

1781:  */
1784: PetscErrorCode PCApplyRichardson_ASA(PC pc,Vec b,Vec x,Vec w,PetscReal rtol,PetscReal abstol, PetscReal dtol,PetscInt its,PetscBool  guesszero,PetscInt *outits,PCRichardsonConvergedReason *reason)
1785: {
1786:   PC_ASA         *asa = (PC_ASA*)pc->data;
1787:   PC_ASA_level   *asa_lev;
1788:   PetscInt       i;
1789:   PetscReal      rnorm, rnorm_start;

1794:   if (! asa->multigrid_constructed) {
1795:     PCConstructMultigrid_ASA(pc);
1796:   }

1798:   /* get first level */
1799:   asa_lev = asa->levellist;

1801:   /* set the right hand side */
1802:   VecDuplicate(b, &(asa->b));
1803:   if (asa->scale_diag) {
1804:     VecPointwiseMult(asa->b, asa->invsqrtdiag, b);
1805:   } else {
1806:     VecCopy(b, asa->b);
1807:   }
1808:   /* set starting vector */
1809:   VecDuplicate(x, &(asa->x));
1810:   VecCopy(x, asa->x);
1811: 
1812:   /* compute starting residual */
1813:   VecDestroy(&(asa->r));
1814:   MatGetVecs(asa->A, &(asa->r), PETSC_NULL);
1815:   MatMult(asa->A, asa->x, asa->r);
1816:   VecAYPX(asa->r, -1.0, asa->b);
1817:   /* starting residual norm */
1818:   VecNorm(asa->r, NORM_2, &rnorm_start);

1820:   /* set vectors */
1821:   asa_lev->x = asa->x;
1822:   asa_lev->b = asa->b;

1824:   *reason = PCRICHARDSON_CONVERGED_ITS;
1825:   /* **************** Full algorithm loop *********************************** */
1826:   for (i=0; i<its; i++) {
1827:     /* apply V-cycle */
1828:     PCApplyVcycleOnLevel_ASA(asa_lev, asa->gamma);
1829:     /* check convergence */
1830:     MatMult(asa->A, asa->x, asa->r);
1831:     VecAYPX(asa->r, -1.0, asa->b);
1832:     VecNorm(asa->r, NORM_2, &rnorm);
1833:     PetscPrintf(asa->comm, "After %D iterations residual norm is %f\n", i+1, rnorm);
1834:     if (rnorm < rnorm_start*(rtol)) {
1835:       *reason = PCRICHARDSON_CONVERGED_RTOL;
1836:       break;
1837:     } else if (rnorm < asa->abstol) {
1838:       *reason = PCRICHARDSON_CONVERGED_ATOL;
1839:       break;
1840:     } else if (rnorm > rnorm_start*(dtol)) {
1841:       *reason = PCRICHARDSON_DIVERGED_DTOL;
1842:       break;
1843:     }
1844:   }
1845:   *outits = i;
1846: 
1847:   /* Return solution */
1848:   if (asa->scale_diag) {
1849:     VecPointwiseMult(x, asa->x, asa->invsqrtdiag);
1850:   } else {
1851:     VecCopy(x, asa->x);
1852:   }

1854:   /* delete working vectors */
1855:   VecDestroy(&(asa->x));
1856:   VecDestroy(&(asa->b));
1857:   VecDestroy(&(asa->r));
1858:   asa_lev->x = PETSC_NULL;
1859:   asa_lev->b = PETSC_NULL;
1860:   return(0);
1861: }

1863: /* -------------------------------------------------------------------------- */
1864: /*
1865:    PCDestroy_ASA - Destroys the private context for the ASA preconditioner
1866:    that was created with PCCreate_ASA().

1868:    Input Parameter:
1869: .  pc - the preconditioner context

1871:    Application Interface Routine: PCDestroy()
1872: */
1875: static PetscErrorCode PCDestroy_ASA(PC pc)
1876: {
1877:   PC_ASA         *asa;
1878:   PC_ASA_level   *asa_lev;
1879:   PC_ASA_level   *asa_next_level;

1884:   asa = (PC_ASA*)pc->data;
1885:   asa_lev = asa->levellist;

1887:   /* Delete top level data */
1888:   PetscFree(asa->ksptype_smooth);
1889:   PetscFree(asa->pctype_smooth);
1890:   PetscFree(asa->ksptype_direct);
1891:   PetscFree(asa->pctype_direct);
1892:   PetscFree(asa->coarse_mat_type);

1894:   /* this is destroyed by the levels below  */
1895: /*   MatDestroy(&(asa->A)); */
1896:   VecDestroy(&(asa->invsqrtdiag));
1897:   VecDestroy(&(asa->b));
1898:   VecDestroy(&(asa->x));
1899:   VecDestroy(&(asa->r));

1901:   if (asa->dm) {DMDestroy(&asa->dm);}

1903:   /* Destroy each of the levels */
1904:   while(asa_lev) {
1905:     asa_next_level = asa_lev->next;
1906:     PCDestroyLevel_ASA(asa_lev);
1907:     asa_lev = asa_next_level;
1908:   }

1910:   PetscFree(asa);
1911:   return(0);
1912: }

1916: static PetscErrorCode PCSetFromOptions_ASA(PC pc)
1917: {
1918:   PC_ASA         *asa = (PC_ASA*)pc->data;
1919:   PetscBool      flg;
1921:   char           type[20];


1926:   PetscOptionsHead("ASA options");
1927:   /* convergence parameters */
1928:   PetscOptionsInt("-pc_asa_nu","Number of cycles to run smoother","No manual page yet",asa->nu,&(asa->nu),&flg);
1929:   PetscOptionsInt("-pc_asa_gamma","Number of cycles to run coarse grid correction","No manual page yet",asa->gamma,&(asa->gamma),&flg);
1930:   PetscOptionsReal("-pc_asa_epsilon","Tolerance for the relaxation method","No manual page yet",asa->epsilon,&(asa->epsilon),&flg);
1931:   PetscOptionsInt("-pc_asa_mu","Number of cycles to relax in setup stages","No manual page yet",asa->mu,&(asa->mu),&flg);
1932:   PetscOptionsInt("-pc_asa_mu_initial","Number of cycles to relax for generating first candidate vector","No manual page yet",asa->mu_initial,&(asa->mu_initial),&flg);
1933:   PetscOptionsInt("-pc_asa_direct_solver","For which matrix size should we use the direct solver?","No manual page yet",asa->direct_solver,&(asa->direct_solver),&flg);
1934:   PetscOptionsBool("-pc_asa_scale_diag","Should we scale the matrix with the inverse of its diagonal?","No manual page yet",asa->scale_diag,&(asa->scale_diag),&flg);
1935:   /* type of smoother used */
1936:   PetscOptionsList("-pc_asa_smoother_ksp_type","The type of KSP to be used in the smoothers","No manual page yet",KSPList,asa->ksptype_smooth,type,20,&flg);
1937:   if (flg) {
1938:     PetscFree(asa->ksptype_smooth);
1939:     PetscStrallocpy(type,&(asa->ksptype_smooth));
1940:   }
1941:   PetscOptionsList("-pc_asa_smoother_pc_type","The type of PC to be used in the smoothers","No manual page yet",PCList,asa->pctype_smooth,type,20,&flg);
1942:   if (flg) {
1943:     PetscFree(asa->pctype_smooth);
1944:     PetscStrallocpy(type,&(asa->pctype_smooth));
1945:   }
1946:   PetscOptionsList("-pc_asa_direct_ksp_type","The type of KSP to be used in the direct solver","No manual page yet",KSPList,asa->ksptype_direct,type,20,&flg);
1947:   if (flg) {
1948:     PetscFree(asa->ksptype_direct);
1949:     PetscStrallocpy(type,&(asa->ksptype_direct));
1950:   }
1951:   PetscOptionsList("-pc_asa_direct_pc_type","The type of PC to be used in the direct solver","No manual page yet",PCList,asa->pctype_direct,type,20,&flg);
1952:   if (flg) {
1953:     PetscFree(asa->pctype_direct);
1954:     PetscStrallocpy(type,&(asa->pctype_direct));
1955:   }
1956:   /* options specific for certain smoothers */
1957:   PetscOptionsReal("-pc_asa_richardson_scale","Scaling parameter for preconditioning in relaxation, if smoothing KSP is Richardson","No manual page yet",asa->richardson_scale,&(asa->richardson_scale),&flg);
1958:   PetscOptionsReal("-pc_asa_sor_omega","Scaling parameter for preconditioning in relaxation, if smoothing KSP is Richardson","No manual page yet",asa->sor_omega,&(asa->sor_omega),&flg);
1959:   /* options for direct solver */
1960:   PetscOptionsString("-pc_asa_coarse_mat_type","The coarse level matrix type (e.g. SuperLU, MUMPS, ...)","No manual page yet",asa->coarse_mat_type, type,20,&flg);
1961:   if (flg) {
1962:     PetscFree(asa->coarse_mat_type);
1963:     PetscStrallocpy(type,&(asa->coarse_mat_type));
1964:   }
1965:   /* storage allocation parameters */
1966:   PetscOptionsInt("-pc_asa_max_cand_vecs","Maximum number of candidate vectors","No manual page yet",asa->max_cand_vecs,&(asa->max_cand_vecs),&flg);
1967:   PetscOptionsInt("-pc_asa_max_dof_lev_2","The maximum number of degrees of freedom per node on level 2 (K in paper)","No manual page yet",asa->max_dof_lev_2,&(asa->max_dof_lev_2),&flg);
1968:   /* construction parameters */
1969:   PetscOptionsReal("-pc_asa_rq_improve","Threshold in RQ improvement for adding another candidate","No manual page yet",asa->rq_improve,&(asa->rq_improve),&flg);
1970:   PetscOptionsTail();
1971:   return(0);
1972: }

1976: static PetscErrorCode PCView_ASA(PC pc,PetscViewer viewer)
1977: {
1978:   PC_ASA          *asa = (PC_ASA*)pc->data;
1980:   PetscBool      iascii;
1981:   PC_ASA_level   *asa_lev = asa->levellist;

1984:   PetscTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1985:   if (iascii) {
1986:     PetscViewerASCIIPrintf(viewer,"  ASA:\n");
1987:     asa_lev = asa->levellist;
1988:     while (asa_lev) {
1989:       if (!asa_lev->next) {
1990:         PetscViewerASCIIPrintf(viewer,"Coarse grid solver -- level %D -------------------------------\n",0);
1991:       } else {
1992:         PetscViewerASCIIPrintf(viewer,"Down solver (pre-smoother) on level ? -------------------------------\n");
1993:       }
1994:       PetscViewerASCIIPushTab(viewer);
1995:       KSPView(asa_lev->smoothd,viewer);
1996:       PetscViewerASCIIPopTab(viewer);
1997:       if (asa_lev->next && asa_lev->smoothd == asa_lev->smoothu) {
1998:         PetscViewerASCIIPrintf(viewer,"Up solver (post-smoother) same as down solver (pre-smoother)\n");
1999:       } else if (asa_lev->next){
2000:         PetscViewerASCIIPrintf(viewer,"Up solver (post-smoother) on level ? -------------------------------\n");
2001:         PetscViewerASCIIPushTab(viewer);
2002:         KSPView(asa_lev->smoothu,viewer);
2003:         PetscViewerASCIIPopTab(viewer);
2004:       }
2005:       asa_lev = asa_lev->next;
2006:     }
2007:   } else {
2008:     SETERRQ1(((PetscObject)pc)->comm,PETSC_ERR_SUP,"Viewer type %s not supported for PCASA",((PetscObject)viewer)->type_name);
2009:   }
2010:   return(0);
2011: }

2013: /* -------------------------------------------------------------------------- */
2014: /*
2015:    PCCreate_ASA - Creates a ASA preconditioner context, PC_ASA, 
2016:    and sets this as the private data within the generic preconditioning 
2017:    context, PC, that was created within PCCreate().

2019:    Input Parameter:
2020: .  pc - the preconditioner context

2022:    Application Interface Routine: PCCreate()
2023: */
2027: PetscErrorCode  PCCreate_ASA(PC pc)
2028: {
2030:   PC_ASA         *asa;


2035:   /*
2036:       Set the pointers for the functions that are provided above.
2037:       Now when the user-level routines (such as PCApply(), PCDestroy(), etc.)
2038:       are called, they will automatically call these functions.  Note we
2039:       choose not to provide a couple of these functions since they are
2040:       not needed.
2041:   */
2042:   pc->ops->apply               = PCApply_ASA;
2043:   /*  pc->ops->applytranspose      = PCApply_ASA;*/
2044:   pc->ops->applyrichardson     = PCApplyRichardson_ASA;
2045:   pc->ops->setup               = 0;
2046:   pc->ops->destroy             = PCDestroy_ASA;
2047:   pc->ops->setfromoptions      = PCSetFromOptions_ASA;
2048:   pc->ops->view                = PCView_ASA;

2050:   /* Set the data to pointer to 0 */
2051:   pc->data                = (void*)0;

2053:   PetscObjectComposeFunctionDynamic((PetscObject)pc,"PCASASetDM_C","PCASASetDM_ASA",PCASASetDM_ASA);
2054:   PetscObjectComposeFunctionDynamic((PetscObject)pc,"PCASASetTolerances_C","PCASASetTolerances_ASA",PCASASetTolerances_ASA);

2056:   /* register events */
2057:   if (! asa_events_registered) {
2058:     PetscLogEventRegister("PCInitializationStage_ASA", PC_CLASSID,&PC_InitializationStage_ASA);
2059:     PetscLogEventRegister("PCGeneralSetupStage_ASA",   PC_CLASSID,&PC_GeneralSetupStage_ASA);
2060:     PetscLogEventRegister("PCCreateTransferOp_ASA",    PC_CLASSID,&PC_CreateTransferOp_ASA);
2061:     PetscLogEventRegister("PCCreateVcycle_ASA",        PC_CLASSID,&PC_CreateVcycle_ASA);
2062:     asa_events_registered = PETSC_TRUE;
2063:   }

2065:   /* Create new PC_ASA object */
2066:   PetscNewLog(pc,PC_ASA,&asa);
2067:   pc->data = (void*)asa;

2069:   /* WORK: find some better initial values  */
2070:   asa->nu             = 3;
2071:   asa->gamma          = 1;
2072:   asa->epsilon        = 1e-4;
2073:   asa->mu             = 3;
2074:   asa->mu_initial     = 20;
2075:   asa->direct_solver  = 100;
2076:   asa->scale_diag     = PETSC_TRUE;
2077:   PetscStrallocpy(KSPRICHARDSON, (char **) &(asa->ksptype_smooth));
2078:   PetscStrallocpy(PCSOR, (char **) &(asa->pctype_smooth));
2079:   asa->smoother_rtol    = 1e-10;
2080:   asa->smoother_abstol  = 1e-20;
2081:   asa->smoother_dtol    = PETSC_DEFAULT;
2082:   PetscStrallocpy(KSPPREONLY, (char **) &(asa->ksptype_direct));
2083:   PetscStrallocpy(PCREDUNDANT, (char **) &(asa->pctype_direct));
2084:   asa->direct_rtol      = 1e-10;
2085:   asa->direct_abstol    = 1e-20;
2086:   asa->direct_dtol      = PETSC_DEFAULT;
2087:   asa->richardson_scale = PETSC_DECIDE;
2088:   asa->sor_omega        = PETSC_DECIDE;
2089:   PetscStrallocpy(MATSAME, (char **) &(asa->coarse_mat_type));

2091:   asa->max_cand_vecs    = 4;
2092:   asa->max_dof_lev_2    = 640; /* I don't think this parameter really matters, 640 should be enough for everyone! */

2094:   asa->multigrid_constructed = PETSC_FALSE;

2096:   asa->rtol       = 1e-10;
2097:   asa->abstol     = 1e-15;
2098:   asa->divtol     = 1e5;
2099:   asa->max_it     = 10000;
2100:   asa->rq_improve = 0.9;
2101: 
2102:   asa->A           = 0;
2103:   asa->invsqrtdiag = 0;
2104:   asa->b           = 0;
2105:   asa->x           = 0;
2106:   asa->r           = 0;

2108:   asa->dm = 0;
2109: 
2110:   asa->levels    = 0;
2111:   asa->levellist = 0;

2113:   asa->comm = ((PetscObject)pc)->comm;
2114:   return(0);
2115: }