Actual source code: geo.c

  1: /*
  2:  GAMG geometric-algebraic multigrid PC - Mark Adams 2011
  3:  */

  5: #include <../src/ksp/pc/impls/gamg/gamg.h>

  7: #if PetscDefined(HAVE_TRIANGLE)
  8:   #if !defined(ANSI_DECLARATORS)
  9:     #define ANSI_DECLARATORS
 10:   #endif
 11:   #include <triangle.h>
 12: #endif

 14: #include <petscblaslapack.h>

 16: /* Private context for the GAMG preconditioner */
 17: typedef struct {
 18:   PetscInt lid;    /* local vertex index */
 19:   PetscInt degree; /* vertex degree */
 20: } GAMGNode;

 22: static inline int petsc_geo_mg_compare(const void *a, const void *b)
 23: {
 24:   return (int)(((GAMGNode *)a)->degree - ((GAMGNode *)b)->degree);
 25: }

 27: // PetscClangLinter pragma disable: -fdoc-sowing-chars
 28: /*
 29:    PCSetCoordinates_GEO

 31:    Input Parameter:
 32:    .  pc - the preconditioner context
 33: */
 34: static PetscErrorCode PCSetCoordinates_GEO(PC pc, PetscInt ndm, PetscInt a_nloc, PetscReal *coords)
 35: {
 36:   PC_MG   *mg      = (PC_MG *)pc->data;
 37:   PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
 38:   PetscInt arrsz, bs, my0, kk, ii, nloc, Iend, aloc;
 39:   Mat      Amat = pc->pmat;

 41:   PetscFunctionBegin;
 43:   PetscCall(MatGetBlockSize(Amat, &bs));
 44:   PetscCall(MatGetOwnershipRange(Amat, &my0, &Iend));
 45:   aloc = (Iend - my0);
 46:   nloc = (Iend - my0) / bs;

 48:   PetscCheck(nloc == a_nloc || aloc == a_nloc, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of local blocks %" PetscInt_FMT " must be %" PetscInt_FMT " or %" PetscInt_FMT ".", a_nloc, nloc, aloc);

 50:   pc_gamg->data_cell_rows = 1;
 51:   PetscCheck(coords || (nloc <= 0), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Need coordinates for pc_gamg_type 'geo'.");
 52:   pc_gamg->data_cell_cols = ndm; /* coordinates */

 54:   arrsz = nloc * pc_gamg->data_cell_rows * pc_gamg->data_cell_cols;

 56:   /* create data - syntactic sugar that should be refactored at some point */
 57:   if (!pc_gamg->data || (pc_gamg->data_sz != arrsz)) {
 58:     PetscCall(PetscFree(pc_gamg->data));
 59:     PetscCall(PetscMalloc1(arrsz + 1, &pc_gamg->data));
 60:   }
 61:   for (kk = 0; kk < arrsz; kk++) pc_gamg->data[kk] = -999.;
 62:   pc_gamg->data[arrsz] = -99.;
 63:   /* copy data in - column-oriented */
 64:   if (nloc == a_nloc) {
 65:     for (kk = 0; kk < nloc; kk++) {
 66:       for (ii = 0; ii < ndm; ii++) pc_gamg->data[ii * nloc + kk] = coords[kk * ndm + ii];
 67:     }
 68:   } else { /* assumes the coordinates are blocked */
 69:     for (kk = 0; kk < nloc; kk++) {
 70:       for (ii = 0; ii < ndm; ii++) pc_gamg->data[ii * nloc + kk] = coords[bs * kk * ndm + ii];
 71:     }
 72:   }
 73:   PetscCheck(pc_gamg->data[arrsz] == -99., PETSC_COMM_SELF, PETSC_ERR_PLIB, "pc_gamg->data[arrsz %" PetscInt_FMT "] %g != -99.", arrsz, (double)pc_gamg->data[arrsz]);
 74:   pc_gamg->data_sz = arrsz;
 75:   PetscFunctionReturn(PETSC_SUCCESS);
 76: }

 78: // PetscClangLinter pragma disable: -fdoc-sowing-chars
 79: /*
 80:    PCSetData_GEO

 82:   Input Parameter:
 83:    . pc -
 84: */
 85: static PetscErrorCode PCSetData_GEO(PC pc, Mat m)
 86: {
 87:   PetscFunctionBegin;
 88:   SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "GEO MG needs coordinates");
 89: }

 91: static PetscErrorCode PCSetFromOptions_GEO(PC pc, PetscOptionItems PetscOptionsObject)
 92: {
 93:   PetscFunctionBegin;
 94:   PetscOptionsHeadBegin(PetscOptionsObject, "GAMG-GEO options");
 95:   {
 96:     /* -pc_gamg_sa_nsmooths */
 97:     /* pc_gamg_sa->smooths = 0; */
 98:     /* ierr = PetscOptionsInt("-pc_gamg_agg_nsmooths", */
 99:     /*                        "smoothing steps for smoothed aggregation, usually 1 (0)", */
100:     /*                        "PCGAMGSetNSmooths_AGG", */
101:     /*                        pc_gamg_sa->smooths, */
102:     /*                        &pc_gamg_sa->smooths, */
103:     /*                        &flag);  */
104:   }
105:   PetscOptionsHeadEnd();
106:   PetscFunctionReturn(PETSC_SUCCESS);
107: }

109: // PetscClangLinter pragma disable: -fdoc-sowing-chars
110: /*
111:  triangulateAndFormProl

113:    Input Parameter:
114:    . selected_2 - list of selected local ID, includes selected ghosts
115:    . data_stride -
116:    . coords[2*data_stride] - column vector of local coordinates w/ ghosts
117:    . nselected_1 - selected IDs that go with base (1) graph includes selected ghosts
118:    . clid_lid_1[nselected_1] - lids of selected (c) nodes   ???????????
119:    . agg_lists_1 - list of aggregates selected_1 vertices of aggregate unselected vertices
120:    . crsGID[selected.size()] - global index for prolongation operator
121:    . bs - block size
122:   Output Parameter:
123:    . a_Prol - prolongation operator
124:    . a_worst_best - measure of worst missed fine vertex, 0 is no misses
125: */
126: static PetscErrorCode triangulateAndFormProl(IS selected_2, PetscInt data_stride, PetscReal coords[], PetscInt nselected_1, const PetscInt clid_lid_1[], const PetscCoarsenData *agg_lists_1, const PetscInt crsGID[], PetscInt bs, Mat a_Prol, PetscReal *a_worst_best)
127: {
128: #if PetscDefined(HAVE_TRIANGLE)
129:   PetscInt             jj, tid, tt, idx, nselected_2;
130:   struct triangulateio in, mid;
131:   const PetscInt      *selected_idx_2;
132:   PetscMPIInt          rank;
133:   PetscInt             Istart, Iend, nFineLoc, myFine0;
134:   int                  kk, nPlotPts, sid;
135:   MPI_Comm             comm;

137:   PetscFunctionBegin;
138:   PetscCall(PetscObjectGetComm((PetscObject)a_Prol, &comm));
139:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
140:   PetscCall(ISGetSize(selected_2, &nselected_2));
141:   if (nselected_2 == 1 || nselected_2 == 2) { /* 0 happens on idle processors */
142:     *a_worst_best = 100.0;                    /* this will cause a stop, but not globalized (should not happen) */
143:   } else *a_worst_best = 0.0;
144:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, a_worst_best, 1, MPIU_REAL, MPIU_MAX, comm));
145:   if (*a_worst_best > 0.0) {
146:     *a_worst_best = 100.0;
147:     PetscFunctionReturn(PETSC_SUCCESS);
148:   }
149:   PetscCall(MatGetOwnershipRange(a_Prol, &Istart, &Iend));
150:   nFineLoc = (Iend - Istart) / bs;
151:   myFine0  = Istart / bs;
152:   PetscCall(PetscCIntCast(nFineLoc, &nPlotPts)); /* locals */
153:   /* triangle */
154:   /* Define input points - in */
155:   PetscCall(PetscCIntCast(nselected_2, &in.numberofpoints));
156:   in.numberofpointattributes = 0;
157:   /* get nselected points */
158:   PetscCall(PetscMalloc1(2 * nselected_2, &in.pointlist));
159:   PetscCall(ISGetIndices(selected_2, &selected_idx_2));

161:   for (kk = 0, sid = 0; kk < nselected_2; kk++, sid += 2) {
162:     PetscInt lid          = selected_idx_2[kk];
163:     in.pointlist[sid]     = coords[lid];
164:     in.pointlist[sid + 1] = coords[data_stride + lid];
165:     if (lid >= nFineLoc) nPlotPts++;
166:   }
167:   PetscCheck(sid == 2 * nselected_2, PETSC_COMM_SELF, PETSC_ERR_PLIB, "sid %d != 2*nselected_2 %" PetscInt_FMT, sid, nselected_2);

169:   in.numberofsegments      = 0;
170:   in.numberofedges         = 0;
171:   in.numberofholes         = 0;
172:   in.numberofregions       = 0;
173:   in.trianglelist          = NULL;
174:   in.segmentmarkerlist     = NULL;
175:   in.pointattributelist    = NULL;
176:   in.pointmarkerlist       = NULL;
177:   in.triangleattributelist = NULL;
178:   in.trianglearealist      = NULL;
179:   in.segmentlist           = NULL;
180:   in.holelist              = NULL;
181:   in.regionlist            = NULL;
182:   in.edgelist              = NULL;
183:   in.edgemarkerlist        = NULL;
184:   in.normlist              = NULL;

186:   /* triangulate */
187:   mid.pointlist = NULL; /* Not needed if -N switch used. */
188:   /* Not needed if -N switch used or number of point attributes is zero: */
189:   mid.pointattributelist = NULL;
190:   mid.pointmarkerlist    = NULL; /* Not needed if -N or -B switch used. */
191:   mid.trianglelist       = NULL; /* Not needed if -E switch used. */
192:   /* Not needed if -E switch used or number of triangle attributes is zero: */
193:   mid.triangleattributelist = NULL;
194:   mid.neighborlist          = NULL; /* Needed only if -n switch used. */
195:   /* Needed only if segments are output (-p or -c) and -P not used: */
196:   mid.segmentlist = NULL;
197:   /* Needed only if segments are output (-p or -c) and -P and -B not used: */
198:   mid.segmentmarkerlist = NULL;
199:   mid.edgelist          = NULL; /* Needed only if -e switch used. */
200:   mid.edgemarkerlist    = NULL; /* Needed if -e used and -B not used. */
201:   mid.numberoftriangles = 0;

203:   /* Triangulate the points.  Switches are chosen to read and write a  */
204:   /*   PSLG (p), preserve the convex hull (c), number everything from  */
205:   /*   zero (z), assign a regional attribute to each element (A), and  */
206:   /*   produce an edge list (e), a Voronoi diagram (v), and a triangle */
207:   /*   neighbor list (n).                                            */
208:   if (nselected_2 != 0) {  /* inactive processor */
209:     char args[] = "npczQ"; /* c is needed ? */
210:     triangulate(args, &in, &mid, (struct triangulateio *)NULL);
211:     /* output .poly files for 'showme' */
212:     if (!PETSC_TRUE) {
213:       static int level = 1;
214:       FILE      *file;
215:       char       fname[32];

217:       PetscCall(PetscSNPrintf(fname, PETSC_STATIC_ARRAY_LENGTH(fname), "C%d_%d.poly", level, rank));
218:       file = fopen(fname, "w");
219:       /* First line: <# of vertices> <dimension (must be 2)> <# of attributes> <# of boundary markers (0 or 1)> */
220:       fprintf(file, "%d  %d  %d  %d\n", in.numberofpoints, 2, 0, 0);
221:       /* Following lines: <vertex #> <x> <y> */
222:       for (kk = 0, sid = 0; kk < in.numberofpoints; kk++, sid += 2) fprintf(file, "%d %e %e\n", kk, in.pointlist[sid], in.pointlist[sid + 1]);
223:       /* One line: <# of segments> <# of boundary markers (0 or 1)> */
224:       fprintf(file, "%d  %d\n", 0, 0);
225:       /* Following lines: <segment #> <endpoint> <endpoint> [boundary marker] */
226:       /* One line: <# of holes> */
227:       fprintf(file, "%d\n", 0);
228:       /* Following lines: <hole #> <x> <y> */
229:       /* Optional line: <# of regional attributes and/or area constraints> */
230:       /* Optional following lines: <region #> <x> <y> <attribute> <maximum area> */
231:       fclose(file);

233:       /* elems */
234:       PetscCall(PetscSNPrintf(fname, PETSC_STATIC_ARRAY_LENGTH(fname), "C%d_%d.ele", level, rank));
235:       file = fopen(fname, "w");
236:       /* First line: <# of triangles> <nodes per triangle> <# of attributes> */
237:       fprintf(file, "%d %d %d\n", mid.numberoftriangles, 3, 0);
238:       /* Remaining lines: <triangle #> <node> <node> <node> ... [attributes] */
239:       for (kk = 0, sid = 0; kk < mid.numberoftriangles; kk++, sid += 3) fprintf(file, "%d %d %d %d\n", kk, mid.trianglelist[sid], mid.trianglelist[sid + 1], mid.trianglelist[sid + 2]);
240:       fclose(file);

242:       PetscCall(PetscSNPrintf(fname, PETSC_STATIC_ARRAY_LENGTH(fname), "C%d_%d.node", level, rank));
243:       file = fopen(fname, "w");
244:       /* First line: <# of vertices> <dimension (must be 2)> <# of attributes> <# of boundary markers (0 or 1)> */
245:       /* fprintf(file, "%d  %d  %d  %d\n",in.numberofpoints,2,0,0); */
246:       fprintf(file, "%d  %d  %d  %d\n", nPlotPts, 2, 0, 0);
247:       /* Following lines: <vertex #> <x> <y> */
248:       for (kk = 0, sid = 0; kk < in.numberofpoints; kk++, sid += 2) fprintf(file, "%d %e %e\n", kk, in.pointlist[sid], in.pointlist[sid + 1]);

250:       sid /= 2;
251:       for (jj = 0; jj < nFineLoc; jj++) {
252:         PetscBool sel = PETSC_TRUE;
253:         for (kk = 0; kk < nselected_2 && sel; kk++) {
254:           PetscInt lid = selected_idx_2[kk];
255:           if (lid == jj) sel = PETSC_FALSE;
256:         }
257:         if (sel) fprintf(file, "%d %e %e\n", sid++, (double)coords[jj], (double)coords[data_stride + jj]);
258:       }
259:       fclose(file);
260:       PetscCheck(sid == nPlotPts, PETSC_COMM_SELF, PETSC_ERR_PLIB, "sid %d != nPlotPts %d", sid, nPlotPts);
261:       level++;
262:     }
263:   }
264:   { /* form P - setup some maps */
265:     PetscInt clid, mm, *nTri, *node_tri;

267:     PetscCall(PetscMalloc2(nselected_2, &node_tri, nselected_2, &nTri));

269:     /* need list of triangles on node */
270:     for (kk = 0; kk < nselected_2; kk++) nTri[kk] = 0;
271:     for (tid = 0, kk = 0; tid < mid.numberoftriangles; tid++) {
272:       for (jj = 0; jj < 3; jj++) {
273:         PetscInt cid = mid.trianglelist[kk++];
274:         if (nTri[cid] == 0) node_tri[cid] = tid;
275:         nTri[cid]++;
276:       }
277:     }
278:   #define EPS 1.e-12
279:     /* find points and set prolongation */
280:     for (mm = clid = 0; mm < nFineLoc; mm++) {
281:       PetscBool ise;
282:       PetscCall(PetscCDIsEmptyAt(agg_lists_1, mm, &ise));
283:       if (!ise) {
284:         const PetscInt lid = mm;
285:         PetscScalar    AA[3][3];
286:         PetscBLASInt   N = 3, NRHS = 1, LDA = 3, IPIV[3], LDB = 3;
287:         PetscCDIntNd  *pos;

289:         PetscCall(PetscCDGetHeadPos(agg_lists_1, lid, &pos));
290:         while (pos) {
291:           PetscInt flid;
292:           PetscCall(PetscCDIntNdGetID(pos, &flid));
293:           PetscCall(PetscCDGetNextPos(agg_lists_1, lid, &pos));

295:           if (flid < nFineLoc) { /* could be a ghost */
296:             PetscInt       bestTID    = -1;
297:             PetscReal      best_alpha = 1.e10;
298:             const PetscInt fgid       = flid + myFine0;
299:             /* compute shape function for gid */
300:             const PetscReal fcoord[3] = {coords[flid], coords[data_stride + flid], 1.0};
301:             PetscBool       haveit    = PETSC_FALSE;
302:             PetscScalar     alpha[3];
303:             PetscInt        clids[3];

305:             /* look for it */
306:             for (tid = node_tri[clid], jj = 0; jj < 5 && !haveit && tid != -1; jj++) {
307:               for (tt = 0; tt < 3; tt++) {
308:                 PetscInt cid2 = mid.trianglelist[3 * tid + tt];
309:                 PetscInt lid2 = selected_idx_2[cid2];
310:                 AA[tt][0]     = coords[lid2];
311:                 AA[tt][1]     = coords[data_stride + lid2];
312:                 AA[tt][2]     = 1.0;
313:                 clids[tt]     = cid2; /* store for interp */
314:               }

316:               for (tt = 0; tt < 3; tt++) alpha[tt] = (PetscScalar)fcoord[tt];

318:               PetscCallLAPACKInfo("LAPACKgesv", LAPACKgesv_(&N, &NRHS, (PetscScalar *)AA, &LDA, IPIV, alpha, &LDB, &info));
319:               {
320:                 PetscBool have   = PETSC_TRUE;
321:                 PetscReal lowest = 1.e10;
322:                 for (tt = 0, idx = 0; tt < 3; tt++) {
323:                   if (PetscRealPart(alpha[tt]) > (1.0 + EPS) || PetscRealPart(alpha[tt]) < -EPS) have = PETSC_FALSE;
324:                   if (PetscRealPart(alpha[tt]) < lowest) {
325:                     lowest = PetscRealPart(alpha[tt]);
326:                     idx    = tt;
327:                   }
328:                 }
329:                 haveit = have;
330:               }
331:               tid = mid.neighborlist[3 * tid + idx];
332:             }

334:             if (!haveit) {
335:               /* brute force */
336:               for (tid = 0; tid < mid.numberoftriangles && !haveit; tid++) {
337:                 for (tt = 0; tt < 3; tt++) {
338:                   PetscInt cid2 = mid.trianglelist[3 * tid + tt];
339:                   PetscInt lid2 = selected_idx_2[cid2];
340:                   AA[tt][0]     = coords[lid2];
341:                   AA[tt][1]     = coords[data_stride + lid2];
342:                   AA[tt][2]     = 1.0;
343:                   clids[tt]     = cid2; /* store for interp */
344:                 }
345:                 for (tt = 0; tt < 3; tt++) alpha[tt] = fcoord[tt];
346:                 PetscCallLAPACKInfo("LAPACKgesv", LAPACKgesv_(&N, &NRHS, (PetscScalar *)AA, &LDA, IPIV, alpha, &LDB, &info));
347:                 {
348:                   PetscBool have  = PETSC_TRUE;
349:                   PetscReal worst = 0.0, v;
350:                   for (tt = 0; tt < 3 && have; tt++) {
351:                     if (PetscRealPart(alpha[tt]) > 1.0 + EPS || PetscRealPart(alpha[tt]) < -EPS) have = PETSC_FALSE;
352:                     if ((v = PetscAbs(PetscRealPart(alpha[tt]) - 0.5)) > worst) worst = v;
353:                   }
354:                   if (worst < best_alpha) {
355:                     best_alpha = worst;
356:                     bestTID    = tid;
357:                   }
358:                   haveit = have;
359:                 }
360:               }
361:             }
362:             if (!haveit) {
363:               if (best_alpha > *a_worst_best) *a_worst_best = best_alpha;
364:               /* use best one */
365:               for (tt = 0; tt < 3; tt++) {
366:                 PetscInt cid2 = mid.trianglelist[3 * bestTID + tt];
367:                 PetscInt lid2 = selected_idx_2[cid2];
368:                 AA[tt][0]     = coords[lid2];
369:                 AA[tt][1]     = coords[data_stride + lid2];
370:                 AA[tt][2]     = 1.0;
371:                 clids[tt]     = cid2; /* store for interp */
372:               }
373:               for (tt = 0; tt < 3; tt++) alpha[tt] = fcoord[tt];
374:               PetscCallLAPACKInfo("LAPACKgesv", LAPACKgesv_(&N, &NRHS, (PetscScalar *)AA, &LDA, IPIV, alpha, &LDB, &info));
375:             }

377:             /* put in row of P */
378:             for (idx = 0; idx < 3; idx++) {
379:               PetscScalar shp = alpha[idx];
380:               if (PetscAbs(PetscRealPart(shp)) > 1.e-6) {
381:                 PetscInt cgid = crsGID[clids[idx]];
382:                 PetscInt jj = cgid * bs, ii = fgid * bs; /* need to gloalize */
383:                 for (tt = 0; tt < bs; tt++, ii++, jj++) PetscCall(MatSetValues(a_Prol, 1, &ii, 1, &jj, &shp, INSERT_VALUES));
384:               }
385:             }
386:           }
387:         } /* aggregates iterations */
388:         clid++;
389:       } /* a coarse agg */
390:     } /* for all fine nodes */

392:     PetscCall(ISRestoreIndices(selected_2, &selected_idx_2));
393:     PetscCall(MatAssemblyBegin(a_Prol, MAT_FINAL_ASSEMBLY));
394:     PetscCall(MatAssemblyEnd(a_Prol, MAT_FINAL_ASSEMBLY));

396:     PetscCall(PetscFree2(node_tri, nTri));
397:   }
398:   free(mid.trianglelist);
399:   free(mid.neighborlist);
400:   free(mid.segmentlist);
401:   free(mid.segmentmarkerlist);
402:   free(mid.pointlist);
403:   free(mid.pointmarkerlist);
404:   PetscCall(PetscFree(in.pointlist));
405:   PetscFunctionReturn(PETSC_SUCCESS);
406: #else
407:   SETERRQ(PetscObjectComm((PetscObject)a_Prol), PETSC_ERR_PLIB, "configure with TRIANGLE to use geometric MG");
408: #endif
409: }

411: // PetscClangLinter pragma disable: -fdoc-sowing-chars
412: /*
413:    getGIDsOnSquareGraph - square graph, get

415:    Input Parameter:
416:    . nselected_1 - selected local indices (includes ghosts in input Gmat1)
417:    . clid_lid_1 - [nselected_1] lids of selected nodes
418:    . Gmat1 - graph that goes with 'selected_1'
419:    Output Parameter:
420:    . a_selected_2 - selected local indices (includes ghosts in output a_Gmat_2)
421:    . a_Gmat_2 - graph that is squared of 'Gmat_1'
422:    . a_crsGID[a_selected_2.size()] - map of global IDs of coarse grid nodes
423: */
424: static PetscErrorCode getGIDsOnSquareGraph(PC pc, PetscInt nselected_1, const PetscInt clid_lid_1[], const Mat Gmat1, IS *a_selected_2, Mat *a_Gmat_2, PetscInt **a_crsGID)
425: {
426:   PetscMPIInt size;
427:   PetscInt   *crsGID, kk, my0, Iend, nloc;
428:   MPI_Comm    comm;

430:   PetscFunctionBegin;
431:   PetscCall(PetscObjectGetComm((PetscObject)Gmat1, &comm));
432:   PetscCallMPI(MPI_Comm_size(comm, &size));
433:   PetscCall(MatGetOwnershipRange(Gmat1, &my0, &Iend)); /* AIJ */
434:   nloc = Iend - my0;                                   /* this does not change */

436:   if (size == 1) { /* not much to do in serial */
437:     PetscCall(PetscMalloc1(nselected_1, &crsGID));
438:     for (kk = 0; kk < nselected_1; kk++) crsGID[kk] = kk;
439:     *a_Gmat_2 = NULL;
440:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nselected_1, clid_lid_1, PETSC_COPY_VALUES, a_selected_2));
441:   } else {
442:     PetscInt     idx, num_fine_ghosts, num_crs_ghost, myCrs0;
443:     Mat_MPIAIJ  *mpimat2;
444:     Mat          Gmat2;
445:     Vec          locState;
446:     PetscScalar *cpcol_state;

448:     /* scan my coarse zero gid, set 'lid_state' with coarse GID */
449:     kk = nselected_1;
450:     PetscCallMPI(MPI_Scan(&kk, &myCrs0, 1, MPIU_INT, MPI_SUM, comm));
451:     myCrs0 -= nselected_1;

453:     if (a_Gmat_2) { /* output */
454:       /* grow graph to get wider set of selected vertices to cover fine grid, invalidates 'llist' */
455:       PetscCall(PCGAMGSquareGraph_GAMG(pc, Gmat1, &Gmat2));
456:       *a_Gmat_2 = Gmat2;  /* output */
457:     } else Gmat2 = Gmat1; /* use local to get crsGIDs at least */
458:     /* get coarse grid GIDS for selected (locals and ghosts) */
459:     mpimat2 = (Mat_MPIAIJ *)Gmat2->data;
460:     PetscCall(MatCreateVecs(Gmat2, &locState, NULL));
461:     PetscCall(VecSet(locState, -1)); /* set with UNKNOWN state */
462:     for (kk = 0; kk < nselected_1; kk++) {
463:       PetscInt    fgid = clid_lid_1[kk] + my0;
464:       PetscScalar v    = (PetscScalar)(kk + myCrs0);
465:       PetscCall(VecSetValues(locState, 1, &fgid, &v, INSERT_VALUES)); /* set with PID */
466:     }
467:     PetscCall(VecAssemblyBegin(locState));
468:     PetscCall(VecAssemblyEnd(locState));
469:     PetscCall(VecScatterBegin(mpimat2->Mvctx, locState, mpimat2->lvec, INSERT_VALUES, SCATTER_FORWARD));
470:     PetscCall(VecScatterEnd(mpimat2->Mvctx, locState, mpimat2->lvec, INSERT_VALUES, SCATTER_FORWARD));
471:     PetscCall(VecGetLocalSize(mpimat2->lvec, &num_fine_ghosts));
472:     PetscCall(VecGetArray(mpimat2->lvec, &cpcol_state));
473:     for (kk = 0, num_crs_ghost = 0; kk < num_fine_ghosts; kk++) {
474:       if ((PetscInt)PetscRealPart(cpcol_state[kk]) != -1) num_crs_ghost++;
475:     }
476:     PetscCall(PetscMalloc1(nselected_1 + num_crs_ghost, &crsGID)); /* output */
477:     {
478:       PetscInt *selected_set;
479:       PetscCall(PetscMalloc1(nselected_1 + num_crs_ghost, &selected_set));
480:       /* do ghost of 'crsGID' */
481:       for (kk = 0, idx = nselected_1; kk < num_fine_ghosts; kk++) {
482:         if ((PetscInt)PetscRealPart(cpcol_state[kk]) != -1) {
483:           PetscInt cgid     = (PetscInt)PetscRealPart(cpcol_state[kk]);
484:           selected_set[idx] = nloc + kk;
485:           crsGID[idx++]     = cgid;
486:         }
487:       }
488:       PetscCheck(idx == (nselected_1 + num_crs_ghost), PETSC_COMM_SELF, PETSC_ERR_PLIB, "idx %" PetscInt_FMT " != (nselected_1 %" PetscInt_FMT " + num_crs_ghost %" PetscInt_FMT ")", idx, nselected_1, num_crs_ghost);
489:       PetscCall(VecRestoreArray(mpimat2->lvec, &cpcol_state));
490:       /* do locals in 'crsGID' */
491:       PetscCall(VecGetArray(locState, &cpcol_state));
492:       for (kk = 0, idx = 0; kk < nloc; kk++) {
493:         if ((PetscInt)PetscRealPart(cpcol_state[kk]) != -1) {
494:           PetscInt cgid     = (PetscInt)PetscRealPart(cpcol_state[kk]);
495:           selected_set[idx] = kk;
496:           crsGID[idx++]     = cgid;
497:         }
498:       }
499:       PetscCheck(idx == nselected_1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "idx %" PetscInt_FMT " != nselected_1 %" PetscInt_FMT, idx, nselected_1);
500:       PetscCall(VecRestoreArray(locState, &cpcol_state));

502:       if (a_selected_2 != NULL) { /* output */
503:         PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nselected_1 + num_crs_ghost, selected_set, PETSC_OWN_POINTER, a_selected_2));
504:       } else {
505:         PetscCall(PetscFree(selected_set));
506:       }
507:     }
508:     PetscCall(VecDestroy(&locState));
509:   }
510:   *a_crsGID = crsGID; /* output */
511:   PetscFunctionReturn(PETSC_SUCCESS);
512: }

514: static PetscErrorCode PCGAMGCreateGraph_GEO(PC pc, Mat Amat, Mat *a_Gmat)
515: {
516:   PC_MG          *mg      = (PC_MG *)pc->data;
517:   PC_GAMG        *pc_gamg = (PC_GAMG *)mg->innerctx;
518:   const PetscReal vfilter = pc_gamg->threshold[0];

520:   PetscFunctionBegin;
521:   PetscCall(MatCreateGraph(Amat, PETSC_TRUE, PETSC_TRUE, vfilter, 0, NULL, a_Gmat));
522:   PetscFunctionReturn(PETSC_SUCCESS);
523: }

525: static PetscErrorCode PCGAMGCoarsen_GEO(PC a_pc, Mat *a_Gmat, PetscCoarsenData **a_llist_parent)
526: {
527:   PetscInt   Istart, Iend, nloc, kk, Ii, ncols;
528:   IS         perm;
529:   GAMGNode  *gnodes;
530:   PetscInt  *permute;
531:   Mat        Gmat = *a_Gmat;
532:   MPI_Comm   comm;
533:   MatCoarsen crs;

535:   PetscFunctionBegin;
536:   PetscCall(PetscObjectGetComm((PetscObject)a_pc, &comm));

538:   PetscCall(MatGetOwnershipRange(Gmat, &Istart, &Iend));
539:   nloc = (Iend - Istart);

541:   /* create random permutation with sort for geo-mg */
542:   PetscCall(PetscMalloc1(nloc, &gnodes));
543:   PetscCall(PetscMalloc1(nloc, &permute));

545:   for (Ii = Istart; Ii < Iend; Ii++) { /* locals only? */
546:     PetscCall(MatGetRow(Gmat, Ii, &ncols, NULL, NULL));
547:     {
548:       PetscInt lid       = Ii - Istart;
549:       gnodes[lid].lid    = lid;
550:       gnodes[lid].degree = ncols;
551:     }
552:     PetscCall(MatRestoreRow(Gmat, Ii, &ncols, NULL, NULL));
553:   }
554:   if (PETSC_TRUE) {
555:     PetscRandom rand;
556:     PetscBool  *bIndexSet;
557:     PetscReal   rr;
558:     PetscInt    iSwapIndex;

560:     PetscCall(PetscRandomCreate(comm, &rand));
561:     PetscCall(PetscCalloc1(nloc, &bIndexSet));
562:     for (Ii = 0; Ii < nloc; Ii++) {
563:       PetscCall(PetscRandomGetValueReal(rand, &rr));
564:       iSwapIndex = (PetscInt)(rr * nloc);
565:       if (!bIndexSet[iSwapIndex] && iSwapIndex != Ii) {
566:         GAMGNode iTemp        = gnodes[iSwapIndex];
567:         gnodes[iSwapIndex]    = gnodes[Ii];
568:         gnodes[Ii]            = iTemp;
569:         bIndexSet[Ii]         = PETSC_TRUE;
570:         bIndexSet[iSwapIndex] = PETSC_TRUE;
571:       }
572:     }
573:     PetscCall(PetscRandomDestroy(&rand));
574:     PetscCall(PetscFree(bIndexSet));
575:   }
576:   /* only sort locals */
577:   if (gnodes) qsort(gnodes, nloc, sizeof(GAMGNode), petsc_geo_mg_compare);
578:   /* create IS of permutation */
579:   for (kk = 0; kk < nloc; kk++) permute[kk] = gnodes[kk].lid; /* locals only */
580:   PetscCall(PetscFree(gnodes));
581:   PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nloc, permute, PETSC_OWN_POINTER, &perm));

583:   /* get MIS aggs */

585:   PetscCall(MatCoarsenCreate(comm, &crs));
586:   PetscCall(MatCoarsenSetType(crs, MATCOARSENMIS));
587:   PetscCall(MatCoarsenSetGreedyOrdering(crs, perm));
588:   PetscCall(MatCoarsenSetAdjacency(crs, Gmat));
589:   PetscCall(MatCoarsenSetStrictAggs(crs, PETSC_FALSE));
590:   PetscCall(MatCoarsenApply(crs));
591:   PetscCall(MatCoarsenGetData(crs, a_llist_parent));
592:   PetscCall(MatCoarsenDestroy(&crs));

594:   PetscCall(ISDestroy(&perm));
595:   PetscFunctionReturn(PETSC_SUCCESS);
596: }

598: static PetscErrorCode PCGAMGProlongator_GEO(PC pc, Mat Amat, PetscCoarsenData *agg_lists, Mat *a_P_out)
599: {
600:   PC_MG          *mg      = (PC_MG *)pc->data;
601:   PC_GAMG        *pc_gamg = (PC_GAMG *)mg->innerctx;
602:   const PetscInt  dim = pc_gamg->data_cell_cols, data_cols = pc_gamg->data_cell_cols;
603:   PetscInt        Istart, Iend, nloc, my0, jj, kk, ncols, nLocalSelected, bs, *clid_flid;
604:   Mat             Prol, Gmat;
605:   PetscMPIInt     rank, size;
606:   MPI_Comm        comm;
607:   IS              selected_2, selected_1;
608:   const PetscInt *selected_idx;
609:   MatType         mtype;

611:   PetscFunctionBegin;
612:   PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));

614:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
615:   PetscCallMPI(MPI_Comm_size(comm, &size));
616:   PetscCall(MatGetOwnershipRange(Amat, &Istart, &Iend));
617:   PetscCall(MatGetBlockSize(Amat, &bs));
618:   nloc = (Iend - Istart) / bs;
619:   my0  = Istart / bs;
620:   PetscCheck((Iend - Istart) % bs == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "(Iend %" PetscInt_FMT " - Istart %" PetscInt_FMT ") %% bs %" PetscInt_FMT, Iend, Istart, bs);

622:   /* get 'nLocalSelected' */
623:   PetscCall(PetscCDGetMat(agg_lists, &Gmat)); // get auxiliary matrix for ghost edges
624:   PetscCall(PetscCDGetNonemptyIS(agg_lists, &selected_1));
625:   PetscCall(ISGetSize(selected_1, &jj));
626:   PetscCall(PetscMalloc1(jj, &clid_flid));
627:   PetscCall(ISGetIndices(selected_1, &selected_idx));
628:   for (kk = 0, nLocalSelected = 0; kk < jj; kk++) {
629:     PetscInt lid = selected_idx[kk];
630:     if (lid < nloc) {
631:       PetscCall(MatGetRow(Gmat, lid + my0, &ncols, NULL, NULL));
632:       if (ncols > 1) clid_flid[nLocalSelected++] = lid; /* filter out singletons */
633:       PetscCall(MatRestoreRow(Gmat, lid + my0, &ncols, NULL, NULL));
634:     }
635:   }
636:   PetscCall(ISRestoreIndices(selected_1, &selected_idx));
637:   PetscCall(ISDestroy(&selected_1)); /* this is selected_1 in serial */

639:   /* create prolongator  matrix */
640:   PetscCall(MatGetType(Amat, &mtype));
641:   PetscCall(MatCreate(comm, &Prol));
642:   PetscCall(MatSetSizes(Prol, nloc * bs, nLocalSelected * bs, PETSC_DETERMINE, PETSC_DETERMINE));
643:   PetscCall(MatSetBlockSizes(Prol, bs, bs));
644:   PetscCall(MatSetType(Prol, mtype));
645:   PetscCall(MatSeqAIJSetPreallocation(Prol, 3 * data_cols, NULL));
646:   PetscCall(MatMPIAIJSetPreallocation(Prol, 3 * data_cols, NULL, 3 * data_cols, NULL));

648:   /* can get all points "removed" - but not on geomg */
649:   PetscCall(MatGetSize(Prol, &kk, &jj));
650:   if (!jj) {
651:     PetscCall(PetscInfo(pc, "ERROE: no selected points on coarse grid\n"));
652:     PetscCall(PetscFree(clid_flid));
653:     PetscCall(MatDestroy(&Prol));
654:     *a_P_out = NULL; /* out */
655:     PetscFunctionReturn(PETSC_SUCCESS);
656:   }

658:   {
659:     PetscReal *coords;
660:     PetscInt   data_stride;
661:     PetscInt  *crsGID = NULL;
662:     Mat        Gmat2;

664:     PetscCheck(dim == data_cols, PETSC_COMM_SELF, PETSC_ERR_PLIB, "dim %" PetscInt_FMT " != data_cols %" PetscInt_FMT, dim, data_cols);
665:     /* grow ghost data for better coarse grid cover of fine grid */
666:     /* messy method, squares graph and gets some data */
667:     PetscCall(getGIDsOnSquareGraph(pc, nLocalSelected, clid_flid, Gmat, &selected_2, &Gmat2, &crsGID));
668:     /* llist is now not valid wrt squared graph, but will work as iterator in 'triangulateAndFormProl' */
669:     /* create global vector of coorindates in 'coords' */
670:     if (size > 1) {
671:       PetscCall(PCGAMGGetDataWithGhosts(Gmat2, dim, pc_gamg->data, &data_stride, &coords));
672:     } else {
673:       coords      = pc_gamg->data;
674:       data_stride = pc_gamg->data_sz / pc_gamg->data_cell_cols;
675:     }
676:     PetscCall(MatDestroy(&Gmat2));
677:     /* triangulate */
678:     {
679:       PetscReal metric, tm;

681:       PetscCheck(dim == 2, comm, PETSC_ERR_PLIB, "3D not implemented for 'geo' AMG");
682:       PetscCall(triangulateAndFormProl(selected_2, data_stride, coords, nLocalSelected, clid_flid, agg_lists, crsGID, bs, Prol, &metric));
683:       PetscCall(PetscFree(crsGID));

685:       /* clean up and create coordinates for coarse grid (output) */
686:       if (size > 1) PetscCall(PetscFree(coords));

688:       PetscCallMPI(MPIU_Allreduce(&metric, &tm, 1, MPIU_REAL, MPIU_MAX, comm));
689:       if (tm > 1.) { /* needs to be globalized - should not happen */
690:         PetscCall(PetscInfo(pc, " failed metric for coarse grid %e\n", (double)tm));
691:         PetscCall(MatDestroy(&Prol));
692:       } else if (metric > .0) {
693:         PetscCall(PetscInfo(pc, "worst metric for coarse grid = %e\n", (double)metric));
694:       }
695:     }
696:     { /* create next coords - output */
697:       PetscReal *crs_crds;
698:       PetscCall(PetscMalloc1(dim * nLocalSelected, &crs_crds));
699:       for (kk = 0; kk < nLocalSelected; kk++) { /* grab local select nodes to promote - output */
700:         PetscInt lid = clid_flid[kk];
701:         for (jj = 0; jj < dim; jj++) crs_crds[jj * nLocalSelected + kk] = pc_gamg->data[jj * nloc + lid];
702:       }

704:       PetscCall(PetscFree(pc_gamg->data));
705:       pc_gamg->data    = crs_crds; /* out */
706:       pc_gamg->data_sz = dim * nLocalSelected;
707:     }
708:     PetscCall(ISDestroy(&selected_2));
709:   }

711:   *a_P_out = Prol; /* out */
712:   PetscCall(PetscFree(clid_flid));
713:   PetscFunctionReturn(PETSC_SUCCESS);
714: }

716: static PetscErrorCode PCDestroy_GAMG_GEO(PC pc)
717: {
718:   PetscFunctionBegin;
719:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", NULL));
720:   PetscFunctionReturn(PETSC_SUCCESS);
721: }

723: PetscErrorCode PCCreateGAMG_GEO(PC pc)
724: {
725:   PC_MG   *mg      = (PC_MG *)pc->data;
726:   PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;

728:   PetscFunctionBegin;
729:   pc_gamg->ops->setfromoptions = PCSetFromOptions_GEO;
730:   pc_gamg->ops->destroy        = PCDestroy_GAMG_GEO;
731:   /* reset does not do anything; setup not virtual */

733:   /* set internal function pointers */
734:   pc_gamg->ops->creategraph       = PCGAMGCreateGraph_GEO;
735:   pc_gamg->ops->coarsen           = PCGAMGCoarsen_GEO;
736:   pc_gamg->ops->prolongator       = PCGAMGProlongator_GEO;
737:   pc_gamg->ops->optprolongator    = NULL;
738:   pc_gamg->ops->createdefaultdata = PCSetData_GEO;

740:   PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", PCSetCoordinates_GEO));
741:   PetscFunctionReturn(PETSC_SUCCESS);
742: }