xref: /petsc/src/ksp/pc/impls/gamg/gamg.c (revision ea5d4fccf296dd2bbd0f9c3a3343651cb1066da7)
1 /*
2  GAMG geometric-algebric multigrid PC - Mark Adams 2011
3  */
4 #include "private/matimpl.h"
5 #include <../src/ksp/pc/impls/gamg/gamg.h>           /*I "petscpc.h" I*/
6 #include <private/kspimpl.h>
7 
8 #if defined PETSC_USE_LOG
9 PetscLogEvent gamg_setup_events[NUM_SET];
10 #endif
11 #define GAMG_MAXLEVELS 30
12 
13 /* #define GAMG_STAGES */
14 #if (defined PETSC_USE_LOG && defined GAMG_STAGES)
15 static PetscLogStage gamg_stages[GAMG_MAXLEVELS];
16 #endif
17 
18 static PetscFList GAMGList = 0;
19 
20 /* ----------------------------------------------------------------------------- */
21 #undef __FUNCT__
22 #define __FUNCT__ "PCReset_GAMG"
23 PetscErrorCode PCReset_GAMG(PC pc)
24 {
25   PetscErrorCode  ierr;
26   PC_MG           *mg = (PC_MG*)pc->data;
27   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
28 
29   PetscFunctionBegin;
30   if( pc_gamg->data != 0 ) { /* this should not happen, cleaned up in SetUp */
31     ierr = PetscFree(pc_gamg->data); CHKERRQ(ierr);
32   }
33   pc_gamg->data = 0; pc_gamg->data_sz = 0;
34   PetscFunctionReturn(0);
35 }
36 
37 /* -------------------------------------------------------------------------- */
38 /*
39    createLevel: create coarse op with RAP.  repartition and/or reduce number
40      of active processors.
41 
42    Input Parameter:
43    . pc - parameters
44    . Amat_fine - matrix on this fine (k) level
45    . cbs - coarse block size
46    . isLast -
47    In/Output Parameter:
48    . a_P_inout - prolongation operator to the next level (k-1)
49    . a_nactive_proc - number of active procs
50    Output Parameter:
51    . a_Amat_crs - coarse matrix that is created (k-1)
52 */
53 
54 #undef __FUNCT__
55 #define __FUNCT__ "createLevel"
56 PetscErrorCode createLevel( const PC pc,
57                             const Mat Amat_fine,
58                             const PetscInt cbs,
59                             const PetscBool isLast,
60                             Mat *a_P_inout,
61                             PetscMPIInt *a_nactive_proc,
62                             Mat *a_Amat_crs
63                             )
64 {
65   PC_MG           *mg = (PC_MG*)pc->data;
66   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
67   const PetscBool  repart = pc_gamg->repart;
68   const PetscInt   min_eq_proc = pc_gamg->min_eq_proc, coarse_max = pc_gamg->coarse_eq_limit;
69   PetscErrorCode   ierr;
70   Mat              Cmat,Pnew,Pold=*a_P_inout;
71   IS               new_indices,isnum;
72   MPI_Comm         wcomm = ((PetscObject)Amat_fine)->comm;
73   PetscMPIInt      mype,npe,new_npe,nactive = *a_nactive_proc;
74   PetscInt         neq,NN,Istart,Iend,Istart0,Iend0,ncrs_new,ncrs0,rfactor;
75 
76   PetscFunctionBegin;
77   ierr = MPI_Comm_rank( wcomm, &mype ); CHKERRQ(ierr);
78   ierr = MPI_Comm_size( wcomm, &npe );  CHKERRQ(ierr);
79 
80   /* RAP */
81 #ifdef USE_R
82   /* make R wih brute force for now */
83   ierr = MatTranspose( Pold, Pnew );
84   ierr = MatDestroy( &Pold );  CHKERRQ(ierr);
85   ierr = MatRARt( Amat_fine, Pnew, MAT_INITIAL_MATRIX, 2.0, &Cmat ); CHKERRQ(ierr);
86   Pold = Pnew;
87 #else
88   ierr = MatPtAP( Amat_fine, Pold, MAT_INITIAL_MATRIX, 2.0, &Cmat ); CHKERRQ(ierr);
89 #endif
90   ierr = MatSetBlockSize( Cmat, cbs );      CHKERRQ(ierr);
91   ierr = MatGetOwnershipRange( Cmat, &Istart0, &Iend0 ); CHKERRQ(ierr);
92   ncrs0 = (Iend0-Istart0)/cbs; assert((Iend0-Istart0)%cbs == 0);
93 
94   /* get number of PEs to make active, reduce */
95   ierr = MatGetSize( Cmat, &neq, &NN );  CHKERRQ(ierr);
96   new_npe = (PetscMPIInt)((float)neq/(float)min_eq_proc + 0.5); /* hardwire min. number of eq/proc */
97   if( new_npe == 0 || neq < coarse_max ) new_npe = 1;
98   else if (new_npe >= nactive ) new_npe = nactive; /* no change, rare */
99   if( isLast ) new_npe = 1;
100 
101   if( !repart && new_npe==nactive ) {
102     *a_Amat_crs = Cmat; /* output - no repartitioning or reduction */
103   }
104   else {
105     /* Repartition Cmat_{k} and move colums of P^{k}_{k-1} and coordinates accordingly */
106     const PetscInt *idx,ndata_rows=pc_gamg->data_cell_rows,ndata_cols=pc_gamg->data_cell_cols,data_sz=ndata_rows*ndata_cols;
107     const PetscInt  stride0=ncrs0*pc_gamg->data_cell_rows;
108     PetscInt        *counts,is_sz,*newproc_idx,ii,jj,kk,strideNew,*tidx,inpe,targetPE;
109     IS              isnewproc;
110     VecScatter      vecscat;
111     PetscScalar    *array;
112     Vec             src_crd, dest_crd;
113     IS              isscat;
114 
115     ierr = PetscMalloc( npe*sizeof(PetscInt), &counts ); CHKERRQ(ierr);
116 #if defined PETSC_USE_LOG
117       ierr = PetscLogEventBegin(gamg_setup_events[SET12],0,0,0,0);CHKERRQ(ierr);
118 #endif
119     if( repart ) {
120       /* create sub communicator  */
121       Mat             adj;
122 
123       if (pc_gamg->verbose) PetscPrintf(wcomm,"\t[%d]%s repartition: npe (active): %d --> %d, neq = %d\n",mype,__FUNCT__,*a_nactive_proc,new_npe,neq);
124 
125       /* MatPartitioningApply call MatConvert, which is collective */
126       if( cbs == 1 ) {
127 	ierr = MatConvert( Cmat, MATMPIADJ, MAT_INITIAL_MATRIX, &adj );   CHKERRQ(ierr);
128       }
129       else{
130 	/* make a scalar matrix to partition */
131 	Mat tMat;
132 	PetscInt ncols,jj,Ii;
133 	const PetscScalar *vals;
134 	const PetscInt *idx;
135 	PetscInt *d_nnz, *o_nnz;
136 	static PetscInt llev = 0;
137 
138 	ierr = PetscMalloc( ncrs0*sizeof(PetscInt), &d_nnz ); CHKERRQ(ierr);
139 	ierr = PetscMalloc( ncrs0*sizeof(PetscInt), &o_nnz ); CHKERRQ(ierr);
140 	for ( Ii = Istart0, jj = 0 ; Ii < Iend0 ; Ii += cbs, jj++ ) {
141 	  ierr = MatGetRow(Cmat,Ii,&ncols,0,0); CHKERRQ(ierr);
142 	  d_nnz[jj] = ncols/cbs;
143 	  o_nnz[jj] = ncols/cbs;
144 	  ierr = MatRestoreRow(Cmat,Ii,&ncols,0,0); CHKERRQ(ierr);
145 	  if( d_nnz[jj] > ncrs0 ) d_nnz[jj] = ncrs0;
146 	  if( o_nnz[jj] > (neq/cbs-ncrs0) ) o_nnz[jj] = neq/cbs-ncrs0;
147 	}
148 
149 	ierr = MatCreateAIJ( wcomm, ncrs0, ncrs0,
150                              PETSC_DETERMINE, PETSC_DETERMINE,
151                              0, d_nnz, 0, o_nnz,
152                              &tMat );
153 	CHKERRQ(ierr);
154 	ierr = PetscFree( d_nnz ); CHKERRQ(ierr);
155 	ierr = PetscFree( o_nnz ); CHKERRQ(ierr);
156 
157 	for ( ii = Istart0; ii < Iend0; ii++ ) {
158 	  PetscInt dest_row = ii/cbs;
159 	  ierr = MatGetRow(Cmat,ii,&ncols,&idx,&vals); CHKERRQ(ierr);
160 	  for( jj = 0 ; jj < ncols ; jj++ ){
161 	    PetscInt dest_col = idx[jj]/cbs;
162 	    PetscScalar v = 1.0;
163 	    ierr = MatSetValues(tMat,1,&dest_row,1,&dest_col,&v,ADD_VALUES); CHKERRQ(ierr);
164 	  }
165 	  ierr = MatRestoreRow(Cmat,ii,&ncols,&idx,&vals); CHKERRQ(ierr);
166 	}
167 	ierr = MatAssemblyBegin(tMat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
168 	ierr = MatAssemblyEnd(tMat,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
169 
170 	if( llev++ == -1 ) {
171 	  PetscViewer viewer; char fname[32];
172 	  sprintf(fname,"part_mat_%d.mat",llev);
173 	  PetscViewerBinaryOpen(wcomm,fname,FILE_MODE_WRITE,&viewer);
174 	  ierr = MatView( tMat, viewer ); CHKERRQ(ierr);
175 	  ierr = PetscViewerDestroy( &viewer );
176 	}
177 
178 	ierr = MatConvert( tMat, MATMPIADJ, MAT_INITIAL_MATRIX, &adj );   CHKERRQ(ierr);
179 
180 	ierr = MatDestroy( &tMat );  CHKERRQ(ierr);
181       }
182 
183       { /* partition: get newproc_idx, set is_sz */
184 	char prefix[256];
185 	const char *pcpre;
186 	const PetscInt *is_idx;
187 	MatPartitioning  mpart;
188 	IS proc_is;
189 
190 	ierr = MatPartitioningCreate( wcomm, &mpart ); CHKERRQ(ierr);
191 	ierr = MatPartitioningSetAdjacency( mpart, adj ); CHKERRQ(ierr);
192 	ierr = PCGetOptionsPrefix( pc, &pcpre );CHKERRQ(ierr);
193 	ierr = PetscSNPrintf(prefix,sizeof prefix,"%spc_gamg_",pcpre?pcpre:"");CHKERRQ(ierr);
194 	ierr = PetscObjectSetOptionsPrefix((PetscObject)mpart,prefix);CHKERRQ(ierr);
195 	ierr = MatPartitioningSetFromOptions( mpart );    CHKERRQ(ierr);
196 	ierr = MatPartitioningSetNParts( mpart, new_npe );CHKERRQ(ierr);
197 	ierr = MatPartitioningApply( mpart, &proc_is ); CHKERRQ(ierr);
198 	ierr = MatPartitioningDestroy( &mpart );          CHKERRQ(ierr);
199 
200 	/* collect IS info */
201 	ierr = ISGetLocalSize( proc_is, &is_sz );       CHKERRQ(ierr);
202 	ierr = PetscMalloc( cbs*is_sz*sizeof(PetscInt), &newproc_idx ); CHKERRQ(ierr);
203 	ierr = ISGetIndices( proc_is, &is_idx );        CHKERRQ(ierr);
204 	NN = 1; /* bring to "front" of machine */
205 	/*NN = npe/new_npe;*/ /* spread partitioning across machine */
206 	for( kk = jj = 0 ; kk < is_sz ; kk++ ){
207 	  for( ii = 0 ; ii < cbs ; ii++, jj++ ){
208 	    newproc_idx[jj] = is_idx[kk] * NN; /* distribution */
209 	  }
210 	}
211 	ierr = ISRestoreIndices( proc_is, &is_idx );     CHKERRQ(ierr);
212 	ierr = ISDestroy( &proc_is );                    CHKERRQ(ierr);
213 
214 	is_sz *= cbs;
215       }
216       ierr = MatDestroy( &adj );                       CHKERRQ(ierr);
217 
218       ierr = ISCreateGeneral( wcomm, is_sz, newproc_idx, PETSC_COPY_VALUES, &isnewproc );
219       CHKERRQ(ierr);
220       if( newproc_idx != 0 ) {
221 	ierr = PetscFree( newproc_idx );  CHKERRQ(ierr);
222       }
223     }
224     else { /* simple aggreagtion of parts */
225       /* find factor */
226       if( new_npe == 1 ) rfactor = npe; /* easy */
227       else {
228 	PetscReal best_fact = 0.;
229 	jj = -1;
230 	for( kk = 1 ; kk <= npe ; kk++ ){
231 	  if( npe%kk==0 ) { /* a candidate */
232 	    PetscReal nactpe = (PetscReal)npe/(PetscReal)kk, fact = nactpe/(PetscReal)new_npe;
233 	    if(fact > 1.0) fact = 1./fact; /* keep fact < 1 */
234 	    if( fact > best_fact ) {
235 	      best_fact = fact; jj = kk;
236 	    }
237 	  }
238 	}
239 	if(jj!=-1) rfactor = jj;
240 	else rfactor = 1; /* prime? */
241       }
242       new_npe = npe/rfactor;
243 
244       if( new_npe==nactive ) {
245 	*a_Amat_crs = Cmat; /* output - no repartitioning or reduction */
246 	ierr = PetscFree( counts );  CHKERRQ(ierr);
247 	*a_nactive_proc = new_npe; /* output */
248 	if (pc_gamg->verbose) PetscPrintf(wcomm,"\t[%d]%s aggregate processors noop: new_npe=%d, neq=%d\n",mype,__FUNCT__,new_npe,neq);
249 	PetscFunctionReturn(0);
250       }
251 
252       /* reduce - isnewproc */
253       targetPE = mype/rfactor;
254 
255       if (pc_gamg->verbose) PetscPrintf(wcomm,"\t[%d]%s aggregate processors: npe: %d --> %d, neq=%d\n",mype,__FUNCT__,*a_nactive_proc,new_npe,neq);
256       is_sz = ncrs0*cbs;
257       ierr = ISCreateStride( wcomm, is_sz, targetPE, 0, &isnewproc );
258       CHKERRQ(ierr);
259     }
260 
261     /*
262       Create an index set from the isnewproc index set to indicate the mapping TO
263     */
264     ierr = ISPartitioningToNumbering( isnewproc, &isnum ); CHKERRQ(ierr);
265     /*
266       Determine how many elements are assigned to each processor
267     */
268     inpe = npe;
269     ierr = ISPartitioningCount( isnewproc, inpe, counts ); CHKERRQ(ierr);
270     ierr = ISDestroy( &isnewproc );                       CHKERRQ(ierr);
271     ncrs_new = counts[mype]/cbs;
272     strideNew = ncrs_new*ndata_rows;
273 #if defined PETSC_USE_LOG
274       ierr = PetscLogEventEnd(gamg_setup_events[SET12],0,0,0,0);   CHKERRQ(ierr);
275 #endif
276     /* Create a vector to contain the newly ordered element information */
277     ierr = VecCreate( wcomm, &dest_crd );
278     ierr = VecSetSizes( dest_crd, data_sz*ncrs_new, PETSC_DECIDE ); CHKERRQ(ierr);
279     ierr = VecSetFromOptions( dest_crd ); CHKERRQ(ierr); /* this is needed! */
280     /*
281      There are 'ndata_rows*ndata_cols' data items per node, (one can think of the vectors of having
282      a block size of ...).  Note, ISs are expanded into equation space by 'cbs'.
283      */
284     ierr = PetscMalloc( (ncrs0*data_sz)*sizeof(PetscInt), &tidx ); CHKERRQ(ierr);
285     ierr = ISGetIndices( isnum, &idx ); CHKERRQ(ierr);
286     for(ii=0,jj=0; ii<ncrs0 ; ii++) {
287       PetscInt id = idx[ii*cbs]/cbs; /* get node back */
288       for( kk=0; kk<data_sz ; kk++, jj++) tidx[jj] = id*data_sz + kk;
289     }
290     ierr = ISRestoreIndices( isnum, &idx ); CHKERRQ(ierr);
291     ierr = ISCreateGeneral( wcomm, data_sz*ncrs0, tidx, PETSC_COPY_VALUES, &isscat );
292     CHKERRQ(ierr);
293     ierr = PetscFree( tidx );  CHKERRQ(ierr);
294     /*
295      Create a vector to contain the original vertex information for each element
296      */
297     ierr = VecCreateSeq( PETSC_COMM_SELF, data_sz*ncrs0, &src_crd ); CHKERRQ(ierr);
298     for( jj=0; jj<ndata_cols ; jj++ ) {
299       for( ii=0 ; ii<ncrs0 ; ii++) {
300 	for( kk=0; kk<ndata_rows ; kk++ ) {
301 	  PetscInt ix = ii*ndata_rows + kk + jj*stride0, jx = ii*data_sz + kk*ndata_cols + jj;
302           PetscScalar tt = (PetscScalar)pc_gamg->data[ix];
303 	  ierr = VecSetValues( src_crd, 1, &jx, &tt, INSERT_VALUES );  CHKERRQ(ierr);
304 	}
305       }
306     }
307     ierr = VecAssemblyBegin(src_crd); CHKERRQ(ierr);
308     ierr = VecAssemblyEnd(src_crd); CHKERRQ(ierr);
309     /*
310       Scatter the element vertex information (still in the original vertex ordering)
311       to the correct processor
312     */
313     ierr = VecScatterCreate( src_crd, PETSC_NULL, dest_crd, isscat, &vecscat);
314     CHKERRQ(ierr);
315     ierr = ISDestroy( &isscat );       CHKERRQ(ierr);
316     ierr = VecScatterBegin(vecscat,src_crd,dest_crd,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
317     ierr = VecScatterEnd(vecscat,src_crd,dest_crd,INSERT_VALUES,SCATTER_FORWARD);CHKERRQ(ierr);
318     ierr = VecScatterDestroy( &vecscat );       CHKERRQ(ierr);
319     ierr = VecDestroy( &src_crd );       CHKERRQ(ierr);
320     /*
321       Put the element vertex data into a new allocation of the gdata->ele
322     */
323     ierr = PetscFree( pc_gamg->data );    CHKERRQ(ierr);
324     ierr = PetscMalloc( data_sz*ncrs_new*sizeof(PetscReal), &pc_gamg->data );    CHKERRQ(ierr);
325     pc_gamg->data_sz = data_sz*ncrs_new;
326     ierr = VecGetArray( dest_crd, &array );    CHKERRQ(ierr);
327     for( jj=0; jj<ndata_cols ; jj++ ) {
328       for( ii=0 ; ii<ncrs_new ; ii++) {
329 	for( kk=0; kk<ndata_rows ; kk++ ) {
330 	  PetscInt ix = ii*ndata_rows + kk + jj*strideNew, jx = ii*data_sz + kk*ndata_cols + jj;
331 	  pc_gamg->data[ix] = PetscRealPart(array[jx]);
332 	  array[jx] = 1.e300;
333 	}
334       }
335     }
336     ierr = VecRestoreArray( dest_crd, &array );    CHKERRQ(ierr);
337     ierr = VecDestroy( &dest_crd );    CHKERRQ(ierr);
338 #if defined PETSC_USE_LOG
339     ierr = PetscLogEventBegin(gamg_setup_events[SET13],0,0,0,0);CHKERRQ(ierr);
340 #endif
341     /*
342       Invert for MatGetSubMatrix
343     */
344     ierr = ISInvertPermutation( isnum, ncrs_new*cbs, &new_indices ); CHKERRQ(ierr);
345     ierr = ISSort( new_indices ); CHKERRQ(ierr); /* is this needed? */
346     ierr = ISDestroy( &isnum ); CHKERRQ(ierr);
347 #if defined PETSC_USE_LOG
348     ierr = PetscLogEventEnd(gamg_setup_events[SET13],0,0,0,0);CHKERRQ(ierr);
349     ierr = PetscLogEventBegin(gamg_setup_events[SET14],0,0,0,0);CHKERRQ(ierr);
350 #endif
351     /* A_crs output */
352     ierr = MatGetSubMatrix( Cmat, new_indices, new_indices, MAT_INITIAL_MATRIX, a_Amat_crs );
353     CHKERRQ(ierr);
354 
355     ierr = MatDestroy( &Cmat ); CHKERRQ(ierr);
356     Cmat = *a_Amat_crs; /* output */
357     ierr = MatSetBlockSize( Cmat, cbs );      CHKERRQ(ierr);
358 #if defined PETSC_USE_LOG
359     ierr = PetscLogEventEnd(gamg_setup_events[SET14],0,0,0,0);CHKERRQ(ierr);
360 #endif
361     /* prolongator */
362     ierr = MatGetOwnershipRange( Pold, &Istart, &Iend );    CHKERRQ(ierr);
363     {
364       IS findices;
365 #if defined PETSC_USE_LOG
366       ierr = PetscLogEventBegin(gamg_setup_events[SET15],0,0,0,0);CHKERRQ(ierr);
367 #endif
368       ierr = ISCreateStride(wcomm,Iend-Istart,Istart,1,&findices);   CHKERRQ(ierr);
369 #ifdef USE_R
370       ierr = MatGetSubMatrix( Pold, new_indices, findices, MAT_INITIAL_MATRIX, &Pnew );
371 #else
372       ierr = MatGetSubMatrix( Pold, findices, new_indices, MAT_INITIAL_MATRIX, &Pnew );
373 #endif
374       CHKERRQ(ierr);
375       ierr = ISDestroy( &findices ); CHKERRQ(ierr);
376 #if defined PETSC_USE_LOG
377       ierr = PetscLogEventEnd(gamg_setup_events[SET15],0,0,0,0);CHKERRQ(ierr);
378 #endif
379     }
380     ierr = MatDestroy( a_P_inout ); CHKERRQ(ierr);
381     *a_P_inout = Pnew; /* output - repartitioned */
382     ierr = ISDestroy( &new_indices ); CHKERRQ(ierr);
383     ierr = PetscFree( counts );  CHKERRQ(ierr);
384   }
385 
386   *a_nactive_proc = new_npe; /* output */
387 
388   if( !PETSC_TRUE ) {
389     PetscViewer viewer; char fname[32]; static int llev=0; Cmat = *a_Amat_crs;
390     if(llev==0) {
391       sprintf(fname,"Cmat_%d.m",llev++);
392       PetscViewerASCIIOpen(wcomm,fname,&viewer);
393       ierr = PetscViewerSetFormat( viewer, PETSC_VIEWER_ASCII_MATLAB);  CHKERRQ(ierr);
394       ierr = MatView(Amat_fine, viewer ); CHKERRQ(ierr);
395       ierr = PetscViewerDestroy( &viewer );
396     }
397     sprintf(fname,"Cmat_%d.m",llev++);
398     PetscViewerASCIIOpen(wcomm,fname,&viewer);
399     ierr = PetscViewerSetFormat( viewer, PETSC_VIEWER_ASCII_MATLAB);  CHKERRQ(ierr);
400     ierr = MatView(Cmat, viewer ); CHKERRQ(ierr);
401     ierr = PetscViewerDestroy( &viewer );
402   }
403 
404   PetscFunctionReturn(0);
405 }
406 
407 /* -------------------------------------------------------------------------- */
408 /*
409    PCSetUp_GAMG - Prepares for the use of the GAMG preconditioner
410                     by setting data structures and options.
411 
412    Input Parameter:
413 .  pc - the preconditioner context
414 
415    Application Interface Routine: PCSetUp()
416 
417    Notes:
418    The interface routine PCSetUp() is not usually called directly by
419    the user, but instead is called by PCApply() if necessary.
420 */
421 #undef __FUNCT__
422 #define __FUNCT__ "PCSetUp_GAMG"
423 PetscErrorCode PCSetUp_GAMG( PC pc )
424 {
425   PetscErrorCode  ierr;
426   PC_MG           *mg = (PC_MG*)pc->data;
427   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
428   Mat              Pmat = pc->pmat;
429   PetscInt         fine_level,level,level1,M,N,bs,nloc,lidx,Istart,Iend;
430   MPI_Comm         wcomm = ((PetscObject)pc)->comm;
431   PetscMPIInt      mype,npe,nactivepe;
432   Mat              Aarr[GAMG_MAXLEVELS], Parr[GAMG_MAXLEVELS];
433   PetscReal        emaxs[GAMG_MAXLEVELS];
434   PetscLogDouble   nnz0=0,nnztot=0;
435   MatInfo          info;
436 
437   PetscFunctionBegin;
438   ierr = MPI_Comm_rank(wcomm,&mype);CHKERRQ(ierr);
439   ierr = MPI_Comm_size(wcomm,&npe);CHKERRQ(ierr);
440   if( pc_gamg->setup_count++ > 0 ) {
441     PC_MG_Levels   **mglevels = mg->levels;
442     /* just do Galerkin grids */
443     Mat B,dA,dB;
444     assert(pc->setupcalled);
445 
446     if( pc_gamg->Nlevels > 1 ) {
447       /* currently only handle case where mat and pmat are the same on coarser levels */
448       ierr = KSPGetOperators(mglevels[pc_gamg->Nlevels-1]->smoothd,&dA,&dB,PETSC_NULL);CHKERRQ(ierr);
449       /* (re)set to get dirty flag */
450       ierr = KSPSetOperators(mglevels[pc_gamg->Nlevels-1]->smoothd,dA,dB,SAME_NONZERO_PATTERN);CHKERRQ(ierr);
451 
452       for (level=pc_gamg->Nlevels-2; level>-1; level--) {
453         /* the first time through the matrix structure has changed from repartitioning */
454         if( pc_gamg->setup_count==2 /*&& (pc_gamg->repart || level==0)*/) {
455           ierr = MatPtAP(dB,mglevels[level+1]->interpolate,MAT_INITIAL_MATRIX,1.0,&B);CHKERRQ(ierr);
456           ierr = MatDestroy(&mglevels[level]->A);CHKERRQ(ierr);
457           mglevels[level]->A = B;
458         }
459         else {
460           ierr = KSPGetOperators(mglevels[level]->smoothd,PETSC_NULL,&B,PETSC_NULL);CHKERRQ(ierr);
461           ierr = MatPtAP(dB,mglevels[level+1]->interpolate,MAT_REUSE_MATRIX,1.0,&B);CHKERRQ(ierr);
462         }
463         ierr = KSPSetOperators(mglevels[level]->smoothd,B,B,SAME_NONZERO_PATTERN); CHKERRQ(ierr);
464         dB = B;
465         }
466     }
467 
468     ierr = PCSetUp_MG( pc );CHKERRQ( ierr );
469 
470     /* PCSetUp_MG seems to insists on setting this to GMRES */
471     ierr = KSPSetType( mglevels[0]->smoothd, KSPPREONLY ); CHKERRQ(ierr);
472 
473     PetscFunctionReturn(0);
474   }
475   assert(pc->setupcalled == 0);
476 
477   /* GAMG requires input of fine-grid matrix. It determines nlevels. */
478   ierr = MatGetBlockSize( Pmat, &bs ); CHKERRQ(ierr);
479   ierr = MatGetSize( Pmat, &M, &N );CHKERRQ(ierr);
480   ierr = MatGetOwnershipRange( Pmat, &Istart, &Iend ); CHKERRQ(ierr);
481   nloc = (Iend-Istart)/bs; assert((Iend-Istart)%bs == 0);
482 
483   if( pc_gamg->data == 0 && nloc > 0 ) {
484     if(!pc_gamg->createdefaultdata){
485       SETERRQ(((PetscObject)pc)->comm,PETSC_ERR_LIB,"'createdefaultdata' not set?!?! need to support NULL data!!!");
486     }
487     ierr = pc_gamg->createdefaultdata( pc ); CHKERRQ(ierr);
488   }
489 
490   /* Get A_i and R_i */
491   if (pc_gamg->verbose) {
492     if(pc_gamg->verbose==1) ierr =  MatGetInfo(Pmat,MAT_LOCAL,&info);
493     else ierr =  MatGetInfo(Pmat,MAT_GLOBAL_SUM,&info);
494     CHKERRQ(ierr);
495     nnz0 = info.nz_used;
496     nnztot = info.nz_used;
497     PetscPrintf(wcomm,"\t[%d]%s level %d N=%d, n data rows=%d, n data cols=%d, nnz/row (ave)=%d, np=%d\n",
498                 mype,__FUNCT__,0,N,pc_gamg->data_cell_rows,pc_gamg->data_cell_cols,
499                 (int)(nnz0/(PetscReal)N),npe);
500   }
501 
502   for ( level=0, Aarr[0] = Pmat, nactivepe = npe; /* hard wired stopping logic */
503         level < (pc_gamg->Nlevels-1) && (level==0 || M>pc_gamg->coarse_eq_limit); /* && (npe==1 || nactivepe>1); */
504         level++ ){
505     level1 = level + 1;
506 #if (defined PETSC_USE_LOG && defined GAMG_STAGES)
507     ierr = PetscLogStagePush(gamg_stages[level]); CHKERRQ( ierr );
508 #endif
509 #if defined PETSC_USE_LOG
510     ierr = PetscLogEventBegin(gamg_setup_events[SET1],0,0,0,0); CHKERRQ(ierr);
511 #endif
512     { /* construct prolongator */
513       Mat Gmat;
514       IS selected, llist;
515 
516       ierr = pc_gamg->graph( pc, Aarr[level], &Gmat ); CHKERRQ(ierr);
517       ierr = pc_gamg->coarsen( pc, &Gmat, &selected, &llist ); CHKERRQ(ierr);
518       ierr = pc_gamg->prolongator( pc, Aarr[level], Gmat, selected, llist, &Parr[level1] );
519       CHKERRQ(ierr);
520 
521       if( Parr[level1] ){
522         /* get new block size of coarse matrices */
523         if( pc_gamg->col_bs_id != -1 ){
524           PetscBool flag;
525           ierr = PetscObjectComposedDataGetInt( (PetscObject)Parr[level1], pc_gamg->col_bs_id, bs, flag );
526           CHKERRQ( ierr ); assert(flag);
527         }
528       }
529 
530       if( pc_gamg->optprol && Parr[level1] ){
531         /* smooth */
532         ierr = pc_gamg->optprol( pc, Aarr[level], &Parr[level1] ); CHKERRQ(ierr);
533       }
534 
535       ierr = MatDestroy( &Gmat );  CHKERRQ(ierr);
536       ierr = ISDestroy( &selected );  CHKERRQ(ierr);
537       ierr = ISDestroy( &llist );  CHKERRQ(ierr);
538     }
539 #if defined PETSC_USE_LOG
540     ierr = PetscLogEventEnd(gamg_setup_events[SET1],0,0,0,0);CHKERRQ(ierr);
541 #endif
542     /* cache eigen estimate */
543     if( pc_gamg->emax_id != -1 ){
544       PetscBool flag;
545       ierr = PetscObjectComposedDataGetReal( (PetscObject)Aarr[level], pc_gamg->emax_id, emaxs[level], flag );
546       CHKERRQ( ierr );
547       if( !flag ) emaxs[level] = -1.;
548     }
549     else emaxs[level] = -1.;
550     if(level==0) Aarr[0] = Pmat; /* use Pmat for finest level setup */
551     if( !Parr[level1] ) {
552       if (pc_gamg->verbose) PetscPrintf(wcomm,"\t[%d]%s stop gridding, level %d\n",mype,__FUNCT__,level);
553       break;
554     }
555 #if defined PETSC_USE_LOG
556     ierr = PetscLogEventBegin(gamg_setup_events[SET2],0,0,0,0);CHKERRQ(ierr);
557 #endif
558     ierr = createLevel( pc, Aarr[level], bs,
559                         (PetscBool)(level==pc_gamg->Nlevels-2),
560                         &Parr[level1], &nactivepe, &Aarr[level1] );
561     CHKERRQ(ierr);
562 #if defined PETSC_USE_LOG
563     ierr = PetscLogEventEnd(gamg_setup_events[SET2],0,0,0,0);CHKERRQ(ierr);
564 #endif
565     ierr = MatGetSize( Aarr[level1], &M, &N );CHKERRQ(ierr);
566     if (pc_gamg->verbose){
567       ierr = MatGetInfo( Aarr[level1], MAT_GLOBAL_SUM, &info ); CHKERRQ(ierr);
568       PetscPrintf(wcomm,"\t\t[%d]%s %d) N=%d, n data cols=%d, nnz/row (ave)=%d, %d active pes\n",
569                   mype,__FUNCT__,(int)level1,N,pc_gamg->data_cell_cols,
570                   (int)(info.nz_used/(PetscReal)N),nactivepe);
571     }
572     /* stop if one node */
573     if( M/pc_gamg->data_cell_cols < 2 ) {
574       level++;
575       break;
576     }
577     /* Vec diag; PetscScalar *data_arr,v; PetscInt Istart,Iend,kk,nloceq,id; */
578     /* v = 1.e-10; /\* LU factor has hard wired numbers for small diags so this needs to match (yuk) *\/ */
579     /* ierr = MatGetOwnershipRange(Aarr[level1], &Istart, &Iend); CHKERRQ(ierr); */
580     /* nloceq = Iend-Istart; */
581     /* ierr = MatGetVecs( Aarr[level1], &diag, 0 );    CHKERRQ(ierr); */
582     /* ierr = MatGetDiagonal( Aarr[level1], diag );    CHKERRQ(ierr); */
583     /* ierr = VecGetArray( diag, &data_arr );   CHKERRQ(ierr); */
584     /* for(kk=0;kk<nloceq;kk++){ */
585     /*   if(data_arr[kk]==0.0) { */
586     /*     id = kk + Istart; */
587     /*     ierr = MatSetValues(Aarr[level1],1,&id,1,&id,&v,INSERT_VALUES); */
588     /*     CHKERRQ(ierr); */
589     /*     PetscPrintf(PETSC_COMM_SELF,"\t[%d]%s warning: added zero to diag (%d) on level %d \n",mype,__FUNCT__,id,level1); */
590     /*   } */
591     /* } */
592     /* ierr = VecRestoreArray( diag, &data_arr ); CHKERRQ(ierr); */
593     /* ierr = VecDestroy( &diag );                CHKERRQ(ierr); */
594     /* ierr = MatAssemblyBegin(Aarr[level1],MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); */
595     /* ierr = MatAssemblyEnd(Aarr[level1],MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); */
596 
597 #if (defined PETSC_USE_LOG && defined GAMG_STAGES)
598     ierr = PetscLogStagePop(); CHKERRQ( ierr );
599 #endif
600     if(pc_gamg->verbose){
601       if(pc_gamg->verbose==1) ierr =  MatGetInfo(Aarr[level1],MAT_LOCAL,&info);
602       else ierr =  MatGetInfo(Aarr[level1],MAT_GLOBAL_SUM,&info);
603       CHKERRQ(ierr);
604       nnztot += info.nz_used;
605     }
606   } /* levels */
607 
608   if( pc_gamg->data ) {
609     ierr = PetscFree( pc_gamg->data ); CHKERRQ( ierr );
610     pc_gamg->data = 0;
611   }
612 
613   if (pc_gamg->verbose) PetscPrintf(wcomm,"\t[%d]%s %d levels, grid compexity = %g\n",0,__FUNCT__,level+1,nnztot/nnz0);
614   pc_gamg->Nlevels = level + 1;
615   fine_level = level;
616   ierr = PCMGSetLevels(pc,pc_gamg->Nlevels,PETSC_NULL);CHKERRQ(ierr);
617 
618   /* simple setup */
619   if( !PETSC_TRUE ){
620     PC_MG_Levels **mglevels = mg->levels;
621     for (lidx=0,level=pc_gamg->Nlevels-1;
622          lidx<fine_level;
623          lidx++, level--){
624       ierr = PCMGSetInterpolation( pc, lidx+1, Parr[level] );CHKERRQ(ierr);
625       ierr = KSPSetOperators( mglevels[lidx]->smoothd, Aarr[level], Aarr[level], SAME_NONZERO_PATTERN );   CHKERRQ(ierr);
626       ierr = MatDestroy( &Parr[level] );  CHKERRQ(ierr);
627       ierr = MatDestroy( &Aarr[level] );  CHKERRQ(ierr);
628     }
629     ierr = KSPSetOperators( mglevels[fine_level]->smoothd, Aarr[0], Aarr[0], SAME_NONZERO_PATTERN );   CHKERRQ(ierr);
630 
631     ierr = PCSetUp_MG( pc );  CHKERRQ( ierr );
632   }
633   else if( pc_gamg->Nlevels > 1 ) { /* don't setup MG if one level */
634     /* set default smoothers & set operators */
635     for ( lidx = 1, level = pc_gamg->Nlevels-2;
636           lidx <= fine_level;
637           lidx++, level--) {
638       KSP smoother; PC subpc;
639       /* set defaults */
640       ierr = PCMGGetSmoother( pc, lidx, &smoother ); CHKERRQ(ierr);
641       ierr = KSPSetType( smoother, KSPCHEBYCHEV );CHKERRQ(ierr);
642       ierr = KSPGetPC( smoother, &subpc ); CHKERRQ(ierr);
643       ierr = PCSetType( subpc, PCJACOBI ); CHKERRQ(ierr);
644       ierr = KSPSetNormType( smoother, KSP_NORM_NONE ); CHKERRQ(ierr);
645       /* set ops */
646       ierr = KSPSetOperators( smoother, Aarr[level], Aarr[level], SAME_NONZERO_PATTERN );   CHKERRQ(ierr);
647       ierr = PCMGSetInterpolation( pc, lidx, Parr[level+1] );CHKERRQ(ierr);
648     }
649     {
650       /* coarse grid */
651       KSP smoother,*k2; PC subpc,pc2; PetscInt ii,first;
652       Mat Lmat = Aarr[(level=pc_gamg->Nlevels-1)]; lidx = 0;
653       ierr = PCMGGetSmoother( pc, lidx, &smoother ); CHKERRQ(ierr);
654       ierr = KSPSetOperators( smoother, Lmat, Lmat, SAME_NONZERO_PATTERN ); CHKERRQ(ierr);
655       ierr = KSPSetNormType( smoother, KSP_NORM_NONE ); CHKERRQ(ierr);
656       ierr = KSPGetPC( smoother, &subpc ); CHKERRQ(ierr);
657       ierr = PCSetType( subpc, PCBJACOBI ); CHKERRQ(ierr);
658       ierr = PCSetUp( subpc ); CHKERRQ(ierr);
659       ierr = PCBJacobiGetSubKSP(subpc,&ii,&first,&k2);CHKERRQ(ierr);      assert(ii==1);
660       ierr = KSPGetPC(k2[0],&pc2);CHKERRQ(ierr);
661       ierr = PCSetType( pc2, PCLU ); CHKERRQ(ierr);
662     }
663 
664     /* should be called in PCSetFromOptions_GAMG(), but cannot be called prior to PCMGSetLevels() */
665     ierr = PetscObjectOptionsBegin((PetscObject)pc);CHKERRQ(ierr);
666     ierr = PCSetFromOptions_MG(pc); CHKERRQ(ierr);
667     ierr = PetscOptionsEnd();CHKERRQ(ierr);
668     if (mg->galerkin != 2) SETERRQ(wcomm,PETSC_ERR_USER,"GAMG does Galerkin manually so the -pc_mg_galerkin option must not be used.");
669 
670     /* create cheby smoothers */
671     for ( lidx = 1, level = pc_gamg->Nlevels-2;
672           lidx <= fine_level;
673           lidx++, level--) {
674       KSP smoother;
675       PetscBool isCheb;
676 
677       ierr = PCMGGetSmoother( pc, lidx, &smoother ); CHKERRQ(ierr);
678       /* do my own cheby */
679       ierr = PetscTypeCompare( (PetscObject)smoother, KSPCHEBYCHEV, &isCheb ); CHKERRQ(ierr);
680       if( isCheb ) {
681         PetscReal emax, emin;
682         PC subpc;
683 
684         ierr = KSPGetPC( smoother, &subpc ); CHKERRQ(ierr);
685         ierr = PetscTypeCompare( (PetscObject)subpc, PCJACOBI, &isCheb ); CHKERRQ(ierr);
686         if( isCheb && emaxs[level] > 0.0 ) emax=emaxs[level]; /* eigen estimate only for diagnal PC */
687         else{ /* eigen estimate 'emax' */
688           KSP eksp; Mat Lmat = Aarr[level];
689           Vec bb, xx;
690 
691           ierr = MatGetVecs( Lmat, &bb, 0 );         CHKERRQ(ierr);
692           ierr = MatGetVecs( Lmat, &xx, 0 );         CHKERRQ(ierr);
693           {
694             PetscRandom    rctx;
695             ierr = PetscRandomCreate(wcomm,&rctx);CHKERRQ(ierr);
696             ierr = PetscRandomSetFromOptions(rctx);CHKERRQ(ierr);
697             ierr = VecSetRandom(bb,rctx);CHKERRQ(ierr);
698             ierr = PetscRandomDestroy( &rctx ); CHKERRQ(ierr);
699           }
700           ierr = KSPCreate(wcomm,&eksp);CHKERRQ(ierr);
701           ierr = KSPSetTolerances( eksp, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT, 10 );
702           CHKERRQ(ierr);
703           ierr = KSPSetNormType( eksp, KSP_NORM_NONE );                 CHKERRQ(ierr);
704 
705           ierr = KSPAppendOptionsPrefix( eksp, "est_");         CHKERRQ(ierr);
706           ierr = KSPSetFromOptions( eksp );    CHKERRQ(ierr);
707 
708           ierr = KSPSetInitialGuessNonzero( eksp, PETSC_FALSE ); CHKERRQ(ierr);
709           ierr = KSPSetOperators( eksp, Lmat, Lmat, SAME_NONZERO_PATTERN ); CHKERRQ( ierr );
710           ierr = KSPSetComputeSingularValues( eksp,PETSC_TRUE ); CHKERRQ(ierr);
711 
712           { /* set PC type to be same as smoother - does not get all parameters!!! */
713             const PCType type;    PC pc;
714             ierr = PCGetType( subpc, &type );   CHKERRQ(ierr);
715             ierr = KSPGetPC( eksp, &pc );CHKERRQ( ierr );
716             ierr = PCSetType( pc, type ); CHKERRQ(ierr);
717           }
718 
719           /* solve - keep stuff out of logging */
720           ierr = PetscLogEventDeactivate(KSP_Solve);CHKERRQ(ierr);
721           ierr = PetscLogEventDeactivate(PC_Apply);CHKERRQ(ierr);
722           ierr = KSPSolve( eksp, bb, xx ); CHKERRQ(ierr);
723           ierr = PetscLogEventActivate(KSP_Solve);CHKERRQ(ierr);
724           ierr = PetscLogEventActivate(PC_Apply);CHKERRQ(ierr);
725 
726           ierr = KSPComputeExtremeSingularValues( eksp, &emax, &emin ); CHKERRQ(ierr);
727 
728           ierr = VecDestroy( &xx );       CHKERRQ(ierr);
729           ierr = VecDestroy( &bb );       CHKERRQ(ierr);
730           ierr = KSPDestroy( &eksp );       CHKERRQ(ierr);
731 
732           if (pc_gamg->verbose) {
733             PetscPrintf(wcomm,"\t\t\t%s PC setup max eigen=%e min=%e\n",__FUNCT__,emax,emin);
734           }
735         }
736         {
737           PetscInt N1, N0, tt;
738           ierr = MatGetSize( Aarr[level], &N1, &tt );         CHKERRQ(ierr);
739           ierr = MatGetSize( Aarr[level+1], &N0, &tt );       CHKERRQ(ierr);
740           /* heuristic - is this crap? */
741           emin = 1.*emax/((PetscReal)N1/(PetscReal)N0);
742           emax *= 1.05;
743         }
744         ierr = KSPChebychevSetEigenvalues( smoother, emax, emin );CHKERRQ(ierr);
745       }
746     }
747 
748     /* clean up */
749     for(level=1;level<pc_gamg->Nlevels;level++){
750       ierr = MatDestroy( &Parr[level] );  CHKERRQ(ierr);
751       ierr = MatDestroy( &Aarr[level] );  CHKERRQ(ierr);
752     }
753     {
754       KSP smoother;  /* PCSetUp_MG seems to insists on setting this to GMRES on coarse grid */
755       ierr = PCMGGetSmoother( pc, 0, &smoother ); CHKERRQ(ierr);
756       ierr = KSPSetType( smoother, KSPPREONLY ); CHKERRQ(ierr);
757     }
758     ierr = PCSetUp_MG( pc );CHKERRQ( ierr );
759   }
760   else {
761     KSP smoother;
762     if (pc_gamg->verbose) PetscPrintf(wcomm,"\t[%d]%s one level solver used (system is seen as DD). Using default solver.\n",mype,__FUNCT__);
763     ierr = PCMGGetSmoother( pc, 0, &smoother ); CHKERRQ(ierr);
764     ierr = KSPSetOperators( smoother, Aarr[0], Aarr[0], SAME_NONZERO_PATTERN );   CHKERRQ(ierr);
765     ierr = KSPSetType( smoother, KSPPREONLY ); CHKERRQ(ierr);
766     ierr = PCSetUp_MG( pc );CHKERRQ( ierr );
767   }
768 
769   PetscFunctionReturn(0);
770 }
771 
772 /* ------------------------------------------------------------------------- */
773 /*
774  PCDestroy_GAMG - Destroys the private context for the GAMG preconditioner
775    that was created with PCCreate_GAMG().
776 
777    Input Parameter:
778 .  pc - the preconditioner context
779 
780    Application Interface Routine: PCDestroy()
781 */
782 #undef __FUNCT__
783 #define __FUNCT__ "PCDestroy_GAMG"
784 PetscErrorCode PCDestroy_GAMG( PC pc )
785 {
786   PetscErrorCode  ierr;
787   PC_MG           *mg = (PC_MG*)pc->data;
788   PC_GAMG         *pc_gamg= (PC_GAMG*)mg->innerctx;
789 
790   PetscFunctionBegin;
791   ierr = PCReset_GAMG( pc );CHKERRQ(ierr);
792   ierr = PetscFree( pc_gamg );CHKERRQ(ierr);
793   ierr = PCDestroy_MG( pc );CHKERRQ(ierr);
794   PetscFunctionReturn(0);
795 }
796 
797 
798 #undef __FUNCT__
799 #define __FUNCT__ "PCGAMGSetProcEqLim"
800 /*@
801    PCGAMGSetProcEqLim - Set number of equations to aim for on coarse grids via
802    processor reduction.
803 
804    Not Collective on PC
805 
806    Input Parameters:
807 .  pc - the preconditioner context
808 
809 
810    Options Database Key:
811 .  -pc_gamg_process_eq_limit
812 
813    Level: intermediate
814 
815    Concepts: Unstructured multrigrid preconditioner
816 
817 .seealso: ()
818 @*/
819 PetscErrorCode  PCGAMGSetProcEqLim(PC pc, PetscInt n)
820 {
821   PetscErrorCode ierr;
822 
823   PetscFunctionBegin;
824   PetscValidHeaderSpecific(pc,PC_CLASSID,1);
825   ierr = PetscTryMethod(pc,"PCGAMGSetProcEqLim_C",(PC,PetscInt),(pc,n));CHKERRQ(ierr);
826   PetscFunctionReturn(0);
827 }
828 
829 EXTERN_C_BEGIN
830 #undef __FUNCT__
831 #define __FUNCT__ "PCGAMGSetProcEqLim_GAMG"
832 PetscErrorCode PCGAMGSetProcEqLim_GAMG(PC pc, PetscInt n)
833 {
834   PC_MG           *mg = (PC_MG*)pc->data;
835   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
836 
837   PetscFunctionBegin;
838   if(n>0) pc_gamg->min_eq_proc = n;
839   PetscFunctionReturn(0);
840 }
841 EXTERN_C_END
842 
843 #undef __FUNCT__
844 #define __FUNCT__ "PCGAMGSetCoarseEqLim"
845 /*@
846    PCGAMGSetCoarseEqLim - Set max number of equations on coarse grids.
847 
848  Collective on PC
849 
850    Input Parameters:
851 .  pc - the preconditioner context
852 
853 
854    Options Database Key:
855 .  -pc_gamg_coarse_eq_limit
856 
857    Level: intermediate
858 
859    Concepts: Unstructured multrigrid preconditioner
860 
861 .seealso: ()
862  @*/
863 PetscErrorCode PCGAMGSetCoarseEqLim(PC pc, PetscInt n)
864 {
865   PetscErrorCode ierr;
866 
867   PetscFunctionBegin;
868   PetscValidHeaderSpecific(pc,PC_CLASSID,1);
869   ierr = PetscTryMethod(pc,"PCGAMGSetCoarseEqLim_C",(PC,PetscInt),(pc,n));CHKERRQ(ierr);
870   PetscFunctionReturn(0);
871 }
872 
873 EXTERN_C_BEGIN
874 #undef __FUNCT__
875 #define __FUNCT__ "PCGAMGSetCoarseEqLim_GAMG"
876 PetscErrorCode PCGAMGSetCoarseEqLim_GAMG(PC pc, PetscInt n)
877 {
878   PC_MG           *mg = (PC_MG*)pc->data;
879   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
880 
881   PetscFunctionBegin;
882   if(n>0) pc_gamg->coarse_eq_limit = n;
883   PetscFunctionReturn(0);
884 }
885 EXTERN_C_END
886 
887 #undef __FUNCT__
888 #define __FUNCT__ "PCGAMGSetRepartitioning"
889 /*@
890    PCGAMGSetRepartitioning - Repartition the coarse grids
891 
892    Collective on PC
893 
894    Input Parameters:
895 .  pc - the preconditioner context
896 
897 
898    Options Database Key:
899 .  -pc_gamg_repartition
900 
901    Level: intermediate
902 
903    Concepts: Unstructured multrigrid preconditioner
904 
905 .seealso: ()
906 @*/
907 PetscErrorCode PCGAMGSetRepartitioning(PC pc, PetscBool n)
908 {
909   PetscErrorCode ierr;
910 
911   PetscFunctionBegin;
912   PetscValidHeaderSpecific(pc,PC_CLASSID,1);
913   ierr = PetscTryMethod(pc,"PCGAMGSetRepartitioning_C",(PC,PetscBool),(pc,n));CHKERRQ(ierr);
914   PetscFunctionReturn(0);
915 }
916 
917 EXTERN_C_BEGIN
918 #undef __FUNCT__
919 #define __FUNCT__ "PCGAMGSetRepartitioning_GAMG"
920 PetscErrorCode PCGAMGSetRepartitioning_GAMG(PC pc, PetscBool n)
921 {
922   PC_MG           *mg = (PC_MG*)pc->data;
923   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
924 
925   PetscFunctionBegin;
926   pc_gamg->repart = n;
927   PetscFunctionReturn(0);
928 }
929 EXTERN_C_END
930 
931 #undef __FUNCT__
932 #define __FUNCT__ "PCGAMGSetNlevels"
933 /*@
934    PCGAMGSetNlevels -
935 
936    Not collective on PC
937 
938    Input Parameters:
939 .  pc - the preconditioner context
940 
941 
942    Options Database Key:
943 .  -pc_mg_levels
944 
945    Level: intermediate
946 
947    Concepts: Unstructured multrigrid preconditioner
948 
949 .seealso: ()
950 @*/
951 PetscErrorCode PCGAMGSetNlevels(PC pc, PetscInt n)
952 {
953   PetscErrorCode ierr;
954 
955   PetscFunctionBegin;
956   PetscValidHeaderSpecific(pc,PC_CLASSID,1);
957   ierr = PetscTryMethod(pc,"PCGAMGSetNlevels_C",(PC,PetscInt),(pc,n));CHKERRQ(ierr);
958   PetscFunctionReturn(0);
959 }
960 
961 EXTERN_C_BEGIN
962 #undef __FUNCT__
963 #define __FUNCT__ "PCGAMGSetNlevels_GAMG"
964 PetscErrorCode PCGAMGSetNlevels_GAMG(PC pc, PetscInt n)
965 {
966   PC_MG           *mg = (PC_MG*)pc->data;
967   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
968 
969   PetscFunctionBegin;
970   pc_gamg->Nlevels = n;
971   PetscFunctionReturn(0);
972 }
973 EXTERN_C_END
974 
975 #undef __FUNCT__
976 #define __FUNCT__ "PCGAMGSetThreshold"
977 /*@
978    PCGAMGSetThreshold - Relative threshold to use for dropping edges in aggregation graph
979 
980    Not collective on PC
981 
982    Input Parameters:
983 .  pc - the preconditioner context
984 
985 
986    Options Database Key:
987 .  -pc_gamg_threshold
988 
989    Level: intermediate
990 
991    Concepts: Unstructured multrigrid preconditioner
992 
993 .seealso: ()
994 @*/
995 PetscErrorCode PCGAMGSetThreshold(PC pc, PetscReal n)
996 {
997   PetscErrorCode ierr;
998 
999   PetscFunctionBegin;
1000   PetscValidHeaderSpecific(pc,PC_CLASSID,1);
1001   ierr = PetscTryMethod(pc,"PCGAMGSetThreshold_C",(PC,PetscReal),(pc,n));CHKERRQ(ierr);
1002   PetscFunctionReturn(0);
1003 }
1004 
1005 EXTERN_C_BEGIN
1006 #undef __FUNCT__
1007 #define __FUNCT__ "PCGAMGSetThreshold_GAMG"
1008 PetscErrorCode PCGAMGSetThreshold_GAMG(PC pc, PetscReal n)
1009 {
1010   PC_MG           *mg = (PC_MG*)pc->data;
1011   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
1012 
1013   PetscFunctionBegin;
1014   pc_gamg->threshold = n;
1015   PetscFunctionReturn(0);
1016 }
1017 EXTERN_C_END
1018 
1019 #undef __FUNCT__
1020 #define __FUNCT__ "PCGAMGSetType"
1021 /*@
1022    PCGAMGSetType - Set solution method - calls sub create method
1023 
1024    Collective on PC
1025 
1026    Input Parameters:
1027 .  pc - the preconditioner context
1028 
1029 
1030    Options Database Key:
1031 .  -pc_gamg_type
1032 
1033    Level: intermediate
1034 
1035    Concepts: Unstructured multrigrid preconditioner
1036 
1037 .seealso: ()
1038 @*/
1039 PetscErrorCode PCGAMGSetType( PC pc, const PCGAMGType type )
1040 {
1041   PetscErrorCode ierr;
1042 
1043   PetscFunctionBegin;
1044   PetscValidHeaderSpecific(pc,PC_CLASSID,1);
1045   ierr = PetscTryMethod(pc,"PCGAMGSetType_C",(PC,const PCGAMGType),(pc,type));
1046   CHKERRQ(ierr);
1047   PetscFunctionReturn(0);
1048 }
1049 
1050 EXTERN_C_BEGIN
1051 #undef __FUNCT__
1052 #define __FUNCT__ "PCGAMGSetType_GAMG"
1053 PetscErrorCode PCGAMGSetType_GAMG( PC pc, const PCGAMGType type )
1054 {
1055   PetscErrorCode ierr,(*r)(PC);
1056 
1057   PetscFunctionBegin;
1058   ierr = PetscFListFind(GAMGList,((PetscObject)pc)->comm,type,PETSC_FALSE,(PetscVoidStarFunction)&r);
1059   CHKERRQ(ierr);
1060 
1061   if (!r) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_ARG_UNKNOWN_TYPE,"Unknown GAMG type %s given",type);
1062 
1063   /* call sub create method */
1064   ierr = (*r)(pc); CHKERRQ(ierr);
1065 
1066   PetscFunctionReturn(0);
1067 }
1068 EXTERN_C_END
1069 
1070 #undef __FUNCT__
1071 #define __FUNCT__ "PCSetFromOptions_GAMG"
1072 PetscErrorCode PCSetFromOptions_GAMG( PC pc )
1073 {
1074   PetscErrorCode  ierr;
1075   PC_MG           *mg = (PC_MG*)pc->data;
1076   PC_GAMG         *pc_gamg = (PC_GAMG*)mg->innerctx;
1077   PetscBool        flag;
1078   MPI_Comm         wcomm = ((PetscObject)pc)->comm;
1079 
1080   PetscFunctionBegin;
1081   ierr = PetscOptionsHead("GAMG options"); CHKERRQ(ierr);
1082   {
1083     /* -pc_gamg_verbose */
1084     ierr = PetscOptionsInt("-pc_gamg_verbose","Verbose (debugging) output for PCGAMG",
1085                            "none", pc_gamg->verbose,
1086                            &pc_gamg->verbose, PETSC_NULL );
1087     CHKERRQ(ierr);
1088 
1089     /* -pc_gamg_repartition */
1090     ierr = PetscOptionsBool("-pc_gamg_repartition",
1091                             "Repartion coarse grids (false)",
1092                             "PCGAMGRepartitioning",
1093                             pc_gamg->repart,
1094                             &pc_gamg->repart,
1095                             &flag);
1096     CHKERRQ(ierr);
1097 
1098     /* -pc_gamg_process_eq_limit */
1099     ierr = PetscOptionsInt("-pc_gamg_process_eq_limit",
1100                            "Limit (goal) on number of equations per process on coarse grids",
1101                            "PCGAMGSetProcEqLim",
1102                            pc_gamg->min_eq_proc,
1103                            &pc_gamg->min_eq_proc,
1104                            &flag );
1105     CHKERRQ(ierr);
1106 
1107     /* -pc_gamg_coarse_eq_limit */
1108     ierr = PetscOptionsInt("-pc_gamg_coarse_eq_limit",
1109                            "Limit on number of equations for the coarse grid",
1110                            "PCGAMGSetCoarseEqLim",
1111                            pc_gamg->coarse_eq_limit,
1112                            &pc_gamg->coarse_eq_limit,
1113                            &flag );
1114     CHKERRQ(ierr);
1115 
1116     /* -pc_gamg_threshold */
1117     ierr = PetscOptionsReal("-pc_gamg_threshold",
1118                             "Relative threshold to use for dropping edges in aggregation graph",
1119                             "PCGAMGSetThreshold",
1120                             pc_gamg->threshold,
1121                             &pc_gamg->threshold,
1122                             &flag );
1123     CHKERRQ(ierr);
1124     if(flag && pc_gamg->verbose) PetscPrintf(wcomm,"\t[%d]%s threshold set %e\n",0,__FUNCT__,pc_gamg->threshold);
1125 
1126     ierr = PetscOptionsInt("-pc_mg_levels",
1127                            "Set number of MG levels",
1128                            "PCGAMGSetNlevels",
1129                            pc_gamg->Nlevels,
1130                            &pc_gamg->Nlevels,
1131                            &flag );
1132   }
1133   ierr = PetscOptionsTail();CHKERRQ(ierr);
1134 
1135   PetscFunctionReturn(0);
1136 }
1137 
1138 /* -------------------------------------------------------------------------- */
1139 /*MC
1140      PCCreate_GAMG - Geometric algebraic multigrid (AMG) preconditioning framework.
1141        - This is the entry point to GAMG, registered in pcregis.c
1142 
1143    Options Database Keys:
1144    Multigrid options(inherited)
1145 +  -pc_mg_cycles <1>: 1 for V cycle, 2 for W-cycle (PCMGSetCycleType)
1146 .  -pc_mg_smoothup <1>: Number of post-smoothing steps (PCMGSetNumberSmoothUp)
1147 .  -pc_mg_smoothdown <1>: Number of pre-smoothing steps (PCMGSetNumberSmoothDown)
1148 -  -pc_mg_type <multiplicative>: (one of) additive multiplicative full cascade kascade
1149 
1150   Level: intermediate
1151 
1152   Concepts: multigrid
1153 
1154 .seealso:  PCCreate(), PCSetType(), PCType (for list of available types), PC, PCMGType,
1155            PCMGSetLevels(), PCMGGetLevels(), PCMGSetType(), PCMGSetCycleType(), PCMGSetNumberSmoothDown(),
1156            PCMGSetNumberSmoothUp(), PCMGGetCoarseSolve(), PCMGSetResidual(), PCMGSetInterpolation(),
1157            PCMGSetRestriction(), PCMGGetSmoother(), PCMGGetSmootherUp(), PCMGGetSmootherDown(),
1158            PCMGSetCyclesOnLevel(), PCMGSetRhs(), PCMGSetX(), PCMGSetR()
1159 M*/
1160 EXTERN_C_BEGIN
1161 #undef __FUNCT__
1162 #define __FUNCT__ "PCCreate_GAMG"
1163 PetscErrorCode  PCCreate_GAMG( PC pc )
1164 {
1165   PetscErrorCode  ierr;
1166   PC_GAMG         *pc_gamg;
1167   PC_MG           *mg;
1168   PetscClassId     cookie;
1169 
1170 #if defined PETSC_USE_LOG
1171   static long count = 0;
1172 #endif
1173 
1174   PetscFunctionBegin;
1175   /* PCGAMG is an inherited class of PCMG. Initialize pc as PCMG */
1176   ierr = PCSetType( pc, PCMG );  CHKERRQ(ierr); /* calls PCCreate_MG() and MGCreate_Private() */
1177   ierr = PetscObjectChangeTypeName( (PetscObject)pc, PCGAMG ); CHKERRQ(ierr);
1178 
1179   /* create a supporting struct and attach it to pc */
1180   ierr = PetscNewLog( pc, PC_GAMG, &pc_gamg ); CHKERRQ(ierr);
1181   mg = (PC_MG*)pc->data;
1182   mg->galerkin = 2;             /* Use Galerkin, but it is computed externally */
1183   mg->innerctx = pc_gamg;
1184 
1185   pc_gamg->setup_count = 0;
1186   /* these should be in subctx but repartitioning needs simple arrays */
1187   pc_gamg->data_sz = 0;
1188   pc_gamg->data = 0;
1189 
1190   /* register AMG type */
1191   if( !GAMGList ){
1192     ierr = PetscFListAdd(&GAMGList,GAMGGEO,"PCCreateGAMG_GEO",(void(*)(void))PCCreateGAMG_GEO);CHKERRQ(ierr);
1193     ierr = PetscFListAdd(&GAMGList,GAMGAGG,"PCCreateGAMG_AGG",(void(*)(void))PCCreateGAMG_AGG);CHKERRQ(ierr);
1194   }
1195 
1196   /* overwrite the pointers of PCMG by the functions of base class PCGAMG */
1197   pc->ops->setfromoptions = PCSetFromOptions_GAMG;
1198   pc->ops->setup          = PCSetUp_GAMG;
1199   pc->ops->reset          = PCReset_GAMG;
1200   pc->ops->destroy        = PCDestroy_GAMG;
1201 
1202   ierr = PetscObjectComposeFunctionDynamic( (PetscObject)pc,
1203 					    "PCGAMGSetProcEqLim_C",
1204 					    "PCGAMGSetProcEqLim_GAMG",
1205 					    PCGAMGSetProcEqLim_GAMG);
1206   CHKERRQ(ierr);
1207 
1208   ierr = PetscObjectComposeFunctionDynamic( (PetscObject)pc,
1209 					    "PCGAMGSetCoarseEqLim_C",
1210 					    "PCGAMGSetCoarseEqLim_GAMG",
1211 					    PCGAMGSetCoarseEqLim_GAMG);
1212   CHKERRQ(ierr);
1213 
1214   ierr = PetscObjectComposeFunctionDynamic( (PetscObject)pc,
1215 					    "PCGAMGSetRepartitioning_C",
1216 					    "PCGAMGSetRepartitioning_GAMG",
1217 					    PCGAMGSetRepartitioning_GAMG);
1218   CHKERRQ(ierr);
1219 
1220   ierr = PetscObjectComposeFunctionDynamic( (PetscObject)pc,
1221 					    "PCGAMGSetThreshold_C",
1222 					    "PCGAMGSetThreshold_GAMG",
1223 					    PCGAMGSetThreshold_GAMG);
1224   CHKERRQ(ierr);
1225 
1226   ierr = PetscObjectComposeFunctionDynamic( (PetscObject)pc,
1227 					    "PCGAMGSetType_C",
1228 					    "PCGAMGSetType_GAMG",
1229 					    PCGAMGSetType_GAMG);
1230   CHKERRQ(ierr);
1231 
1232   pc_gamg->repart = PETSC_FALSE;
1233   pc_gamg->min_eq_proc = 100;
1234   pc_gamg->coarse_eq_limit = 800;
1235   pc_gamg->threshold = 0.05;
1236   pc_gamg->Nlevels = GAMG_MAXLEVELS;
1237   pc_gamg->verbose = 0;
1238   pc_gamg->emax_id = -1;
1239   pc_gamg->col_bs_id = -1;
1240 
1241   /* instantiate derived type */
1242   ierr = PetscOptionsHead("GAMG options"); CHKERRQ(ierr);
1243   {
1244     char tname[256] = GAMGAGG;
1245     ierr = PetscOptionsList("-pc_gamg_type","Type of GAMG method","PCGAMGSetType",
1246                             GAMGList, tname, tname, sizeof(tname), PETSC_NULL );
1247     CHKERRQ(ierr);
1248     ierr = PCGAMGSetType( pc, tname ); CHKERRQ(ierr);
1249   }
1250   ierr = PetscOptionsTail();CHKERRQ(ierr);
1251 
1252 #if defined PETSC_USE_LOG
1253   if( count++ == 0 ) {
1254     PetscClassIdRegister("GAMG Setup",&cookie);
1255     PetscLogEventRegister("GAMG: createProl", cookie, &gamg_setup_events[SET1]);
1256     PetscLogEventRegister("  Graph", cookie, &gamg_setup_events[GRAPH]);
1257     /* PetscLogEventRegister("    G.Mat", cookie, &gamg_setup_events[GRAPH_MAT]); */
1258     /* PetscLogEventRegister("    G.Filter", cookie, &gamg_setup_events[GRAPH_FILTER]); */
1259     /* PetscLogEventRegister("    G.Square", cookie, &gamg_setup_events[GRAPH_SQR]); */
1260     PetscLogEventRegister("  MIS/Agg", cookie, &gamg_setup_events[SET4]);
1261     PetscLogEventRegister("  geo: growSupp", cookie, &gamg_setup_events[SET5]);
1262     PetscLogEventRegister("  geo: triangle", cookie, &gamg_setup_events[SET6]);
1263     PetscLogEventRegister("    search&set", cookie, &gamg_setup_events[FIND_V]);
1264     PetscLogEventRegister("  SA: colect data", cookie, &gamg_setup_events[SET7]);
1265     PetscLogEventRegister("  SA: frmProl0", cookie, &gamg_setup_events[SET8]);
1266     PetscLogEventRegister("  SA: smooth", cookie, &gamg_setup_events[SET9]);
1267     PetscLogEventRegister("GAMG: partLevel", cookie, &gamg_setup_events[SET2]);
1268     PetscLogEventRegister("  repartition", cookie, &gamg_setup_events[SET12]);
1269     PetscLogEventRegister("  Invert-Sort", cookie, &gamg_setup_events[SET13]);
1270     PetscLogEventRegister("  Move A", cookie, &gamg_setup_events[SET14]);
1271     PetscLogEventRegister("  Move P", cookie, &gamg_setup_events[SET15]);
1272 
1273     /* PetscLogEventRegister(" PL move data", cookie, &gamg_setup_events[SET13]); */
1274     /* PetscLogEventRegister("GAMG: fix", cookie, &gamg_setup_events[SET10]); */
1275     /* PetscLogEventRegister("GAMG: set levels", cookie, &gamg_setup_events[SET11]); */
1276     /* create timer stages */
1277 #if defined GAMG_STAGES
1278     {
1279       char str[32];
1280       sprintf(str,"MG Level %d (finest)",0);
1281       PetscLogStageRegister(str, &gamg_stages[0]);
1282       PetscInt lidx;
1283       for (lidx=1;lidx<9;lidx++){
1284 	sprintf(str,"MG Level %d",lidx);
1285 	PetscLogStageRegister(str, &gamg_stages[lidx]);
1286       }
1287     }
1288 #endif
1289   }
1290 #endif
1291   PetscFunctionReturn(0);
1292 }
1293 EXTERN_C_END
1294