Actual source code: agg.c
1: /*
2: GAMG geometric-algebric multigrid PC - Mark Adams 2011
3: */
5: #include <../src/ksp/pc/impls/gamg/gamg.h>
6: #include <petscblaslapack.h>
7: #include <petscdm.h>
8: #include <petsc/private/kspimpl.h>
10: typedef struct {
11: PetscInt nsmooths; // number of smoothing steps to construct prolongation
12: PetscInt aggressive_coarsening_levels; // number of aggressive coarsening levels (square or MISk)
13: PetscInt aggressive_mis_k; // the k in MIS-k
14: PetscBool use_aggressive_square_graph;
15: PetscBool use_minimum_degree_ordering;
16: PetscBool use_low_mem_filter;
17: PetscBool graph_symmetrize;
18: MatCoarsen crs;
19: } PC_GAMG_AGG;
21: /*@
22: PCGAMGSetNSmooths - Set number of smoothing steps (1 is typical) used to construct the prolongation operator
24: Logically Collective
26: Input Parameters:
27: + pc - the preconditioner context
28: - n - the number of smooths, default is 1
30: Options Database Key:
31: . -pc_gamg_agg_nsmooths nsmooth - number of smoothing steps to use
33: Level: intermediate
35: Note:
36: This is a different concept from the number smoothing steps used during the linear solution process which
37: can be set with `-mg_levels_ksp_max_it`
39: Developer Note:
40: This should be named `PCGAMGAGGSetNSmooths()`.
42: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), [](ch_ksp), `PCMG`, `PCGAMG`
43: @*/
44: PetscErrorCode PCGAMGSetNSmooths(PC pc, PetscInt n)
45: {
46: PetscFunctionBegin;
49: PetscTryMethod(pc, "PCGAMGSetNSmooths_C", (PC, PetscInt), (pc, n));
50: PetscFunctionReturn(PETSC_SUCCESS);
51: }
53: static PetscErrorCode PCGAMGSetNSmooths_AGG(PC pc, PetscInt n)
54: {
55: PC_MG *mg = (PC_MG *)pc->data;
56: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
57: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
59: PetscFunctionBegin;
60: pc_gamg_agg->nsmooths = n;
61: PetscFunctionReturn(PETSC_SUCCESS);
62: }
64: /*@
65: PCGAMGSetAggressiveLevels - Use aggressive coarsening on first n levels
67: Logically Collective
69: Input Parameters:
70: + pc - the preconditioner context
71: - n - 0, 1 or more, the default is 1
73: Options Database Key:
74: . -pc_gamg_aggressive_coarsening n - the number of coarsenings to do aggressively
76: Level: intermediate
78: Note:
79: By default, aggressive coarsening squares the matrix (computes $A^T A$) before coarsening.
80: Calling `PCGAMGSetAggressiveSquareGraph()` with a value of `PETSC_FALSE` changes the aggressive coarsening strategy to use MIS-k, see `PCGAMGMISkSetAggressive()`.
82: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), [](ch_ksp), `PCGAMG`, `PCGAMGSetThreshold()`, `PCGAMGMISkSetAggressive()`,
83: `PCGAMGSetAggressiveSquareGraph()`, `PCGAMGMISkSetMinDegreeOrdering()`, `PCGAMGSetLowMemoryFilter()`
84: @*/
85: PetscErrorCode PCGAMGSetAggressiveLevels(PC pc, PetscInt n)
86: {
87: PetscFunctionBegin;
90: PetscTryMethod(pc, "PCGAMGSetAggressiveLevels_C", (PC, PetscInt), (pc, n));
91: PetscFunctionReturn(PETSC_SUCCESS);
92: }
94: /*@
95: PCGAMGMISkSetAggressive - Number (k) distance in MIS coarsening (> 2 is aggressive)
97: Logically Collective
99: Input Parameters:
100: + pc - the preconditioner context
101: - n - 1 or more (default = 2)
103: Options Database Key:
104: . -pc_gamg_aggressive_mis_k n - the distance to use
106: Level: intermediate
108: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), [](ch_ksp), `PCGAMG`, `PCGAMGSetThreshold()`, `PCGAMGSetAggressiveLevels()`,
109: `PCGAMGSetAggressiveSquareGraph()`, `PCGAMGMISkSetMinDegreeOrdering()`, `PCGAMGSetLowMemoryFilter()`
110: @*/
111: PetscErrorCode PCGAMGMISkSetAggressive(PC pc, PetscInt n)
112: {
113: PetscFunctionBegin;
116: PetscTryMethod(pc, "PCGAMGMISkSetAggressive_C", (PC, PetscInt), (pc, n));
117: PetscFunctionReturn(PETSC_SUCCESS);
118: }
120: /*@
121: PCGAMGSetAggressiveSquareGraph - Use graph square ($A^T A$) for aggressive coarsening. Coarsening is slower than the alternative (MIS-2), which is faster and uses less memory
123: Logically Collective
125: Input Parameters:
126: + pc - the preconditioner context
127: - b - default true
129: Options Database Key:
130: . -pc_gamg_aggressive_square_graph (true|false) - whether to use the graph square to aggressively coarsen
132: Level: intermediate
134: Notes:
135: If `b` is `PETSC_FALSE` then MIS-k is used for aggressive coarsening, see `PCGAMGMISkSetAggressive()`
137: Squaring the matrix to perform the aggressive coarsening is slower and requires more memory than using MIS-k, but may result in a better preconditioner
138: that converges faster.
140: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), [](ch_ksp), `PCGAMG`, `PCGAMGSetThreshold()`, `PCGAMGSetAggressiveLevels()`, `PCGAMGMISkSetAggressive()`, `PCGAMGMISkSetMinDegreeOrdering()`, `PCGAMGSetLowMemoryFilter()`
141: @*/
142: PetscErrorCode PCGAMGSetAggressiveSquareGraph(PC pc, PetscBool b)
143: {
144: PetscFunctionBegin;
147: PetscTryMethod(pc, "PCGAMGSetAggressiveSquareGraph_C", (PC, PetscBool), (pc, b));
148: PetscFunctionReturn(PETSC_SUCCESS);
149: }
151: /*@
152: PCGAMGMISkSetMinDegreeOrdering - Use minimum degree ordering in greedy MIS algorithm
154: Logically Collective
156: Input Parameters:
157: + pc - the preconditioner context
158: - b - default false
160: Options Database Key:
161: . -pc_gamg_mis_k_minimum_degree_ordering (true|false) - use the minimum degree ordering
163: Level: intermediate
165: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), [](ch_ksp), `PCGAMG`, `PCGAMGSetThreshold()`,
166: `PCGAMGSetAggressiveLevels()`, `PCGAMGMISkSetAggressive()`, `PCGAMGSetAggressiveSquareGraph()`, `PCGAMGSetLowMemoryFilter()`
167: @*/
168: PetscErrorCode PCGAMGMISkSetMinDegreeOrdering(PC pc, PetscBool b)
169: {
170: PetscFunctionBegin;
173: PetscTryMethod(pc, "PCGAMGMISkSetMinDegreeOrdering_C", (PC, PetscBool), (pc, b));
174: PetscFunctionReturn(PETSC_SUCCESS);
175: }
177: /*@
178: PCGAMGSetLowMemoryFilter - Use low memory graph/matrix filter
180: Logically Collective
182: Input Parameters:
183: + pc - the preconditioner context
184: - b - default false
186: Options Database Key:
187: . -pc_gamg_low_memory_threshold_filter (true|false) - use the low memory filter
189: Level: intermediate
191: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), `PCGAMG`, `PCGAMGSetThreshold()`, `PCGAMGSetAggressiveLevels()`,
192: `PCGAMGMISkSetAggressive()`, `PCGAMGSetAggressiveSquareGraph()`, `PCGAMGMISkSetMinDegreeOrdering()`
193: @*/
194: PetscErrorCode PCGAMGSetLowMemoryFilter(PC pc, PetscBool b)
195: {
196: PetscFunctionBegin;
199: PetscTryMethod(pc, "PCGAMGSetLowMemoryFilter_C", (PC, PetscBool), (pc, b));
200: PetscFunctionReturn(PETSC_SUCCESS);
201: }
203: /*@
204: PCGAMGSetGraphSymmetrize - Symmetrize graph used for coarsening. Defaults to true, but if matrix has symmetric attribute, then not needed since the graph is already known to be symmetric
206: Logically Collective
208: Input Parameters:
209: + pc - the preconditioner context
210: - b - default true
212: Options Database Key:
213: . -pc_gamg_graph_symmetrize (true|false) - symmetrize the graph
215: Level: intermediate
217: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), `PCGAMG`, `PCGAMGSetThreshold()`, `PCGAMGSetAggressiveLevels()`, `MatCreateGraph()`,
218: `PCGAMGMISkSetAggressive()`, `PCGAMGSetAggressiveSquareGraph()`, `PCGAMGMISkSetMinDegreeOrdering()`
219: @*/
220: PetscErrorCode PCGAMGSetGraphSymmetrize(PC pc, PetscBool b)
221: {
222: PetscFunctionBegin;
225: PetscTryMethod(pc, "PCGAMGSetGraphSymmetrize_C", (PC, PetscBool), (pc, b));
226: PetscFunctionReturn(PETSC_SUCCESS);
227: }
229: /*@
230: PCGAMGSetProlongatorFilter - Set threshold for filtering small entries from the prolongator (a kernel-preserving correction is applied afterward)
232: Logically Collective
234: Input Parameters:
235: + pc - the preconditioner context
236: - thr - threshold value; entries with absolute value below this are dropped (0 disables filtering)
238: Options Database Key:
239: . -pc_gamg_prolongator_filter thr - threshold for filtering small entries from prolongator (0=disabled, 0.0025=typical)
241: Level: intermediate
243: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), [](ch_ksp), `PCGAMG`, `PCGAMGGetProlongatorFilter()`, `PCGAMGSetLowMemoryFilter()`
244: @*/
245: PetscErrorCode PCGAMGSetProlongatorFilter(PC pc, PetscReal thr)
246: {
247: PetscFunctionBegin;
250: PetscTryMethod(pc, "PCGAMGSetProlongatorFilter_C", (PC, PetscReal), (pc, thr));
251: PetscFunctionReturn(PETSC_SUCCESS);
252: }
254: /*@
255: PCGAMGGetProlongatorFilter - Get threshold for filtering small entries from the prolongator
257: Not Collective
259: Input Parameter:
260: . pc - the preconditioner context
262: Output Parameter:
263: . thr - threshold value; entries with absolute value below this are dropped (0 disables filtering)
265: Level: intermediate
267: .seealso: [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), [](ch_ksp), `PCGAMG`, `PCGAMGSetProlongatorFilter()`, `PCGAMGSetLowMemoryFilter()`
268: @*/
269: PetscErrorCode PCGAMGGetProlongatorFilter(PC pc, PetscReal *thr)
270: {
271: PetscFunctionBegin;
273: PetscAssertPointer(thr, 2);
274: PetscUseMethod(pc, "PCGAMGGetProlongatorFilter_C", (PC, PetscReal *), (pc, thr));
275: PetscFunctionReturn(PETSC_SUCCESS);
276: }
278: static PetscErrorCode PCGAMGSetAggressiveLevels_AGG(PC pc, PetscInt n)
279: {
280: PC_MG *mg = (PC_MG *)pc->data;
281: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
282: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
284: PetscFunctionBegin;
285: pc_gamg_agg->aggressive_coarsening_levels = n;
286: PetscFunctionReturn(PETSC_SUCCESS);
287: }
289: static PetscErrorCode PCGAMGMISkSetAggressive_AGG(PC pc, PetscInt n)
290: {
291: PC_MG *mg = (PC_MG *)pc->data;
292: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
293: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
295: PetscFunctionBegin;
296: pc_gamg_agg->aggressive_mis_k = n;
297: PetscFunctionReturn(PETSC_SUCCESS);
298: }
300: static PetscErrorCode PCGAMGSetAggressiveSquareGraph_AGG(PC pc, PetscBool b)
301: {
302: PC_MG *mg = (PC_MG *)pc->data;
303: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
304: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
306: PetscFunctionBegin;
307: pc_gamg_agg->use_aggressive_square_graph = b;
308: PetscFunctionReturn(PETSC_SUCCESS);
309: }
311: static PetscErrorCode PCGAMGSetLowMemoryFilter_AGG(PC pc, PetscBool b)
312: {
313: PC_MG *mg = (PC_MG *)pc->data;
314: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
315: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
317: PetscFunctionBegin;
318: pc_gamg_agg->use_low_mem_filter = b;
319: PetscFunctionReturn(PETSC_SUCCESS);
320: }
322: static PetscErrorCode PCGAMGSetGraphSymmetrize_AGG(PC pc, PetscBool b)
323: {
324: PC_MG *mg = (PC_MG *)pc->data;
325: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
326: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
328: PetscFunctionBegin;
329: pc_gamg_agg->graph_symmetrize = b;
330: PetscFunctionReturn(PETSC_SUCCESS);
331: }
333: static PetscErrorCode PCGAMGMISkSetMinDegreeOrdering_AGG(PC pc, PetscBool b)
334: {
335: PC_MG *mg = (PC_MG *)pc->data;
336: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
337: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
339: PetscFunctionBegin;
340: pc_gamg_agg->use_minimum_degree_ordering = b;
341: PetscFunctionReturn(PETSC_SUCCESS);
342: }
344: static PetscErrorCode PCGAMGSetProlongatorFilter_AGG(PC pc, PetscReal thr)
345: {
346: PC_MG *mg = (PC_MG *)pc->data;
347: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
349: PetscFunctionBegin;
350: PetscCheck(thr >= 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_OUTOFRANGE, "Filter threshold %g must be non-negative", (double)thr);
351: pc_gamg->prolongator_filter = thr;
352: PetscFunctionReturn(PETSC_SUCCESS);
353: }
355: static PetscErrorCode PCGAMGGetProlongatorFilter_AGG(PC pc, PetscReal *thr)
356: {
357: PC_MG *mg = (PC_MG *)pc->data;
358: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
360: PetscFunctionBegin;
361: *thr = pc_gamg->prolongator_filter;
362: PetscFunctionReturn(PETSC_SUCCESS);
363: }
365: static PetscErrorCode PCSetFromOptions_GAMG_AGG(PC pc, PetscOptionItems PetscOptionsObject)
366: {
367: PC_MG *mg = (PC_MG *)pc->data;
368: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
369: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
370: PetscBool n_aggressive_flg, old_sq_provided = PETSC_FALSE, new_sq_provided = PETSC_FALSE, new_sqr_graph = pc_gamg_agg->use_aggressive_square_graph;
371: PetscInt nsq_graph_old = 0;
372: PetscReal thr = pc_gamg->prolongator_filter;
373: PetscBool flg;
375: PetscFunctionBegin;
376: PetscOptionsHeadBegin(PetscOptionsObject, "GAMG-AGG options");
377: PetscCall(PetscOptionsInt("-pc_gamg_agg_nsmooths", "number of smoothing steps to construct prolongation, usually 1", "PCGAMGSetNSmooths", pc_gamg_agg->nsmooths, &pc_gamg_agg->nsmooths, NULL));
378: // aggressive coarsening logic with deprecated -pc_gamg_square_graph
379: PetscCall(PetscOptionsInt("-pc_gamg_aggressive_coarsening", "Number of aggressive coarsening (MIS-2) levels from finest", "PCGAMGSetAggressiveLevels", pc_gamg_agg->aggressive_coarsening_levels, &pc_gamg_agg->aggressive_coarsening_levels, &n_aggressive_flg));
380: if (!n_aggressive_flg)
381: PetscCall(PetscOptionsInt("-pc_gamg_square_graph", "Number of aggressive coarsening (MIS-2) levels from finest (deprecated alias for -pc_gamg_aggressive_coarsening)", "PCGAMGSetAggressiveLevels", nsq_graph_old, &nsq_graph_old, &old_sq_provided));
382: PetscCall(PetscOptionsBool("-pc_gamg_aggressive_square_graph", "Use square graph $(A^T A)$ for aggressive coarsening, if false, MIS-k (k=2) is used, see PCGAMGMISkSetAggressive()", "PCGAMGSetAggressiveSquareGraph", new_sqr_graph, &pc_gamg_agg->use_aggressive_square_graph, &new_sq_provided));
383: if (!new_sq_provided && old_sq_provided) {
384: pc_gamg_agg->aggressive_coarsening_levels = nsq_graph_old; // could be zero
385: pc_gamg_agg->use_aggressive_square_graph = PETSC_TRUE;
386: }
387: if (new_sq_provided && old_sq_provided)
388: PetscCall(PetscInfo(pc, "Warning: both -pc_gamg_square_graph and -pc_gamg_aggressive_coarsening are used. -pc_gamg_square_graph is deprecated, Number of aggressive levels is %" PetscInt_FMT "\n", pc_gamg_agg->aggressive_coarsening_levels));
389: PetscCall(PetscOptionsBool("-pc_gamg_mis_k_minimum_degree_ordering", "Use minimum degree ordering for greedy MIS", "PCGAMGMISkSetMinDegreeOrdering", pc_gamg_agg->use_minimum_degree_ordering, &pc_gamg_agg->use_minimum_degree_ordering, NULL));
390: PetscCall(PetscOptionsBool("-pc_gamg_low_memory_threshold_filter", "Use the (built-in) low memory graph/matrix filter", "PCGAMGSetLowMemoryFilter", pc_gamg_agg->use_low_mem_filter, &pc_gamg_agg->use_low_mem_filter, NULL));
391: PetscCall(PetscOptionsInt("-pc_gamg_aggressive_mis_k", "Number of levels of multigrid to use.", "PCGAMGMISkSetAggressive", pc_gamg_agg->aggressive_mis_k, &pc_gamg_agg->aggressive_mis_k, NULL));
392: PetscCall(PetscOptionsBool("-pc_gamg_graph_symmetrize", "Symmetrize graph for coarsening", "PCGAMGSetGraphSymmetrize", pc_gamg_agg->graph_symmetrize, &pc_gamg_agg->graph_symmetrize, NULL));
393: PetscCall(PetscOptionsReal("-pc_gamg_prolongator_filter", "Threshold for filtering small entries from prolongator (0=disabled)", "PCGAMGSetProlongatorFilter", thr, &thr, &flg));
394: if (flg) PetscCall(PCGAMGSetProlongatorFilter(pc, thr));
396: PetscOptionsHeadEnd();
397: PetscFunctionReturn(PETSC_SUCCESS);
398: }
400: static PetscErrorCode PCDestroy_GAMG_AGG(PC pc)
401: {
402: PC_MG *mg = (PC_MG *)pc->data;
403: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
404: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
406: PetscFunctionBegin;
407: PetscCall(MatCoarsenDestroy(&pc_gamg_agg->crs));
408: PetscCall(PetscFree(pc_gamg->subctx));
409: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetNSmooths_C", NULL));
410: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetAggressiveLevels_C", NULL));
411: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGMISkSetAggressive_C", NULL));
412: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGMISkSetMinDegreeOrdering_C", NULL));
413: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetLowMemoryFilter_C", NULL));
414: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetAggressiveSquareGraph_C", NULL));
415: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetGraphSymmetrize_C", NULL));
416: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetProlongatorFilter_C", NULL));
417: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGGetProlongatorFilter_C", NULL));
418: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", NULL));
419: PetscFunctionReturn(PETSC_SUCCESS);
420: }
422: /*
423: PCSetCoordinates_AGG
425: Collective
427: Input Parameter:
428: . pc - the preconditioner context
429: . ndm - dimension of data (used for dof/vertex for Stokes)
430: . a_nloc - number of vertices local
431: . coords - [a_nloc][ndm] - interleaved coordinate data: {x_0, y_0, z_0, x_1, y_1, ...}
432: */
434: static PetscErrorCode PCSetCoordinates_AGG(PC pc, PetscInt ndm, PetscInt a_nloc, PetscReal *coords)
435: {
436: PC_MG *mg = (PC_MG *)pc->data;
437: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
438: PetscInt arrsz, kk, ii, jj, nloc, ndatarows, ndf;
439: Mat mat = pc->pmat;
441: PetscFunctionBegin;
444: nloc = a_nloc;
446: /* SA: null space vectors */
447: PetscCall(MatGetBlockSize(mat, &ndf)); /* this does not work for Stokes */
448: if (coords && ndf == 1) pc_gamg->data_cell_cols = 1; /* scalar w/ coords and SA (not needed) */
449: else if (coords) {
450: PetscCheck(ndm <= ndf, PETSC_COMM_SELF, PETSC_ERR_PLIB, "degrees of motion %" PetscInt_FMT " > block size %" PetscInt_FMT, ndm, ndf);
451: pc_gamg->data_cell_cols = (ndm == 2 ? 3 : 6); /* displacement elasticity */
452: if (ndm != ndf) PetscCheck(pc_gamg->data_cell_cols == ndf, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Don't know how to create null space for ndm=%" PetscInt_FMT ", ndf=%" PetscInt_FMT ". Use MatSetNearNullSpace().", ndm, ndf);
453: } else pc_gamg->data_cell_cols = ndf; /* no data, force SA with constant null space vectors */
454: pc_gamg->data_cell_rows = ndatarows = ndf;
455: PetscCheck(pc_gamg->data_cell_cols > 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "pc_gamg->data_cell_cols %" PetscInt_FMT " <= 0", pc_gamg->data_cell_cols);
456: arrsz = nloc * pc_gamg->data_cell_rows * pc_gamg->data_cell_cols;
458: if (!pc_gamg->data || (pc_gamg->data_sz != arrsz)) {
459: PetscCall(PetscFree(pc_gamg->data));
460: PetscCall(PetscMalloc1(arrsz + 1, &pc_gamg->data));
461: }
462: /* copy data in - column-oriented */
463: for (kk = 0; kk < nloc; kk++) {
464: const PetscInt M = nloc * pc_gamg->data_cell_rows; /* stride into data */
465: PetscReal *data = &pc_gamg->data[kk * ndatarows]; /* start of cell */
467: if (pc_gamg->data_cell_cols == 1) *data = 1.0;
468: else {
469: /* translational modes */
470: for (ii = 0; ii < ndatarows; ii++) {
471: for (jj = 0; jj < ndatarows; jj++) {
472: if (ii == jj) data[ii * M + jj] = 1.0;
473: else data[ii * M + jj] = 0.0;
474: }
475: }
477: /* rotational modes */
478: if (coords) {
479: if (ndm == 2) {
480: data += 2 * M;
481: data[0] = -coords[2 * kk + 1];
482: data[1] = coords[2 * kk];
483: } else {
484: data += 3 * M;
485: data[0] = 0.0;
486: data[M + 0] = coords[3 * kk + 2];
487: data[2 * M + 0] = -coords[3 * kk + 1];
488: data[1] = -coords[3 * kk + 2];
489: data[M + 1] = 0.0;
490: data[2 * M + 1] = coords[3 * kk];
491: data[2] = coords[3 * kk + 1];
492: data[M + 2] = -coords[3 * kk];
493: data[2 * M + 2] = 0.0;
494: }
495: }
496: }
497: }
498: pc_gamg->data_sz = arrsz;
499: PetscFunctionReturn(PETSC_SUCCESS);
500: }
502: /*
503: PCSetData_AGG - called if data is not set with PCSetCoordinates.
504: Looks in Mat for near null space.
505: Does not work for Stokes
507: Input Parameter:
508: . pc -
509: . a_A - matrix to get (near) null space out of.
510: */
511: static PetscErrorCode PCSetData_AGG(PC pc, Mat a_A)
512: {
513: PC_MG *mg = (PC_MG *)pc->data;
514: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
515: MatNullSpace mnull;
517: PetscFunctionBegin;
518: PetscCall(MatGetNearNullSpace(a_A, &mnull));
519: if (!mnull) {
520: DM dm;
522: PetscCall(PCGetDM(pc, &dm));
523: if (!dm) PetscCall(MatGetDM(a_A, &dm));
524: if (dm) {
525: PetscObject deformation;
526: PetscInt Nf;
528: PetscCall(DMGetNumFields(dm, &Nf));
529: if (Nf) {
530: PetscCall(DMGetField(dm, 0, NULL, &deformation));
531: if (deformation) {
532: PetscCall(PetscObjectQuery(deformation, "nearnullspace", (PetscObject *)&mnull));
533: if (!mnull) PetscCall(PetscObjectQuery(deformation, "nullspace", (PetscObject *)&mnull));
534: }
535: }
536: }
537: }
539: if (!mnull) {
540: PetscInt bs, NN, MM;
542: PetscCall(MatGetBlockSize(a_A, &bs));
543: PetscCall(MatGetLocalSize(a_A, &MM, &NN));
544: PetscCheck(MM % bs == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "MM %" PetscInt_FMT " must be divisible by bs %" PetscInt_FMT, MM, bs);
545: PetscCall(PCSetCoordinates_AGG(pc, bs, MM / bs, NULL));
546: } else {
547: PetscReal *nullvec;
548: PetscBool has_const;
549: PetscInt i, j, mlocal, nvec, bs;
550: const Vec *vecs;
551: const PetscScalar *v;
553: PetscCall(MatGetLocalSize(a_A, &mlocal, NULL));
554: PetscCall(MatNullSpaceGetVecs(mnull, &has_const, &nvec, &vecs));
555: for (i = 0; i < nvec; i++) {
556: PetscCall(VecGetLocalSize(vecs[i], &j));
557: PetscCheck(j == mlocal, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Attached null space vector size %" PetscInt_FMT " != matrix size %" PetscInt_FMT, j, mlocal);
558: }
559: pc_gamg->data_sz = (nvec + !!has_const) * mlocal;
560: PetscCall(PetscMalloc1((nvec + !!has_const) * mlocal, &nullvec));
561: if (has_const)
562: for (i = 0; i < mlocal; i++) nullvec[i] = 1.0;
563: for (i = 0; i < nvec; i++) {
564: PetscCall(VecGetArrayRead(vecs[i], &v));
565: for (j = 0; j < mlocal; j++) nullvec[(i + !!has_const) * mlocal + j] = PetscRealPart(v[j]);
566: PetscCall(VecRestoreArrayRead(vecs[i], &v));
567: }
568: pc_gamg->data = nullvec;
569: pc_gamg->data_cell_cols = (nvec + !!has_const);
570: PetscCall(MatGetBlockSize(a_A, &bs));
571: pc_gamg->data_cell_rows = bs;
572: }
573: PetscFunctionReturn(PETSC_SUCCESS);
574: }
576: /*
577: formProl0 - collect null space data for each aggregate, do QR, put R in coarse grid data and Q in P_0
579: Input Parameter:
580: . agg_llists - list of arrays with aggregates -- list from selected vertices of aggregate unselected vertices
581: . bs - row block size
582: . nSAvec - column bs of new P
583: . my0crs - global index of start of locals
584: . data_stride - bs*(nloc nodes + ghost nodes) [data_stride][nSAvec]
585: . data_in[data_stride*nSAvec] - local data on fine grid
586: . flid_fgid[data_stride/bs] - make local to global IDs, includes ghosts in 'locals_llist'
588: Output Parameter:
589: . a_data_out - in with fine grid data (w/ghosts), out with coarse grid data
590: . a_Prol - prolongation operator
591: */
592: static PetscErrorCode formProl0(PetscCoarsenData *agg_llists, PetscInt bs, PetscInt nSAvec, PetscInt my0crs, PetscInt data_stride, PetscReal data_in[], const PetscInt flid_fgid[], PetscReal **a_data_out, Mat a_Prol)
593: {
594: PetscInt Istart, my0, Iend, nloc, clid, flid = 0, aggID, kk, jj, ii, mm, nSelected, minsz, nghosts, out_data_stride;
595: MPI_Comm comm;
596: PetscReal *out_data;
597: PetscCDIntNd *pos;
598: PetscHMapI fgid_flid;
600: PetscFunctionBegin;
601: PetscCall(PetscObjectGetComm((PetscObject)a_Prol, &comm));
602: PetscCall(MatGetOwnershipRange(a_Prol, &Istart, &Iend));
603: nloc = (Iend - Istart) / bs;
604: my0 = Istart / bs;
605: PetscCheck((Iend - Istart) % bs == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Iend %" PetscInt_FMT " - Istart %" PetscInt_FMT " must be divisible by bs %" PetscInt_FMT, Iend, Istart, bs);
606: Iend /= bs;
607: nghosts = data_stride / bs - nloc;
609: PetscCall(PetscHMapICreateWithSize(2 * nghosts + 1, &fgid_flid));
611: for (kk = 0; kk < nghosts; kk++) PetscCall(PetscHMapISet(fgid_flid, flid_fgid[nloc + kk], nloc + kk));
613: /* count selected -- same as number of cols of P */
614: for (nSelected = mm = 0; mm < nloc; mm++) {
615: PetscBool ise;
617: PetscCall(PetscCDIsEmptyAt(agg_llists, mm, &ise));
618: if (!ise) nSelected++;
619: }
620: PetscCall(MatGetOwnershipRangeColumn(a_Prol, &ii, &jj));
621: PetscCheck((ii / nSAvec) == my0crs, PETSC_COMM_SELF, PETSC_ERR_PLIB, "ii %" PetscInt_FMT " /nSAvec %" PetscInt_FMT " != my0crs %" PetscInt_FMT, ii, nSAvec, my0crs);
622: PetscCheck(nSelected == (jj - ii) / nSAvec, PETSC_COMM_SELF, PETSC_ERR_PLIB, "nSelected %" PetscInt_FMT " != (jj %" PetscInt_FMT " - ii %" PetscInt_FMT ")/nSAvec %" PetscInt_FMT, nSelected, jj, ii, nSAvec);
624: /* aloc space for coarse point data (output) */
625: out_data_stride = nSelected * nSAvec;
627: PetscCall(PetscMalloc1(out_data_stride * nSAvec, &out_data));
628: for (ii = 0; ii < out_data_stride * nSAvec; ii++) out_data[ii] = PETSC_MAX_REAL;
629: *a_data_out = out_data; /* output - stride nSelected*nSAvec */
631: /* find points and set prolongation */
632: minsz = 100;
633: for (mm = clid = 0; mm < nloc; mm++) {
634: PetscCall(PetscCDCountAt(agg_llists, mm, &jj));
635: if (jj > 0) {
636: const PetscInt lid = mm, cgid = my0crs + clid;
637: PetscInt cids[100]; /* max bs */
638: PetscBLASInt asz, M, N;
639: PetscBLASInt Mdata, LDA, LWORK;
640: PetscScalar *qqc, *qqr, *TAU, *WORK;
641: PetscInt *fids;
642: PetscReal *data;
644: PetscCall(PetscBLASIntCast(jj, &asz));
645: PetscCall(PetscBLASIntCast(asz * bs, &M));
646: PetscCall(PetscBLASIntCast(nSAvec, &N));
647: PetscCall(PetscBLASIntCast(M + ((N - M > 0) ? N - M : 0), &Mdata));
648: PetscCall(PetscBLASIntCast(Mdata, &LDA));
649: PetscCall(PetscBLASIntCast(N * bs, &LWORK));
650: /* count agg */
651: if (asz < minsz) minsz = asz;
653: /* get block */
654: PetscCall(PetscMalloc5(Mdata * N, &qqc, M * N, &qqr, N, &TAU, LWORK, &WORK, M, &fids));
656: aggID = 0;
657: PetscCall(PetscCDGetHeadPos(agg_llists, lid, &pos));
658: while (pos) {
659: PetscInt gid1;
661: PetscCall(PetscCDIntNdGetID(pos, &gid1));
662: PetscCall(PetscCDGetNextPos(agg_llists, lid, &pos));
664: if (gid1 >= my0 && gid1 < Iend) flid = gid1 - my0;
665: else {
666: PetscCall(PetscHMapIGet(fgid_flid, gid1, &flid));
667: PetscCheck(flid >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Cannot find gid1 in table");
668: }
669: /* copy in B_i matrix - column-oriented */
670: data = &data_in[flid * bs];
671: for (ii = 0; ii < bs; ii++) {
672: for (jj = 0; jj < N; jj++) {
673: PetscReal d = data[jj * data_stride + ii];
675: qqc[jj * Mdata + aggID * bs + ii] = d;
676: }
677: }
678: /* set fine IDs */
679: for (kk = 0; kk < bs; kk++) fids[aggID * bs + kk] = flid_fgid[flid] * bs + kk;
680: aggID++;
681: }
683: /* pad with zeros */
684: for (ii = asz * bs; ii < Mdata; ii++) {
685: for (jj = 0; jj < N; jj++, kk++) qqc[jj * Mdata + ii] = .0;
686: }
688: /* QR */
689: PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
690: PetscCallLAPACKInfo("LAPACKgeqrf", LAPACKgeqrf_(&Mdata, &N, qqc, &LDA, TAU, WORK, &LWORK, &info));
691: PetscCall(PetscFPTrapPop());
692: /* get R - column-oriented - output B_{i+1} */
693: {
694: PetscReal *data = &out_data[clid * nSAvec];
696: for (jj = 0; jj < nSAvec; jj++) {
697: for (ii = 0; ii < nSAvec; ii++) {
698: PetscCheck(data[jj * out_data_stride + ii] == PETSC_MAX_REAL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "data[jj*out_data_stride + ii] != %e", (double)PETSC_MAX_REAL);
699: if (ii <= jj) data[jj * out_data_stride + ii] = PetscRealPart(qqc[jj * Mdata + ii]);
700: else data[jj * out_data_stride + ii] = 0.;
701: }
702: }
703: }
705: /* get Q - row-oriented */
706: PetscCallLAPACKInfo("LAPACKorgqr", LAPACKorgqr_(&Mdata, &N, &N, qqc, &LDA, TAU, WORK, &LWORK, &info));
708: for (ii = 0; ii < M; ii++) {
709: for (jj = 0; jj < N; jj++) qqr[N * ii + jj] = qqc[jj * Mdata + ii];
710: }
712: /* add diagonal block of P0 */
713: for (kk = 0; kk < N; kk++) cids[kk] = N * cgid + kk; /* global col IDs in P0 */
714: PetscCall(MatSetValues(a_Prol, M, fids, N, cids, qqr, INSERT_VALUES));
715: PetscCall(PetscFree5(qqc, qqr, TAU, WORK, fids));
716: clid++;
717: } /* coarse agg */
718: } /* for all fine nodes */
719: PetscCall(MatAssemblyBegin(a_Prol, MAT_FINAL_ASSEMBLY));
720: PetscCall(MatAssemblyEnd(a_Prol, MAT_FINAL_ASSEMBLY));
721: PetscCall(PetscHMapIDestroy(&fgid_flid));
722: PetscFunctionReturn(PETSC_SUCCESS);
723: }
725: static PetscErrorCode PCView_GAMG_AGG(PC pc, PetscViewer viewer)
726: {
727: PC_MG *mg = (PC_MG *)pc->data;
728: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
729: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
731: PetscFunctionBegin;
732: PetscCall(PetscViewerASCIIPrintf(viewer, " AGG specific options\n"));
733: PetscCall(PetscViewerASCIIPrintf(viewer, " Number of levels of aggressive coarsening %" PetscInt_FMT "\n", pc_gamg_agg->aggressive_coarsening_levels));
734: if (pc_gamg_agg->aggressive_coarsening_levels > 0) {
735: PetscCall(PetscViewerASCIIPrintf(viewer, " %s aggressive coarsening\n", !pc_gamg_agg->use_aggressive_square_graph ? "MIS-k" : "Square graph"));
736: if (!pc_gamg_agg->use_aggressive_square_graph) PetscCall(PetscViewerASCIIPrintf(viewer, " MIS-%" PetscInt_FMT " coarsening on aggressive levels\n", pc_gamg_agg->aggressive_mis_k));
737: }
738: PetscCall(PetscViewerASCIIPushTab(viewer));
739: PetscCall(PetscViewerASCIIPushTab(viewer));
740: PetscCall(PetscViewerASCIIPushTab(viewer));
741: PetscCall(PetscViewerASCIIPushTab(viewer));
742: if (pc_gamg_agg->crs) PetscCall(MatCoarsenView(pc_gamg_agg->crs, viewer));
743: else PetscCall(PetscViewerASCIIPrintf(viewer, "Coarsening algorithm not yet selected\n"));
744: PetscCall(PetscViewerASCIIPopTab(viewer));
745: PetscCall(PetscViewerASCIIPopTab(viewer));
746: PetscCall(PetscViewerASCIIPopTab(viewer));
747: PetscCall(PetscViewerASCIIPopTab(viewer));
748: PetscCall(PetscViewerASCIIPrintf(viewer, " Number smoothing steps to construct prolongation %" PetscInt_FMT "\n", pc_gamg_agg->nsmooths));
749: PetscFunctionReturn(PETSC_SUCCESS);
750: }
752: static PetscErrorCode PCGAMGCreateGraph_AGG(PC pc, Mat Amat, Mat *a_Gmat)
753: {
754: PC_MG *mg = (PC_MG *)pc->data;
755: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
756: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
757: const PetscReal vfilter = pc_gamg->threshold[pc_gamg->current_level];
758: PetscBool ishem, ismis;
759: const char *prefix;
760: MatInfo info0, info1;
761: PetscInt bs;
763: PetscFunctionBegin;
764: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_COARSEN], 0, 0, 0, 0));
765: /* Note: depending on the algorithm that will be used for computing the coarse grid points this should pass PETSC_TRUE or PETSC_FALSE as the first argument */
766: /* MATCOARSENHEM requires numerical weights for edges so ensure they are computed */
767: PetscCall(MatCoarsenDestroy(&pc_gamg_agg->crs));
768: PetscCall(MatCoarsenCreate(PetscObjectComm((PetscObject)pc), &pc_gamg_agg->crs));
769: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)pc, &prefix));
770: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)pc_gamg_agg->crs, prefix));
771: PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)pc_gamg_agg->crs, "pc_gamg_"));
772: PetscCall(MatCoarsenSetFromOptions(pc_gamg_agg->crs));
773: PetscCall(MatGetBlockSize(Amat, &bs));
774: // check for valid indices wrt bs
775: for (int ii = 0; ii < pc_gamg_agg->crs->strength_index_size; ii++) {
776: PetscCheck(pc_gamg_agg->crs->strength_index[ii] >= 0 && pc_gamg_agg->crs->strength_index[ii] < bs, PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONG, "Indices (%" PetscInt_FMT ") must be non-negative and < block size (%" PetscInt_FMT "), NB, can not use -mat_coarsen_strength_index with -mat_coarsen_strength_index",
777: pc_gamg_agg->crs->strength_index[ii], bs);
778: }
779: PetscCall(PetscObjectTypeCompare((PetscObject)pc_gamg_agg->crs, MATCOARSENHEM, &ishem));
780: if (ishem) {
781: if (pc_gamg_agg->aggressive_coarsening_levels) PetscCall(PetscInfo(pc, "HEM and aggressive coarsening ignored: HEM using %" PetscInt_FMT " iterations\n", pc_gamg_agg->crs->max_it));
782: pc_gamg_agg->aggressive_coarsening_levels = 0; // aggressive and HEM does not make sense
783: PetscCall(MatCoarsenSetMaximumIterations(pc_gamg_agg->crs, pc_gamg_agg->crs->max_it)); // for code coverage
784: PetscCall(MatCoarsenSetThreshold(pc_gamg_agg->crs, vfilter)); // for code coverage
785: } else {
786: PetscCall(PetscObjectTypeCompare((PetscObject)pc_gamg_agg->crs, MATCOARSENMIS, &ismis));
787: if (ismis && pc_gamg_agg->aggressive_coarsening_levels && !pc_gamg_agg->use_aggressive_square_graph) {
788: PetscCall(PetscInfo(pc, "MIS and aggressive coarsening and no square graph: force square graph\n"));
789: pc_gamg_agg->use_aggressive_square_graph = PETSC_TRUE;
790: }
791: }
792: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_COARSEN], 0, 0, 0, 0));
793: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_GRAPH], 0, 0, 0, 0));
794: PetscCall(MatGetInfo(Amat, MAT_LOCAL, &info0)); /* global reduction */
796: if (ishem || pc_gamg_agg->use_low_mem_filter) {
797: PetscCall(MatCreateGraph(Amat, pc_gamg_agg->graph_symmetrize, (vfilter >= 0 || ishem) ? PETSC_TRUE : PETSC_FALSE, vfilter, pc_gamg_agg->crs->strength_index_size, pc_gamg_agg->crs->strength_index, a_Gmat));
798: } else {
799: // make scalar graph, symmetrize if not known to be symmetric, scale, but do not filter (expensive)
800: PetscCall(MatCreateGraph(Amat, pc_gamg_agg->graph_symmetrize, PETSC_TRUE, -1, pc_gamg_agg->crs->strength_index_size, pc_gamg_agg->crs->strength_index, a_Gmat));
801: if (vfilter >= 0) {
802: PetscInt Istart, Iend, ncols, nnz0, nnz1, NN, MM, nloc;
803: Mat tGmat, Gmat = *a_Gmat;
804: MPI_Comm comm;
805: const PetscScalar *vals;
806: const PetscInt *idx;
807: PetscInt *d_nnz, *o_nnz, kk, *garray = NULL, *AJ, maxcols = 0;
808: MatScalar *AA; // this is checked in graph
809: PetscBool isseqaij;
810: Mat a, b, c;
811: MatType jtype;
813: PetscCall(PetscObjectGetComm((PetscObject)Gmat, &comm));
814: PetscCall(PetscObjectBaseTypeCompare((PetscObject)Gmat, MATSEQAIJ, &isseqaij));
815: PetscCall(MatGetType(Gmat, &jtype));
816: PetscCall(MatCreate(comm, &tGmat));
817: PetscCall(MatSetType(tGmat, jtype));
819: /* TODO GPU: this can be called when filter = 0 -> Probably provide MatAIJThresholdCompress that compresses the entries below a threshold?
820: Also, if the matrix is symmetric, can we skip this
821: operation? It can be very expensive on large matrices. */
823: // global sizes
824: PetscCall(MatGetSize(Gmat, &MM, &NN));
825: PetscCall(MatGetOwnershipRange(Gmat, &Istart, &Iend));
826: nloc = Iend - Istart;
827: PetscCall(PetscMalloc2(nloc, &d_nnz, nloc, &o_nnz));
828: if (isseqaij) {
829: a = Gmat;
830: b = NULL;
831: } else {
832: Mat_MPIAIJ *d = (Mat_MPIAIJ *)Gmat->data;
834: a = d->A;
835: b = d->B;
836: garray = d->garray;
837: }
838: /* Determine upper bound on non-zeros needed in new filtered matrix */
839: for (PetscInt row = 0; row < nloc; row++) {
840: PetscCall(MatGetRow(a, row, &ncols, NULL, NULL));
841: d_nnz[row] = ncols;
842: if (ncols > maxcols) maxcols = ncols;
843: PetscCall(MatRestoreRow(a, row, &ncols, NULL, NULL));
844: }
845: if (b) {
846: for (PetscInt row = 0; row < nloc; row++) {
847: PetscCall(MatGetRow(b, row, &ncols, NULL, NULL));
848: o_nnz[row] = ncols;
849: if (ncols > maxcols) maxcols = ncols;
850: PetscCall(MatRestoreRow(b, row, &ncols, NULL, NULL));
851: }
852: }
853: PetscCall(MatSetSizes(tGmat, nloc, nloc, MM, MM));
854: PetscCall(MatSetBlockSizes(tGmat, 1, 1));
855: PetscCall(MatSeqAIJSetPreallocation(tGmat, 0, d_nnz));
856: PetscCall(MatMPIAIJSetPreallocation(tGmat, 0, d_nnz, 0, o_nnz));
857: PetscCall(MatSetOption(tGmat, MAT_NO_OFF_PROC_ENTRIES, PETSC_TRUE));
858: PetscCall(PetscFree2(d_nnz, o_nnz));
859: PetscCall(PetscMalloc2(maxcols, &AA, maxcols, &AJ));
860: nnz0 = nnz1 = 0;
861: for (c = a, kk = 0; c && kk < 2; c = b, kk++) {
862: for (PetscInt row = 0, grow = Istart, ncol_row, jj; row < nloc; row++, grow++) {
863: PetscCall(MatGetRow(c, row, &ncols, &idx, &vals));
864: for (ncol_row = jj = 0; jj < ncols; jj++, nnz0++) {
865: PetscScalar sv = PetscAbs(PetscRealPart(vals[jj]));
866: if (PetscRealPart(sv) > vfilter) {
867: PetscInt cid = idx[jj] + Istart; //diag
869: nnz1++;
870: if (c != a) cid = garray[idx[jj]];
871: AA[ncol_row] = vals[jj];
872: AJ[ncol_row] = cid;
873: ncol_row++;
874: }
875: }
876: PetscCall(MatRestoreRow(c, row, &ncols, &idx, &vals));
877: PetscCall(MatSetValues(tGmat, 1, &grow, ncol_row, AJ, AA, INSERT_VALUES));
878: }
879: }
880: PetscCall(PetscFree2(AA, AJ));
881: PetscCall(MatAssemblyBegin(tGmat, MAT_FINAL_ASSEMBLY));
882: PetscCall(MatAssemblyEnd(tGmat, MAT_FINAL_ASSEMBLY));
883: PetscCall(MatPropagateSymmetryOptions(Gmat, tGmat)); /* Normal Mat options are not relevant ? */
884: PetscCall(PetscInfo(pc, "\t %g%% nnz after filtering, with threshold %g, %g nnz ave. (N=%" PetscInt_FMT ", max row size %" PetscInt_FMT "\n", (!nnz0) ? 1. : 100. * (double)nnz1 / (double)nnz0, (double)vfilter, (!nloc) ? 1. : (double)nnz0 / (double)nloc, MM, maxcols));
885: PetscCall(MatViewFromOptions(tGmat, NULL, "-mat_filter_graph_view"));
886: PetscCall(MatDestroy(&Gmat));
887: *a_Gmat = tGmat;
888: }
889: }
891: PetscCall(MatGetInfo(*a_Gmat, MAT_LOCAL, &info1)); /* global reduction */
892: if (info0.nz_used > 0) PetscCall(PetscInfo(pc, "Filtering left %g %% edges in graph (%e %e)\n", 100.0 * info1.nz_used * (double)(bs * bs) / info0.nz_used, info0.nz_used, info1.nz_used));
893: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_GRAPH], 0, 0, 0, 0));
894: PetscFunctionReturn(PETSC_SUCCESS);
895: }
897: typedef PetscInt NState;
898: static const NState NOT_DONE = -2;
899: static const NState DELETED = -1;
900: static const NState REMOVED = -3;
901: #define IS_SELECTED(s) (s != DELETED && s != NOT_DONE && s != REMOVED)
903: /*
904: fixAggregatesWithSquare - greedy grab of with G1 (unsquared graph) -- AIJ specific -- change to fixAggregatesWithSquare -- TODD
905: - AGG-MG specific: clears singletons out of 'selected_2'
907: Input Parameter:
908: . Gmat_2 - global matrix of squared graph (data not defined)
909: . Gmat_1 - base graph to grab with base graph
910: Input/Output Parameter:
911: . aggs_2 - linked list of aggs with gids)
912: */
913: static PetscErrorCode fixAggregatesWithSquare(PC pc, Mat Gmat_2, Mat Gmat_1, PetscCoarsenData *aggs_2)
914: {
915: PetscBool isMPI;
916: Mat_SeqAIJ *matA_1, *matB_1 = NULL;
917: MPI_Comm comm;
918: PetscInt lid, *ii, *idx, ix, Iend, my0, kk, n, j;
919: Mat_MPIAIJ *mpimat_2 = NULL, *mpimat_1 = NULL;
920: const PetscInt nloc = Gmat_2->rmap->n;
921: PetscScalar *cpcol_1_state, *cpcol_2_state, *cpcol_2_par_orig, *lid_parent_gid;
922: PetscInt *lid_cprowID_1 = NULL;
923: NState *lid_state;
924: Vec ghost_par_orig2;
925: PetscMPIInt rank;
927: PetscFunctionBegin;
928: PetscCall(PetscObjectGetComm((PetscObject)Gmat_2, &comm));
929: PetscCallMPI(MPI_Comm_rank(comm, &rank));
930: PetscCall(MatGetOwnershipRange(Gmat_1, &my0, &Iend));
932: /* get submatrices */
933: PetscCall(PetscStrbeginswith(((PetscObject)Gmat_1)->type_name, MATMPIAIJ, &isMPI));
934: PetscCall(PetscInfo(pc, "isMPI = %s\n", isMPI ? "yes" : "no"));
935: PetscCall(PetscMalloc3(nloc, &lid_state, nloc, &lid_parent_gid, nloc, &lid_cprowID_1));
936: for (lid = 0; lid < nloc; lid++) lid_cprowID_1[lid] = -1;
937: if (isMPI) {
938: /* grab matrix objects */
939: mpimat_2 = (Mat_MPIAIJ *)Gmat_2->data;
940: mpimat_1 = (Mat_MPIAIJ *)Gmat_1->data;
941: matA_1 = (Mat_SeqAIJ *)mpimat_1->A->data;
942: matB_1 = (Mat_SeqAIJ *)mpimat_1->B->data;
944: /* force compressed row storage for B matrix in AuxMat */
945: PetscCall(MatCheckCompressedRow(mpimat_1->B, matB_1->nonzerorowcnt, &matB_1->compressedrow, matB_1->i, Gmat_1->rmap->n, -1.0));
946: for (ix = 0; ix < matB_1->compressedrow.nrows; ix++) {
947: PetscInt lid = matB_1->compressedrow.rindex[ix];
949: PetscCheck(lid <= nloc && lid >= -1, PETSC_COMM_SELF, PETSC_ERR_USER, "lid %" PetscInt_FMT " out of range. nloc = %" PetscInt_FMT, lid, nloc);
950: if (lid != -1) lid_cprowID_1[lid] = ix;
951: }
952: } else {
953: PetscBool isAIJ;
955: PetscCall(PetscStrbeginswith(((PetscObject)Gmat_1)->type_name, MATSEQAIJ, &isAIJ));
956: PetscCheck(isAIJ, PETSC_COMM_SELF, PETSC_ERR_USER, "Require AIJ matrix.");
957: matA_1 = (Mat_SeqAIJ *)Gmat_1->data;
958: }
959: if (nloc > 0) PetscCheck(!matB_1 || matB_1->compressedrow.use, PETSC_COMM_SELF, PETSC_ERR_PLIB, "matB_1 && !matB_1->compressedrow.use: PETSc bug???");
960: /* get state of locals and selected gid for deleted */
961: for (lid = 0; lid < nloc; lid++) {
962: lid_parent_gid[lid] = -1.0;
963: lid_state[lid] = DELETED;
964: }
966: /* set lid_state */
967: for (lid = 0; lid < nloc; lid++) {
968: PetscCDIntNd *pos;
970: PetscCall(PetscCDGetHeadPos(aggs_2, lid, &pos));
971: if (pos) {
972: PetscInt gid1;
974: PetscCall(PetscCDIntNdGetID(pos, &gid1));
975: PetscCheck(gid1 == lid + my0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "gid1 %" PetscInt_FMT " != lid %" PetscInt_FMT " + my0 %" PetscInt_FMT, gid1, lid, my0);
976: lid_state[lid] = gid1;
977: }
978: }
980: /* map local to selected local, DELETED means a ghost owns it */
981: for (lid = 0; lid < nloc; lid++) {
982: NState state = lid_state[lid];
984: if (IS_SELECTED(state)) {
985: PetscCDIntNd *pos;
987: PetscCall(PetscCDGetHeadPos(aggs_2, lid, &pos));
988: while (pos) {
989: PetscInt gid1;
991: PetscCall(PetscCDIntNdGetID(pos, &gid1));
992: PetscCall(PetscCDGetNextPos(aggs_2, lid, &pos));
993: if (gid1 >= my0 && gid1 < Iend) lid_parent_gid[gid1 - my0] = (PetscScalar)(lid + my0);
994: }
995: }
996: }
997: /* get 'cpcol_1/2_state' & cpcol_2_par_orig - uses mpimat_1/2->lvec for temp space */
998: if (isMPI) {
999: Vec tempVec;
1001: /* get 'cpcol_1_state' */
1002: PetscCall(MatCreateVecs(Gmat_1, &tempVec, NULL));
1003: for (kk = 0, j = my0; kk < nloc; kk++, j++) {
1004: PetscScalar v = (PetscScalar)lid_state[kk];
1006: PetscCall(VecSetValues(tempVec, 1, &j, &v, INSERT_VALUES));
1007: }
1008: PetscCall(VecAssemblyBegin(tempVec));
1009: PetscCall(VecAssemblyEnd(tempVec));
1010: PetscCall(VecScatterBegin(mpimat_1->Mvctx, tempVec, mpimat_1->lvec, INSERT_VALUES, SCATTER_FORWARD));
1011: PetscCall(VecScatterEnd(mpimat_1->Mvctx, tempVec, mpimat_1->lvec, INSERT_VALUES, SCATTER_FORWARD));
1012: PetscCall(VecGetArray(mpimat_1->lvec, &cpcol_1_state));
1013: /* get 'cpcol_2_state' */
1014: PetscCall(VecScatterBegin(mpimat_2->Mvctx, tempVec, mpimat_2->lvec, INSERT_VALUES, SCATTER_FORWARD));
1015: PetscCall(VecScatterEnd(mpimat_2->Mvctx, tempVec, mpimat_2->lvec, INSERT_VALUES, SCATTER_FORWARD));
1016: PetscCall(VecGetArray(mpimat_2->lvec, &cpcol_2_state));
1017: /* get 'cpcol_2_par_orig' */
1018: for (kk = 0, j = my0; kk < nloc; kk++, j++) {
1019: PetscScalar v = lid_parent_gid[kk];
1021: PetscCall(VecSetValues(tempVec, 1, &j, &v, INSERT_VALUES));
1022: }
1023: PetscCall(VecAssemblyBegin(tempVec));
1024: PetscCall(VecAssemblyEnd(tempVec));
1025: PetscCall(VecDuplicate(mpimat_2->lvec, &ghost_par_orig2));
1026: PetscCall(VecScatterBegin(mpimat_2->Mvctx, tempVec, ghost_par_orig2, INSERT_VALUES, SCATTER_FORWARD));
1027: PetscCall(VecScatterEnd(mpimat_2->Mvctx, tempVec, ghost_par_orig2, INSERT_VALUES, SCATTER_FORWARD));
1028: PetscCall(VecGetArray(ghost_par_orig2, &cpcol_2_par_orig));
1030: PetscCall(VecDestroy(&tempVec));
1031: } /* ismpi */
1032: for (lid = 0; lid < nloc; lid++) {
1033: NState state = lid_state[lid];
1035: if (IS_SELECTED(state)) {
1036: /* steal locals */
1037: ii = matA_1->i;
1038: n = ii[lid + 1] - ii[lid];
1039: idx = matA_1->j + ii[lid];
1040: for (j = 0; j < n; j++) {
1041: PetscInt lidj = idx[j], sgid;
1042: NState statej = lid_state[lidj];
1044: if (statej == DELETED && (sgid = (PetscInt)PetscRealPart(lid_parent_gid[lidj])) != lid + my0) { /* steal local */
1045: lid_parent_gid[lidj] = (PetscScalar)(lid + my0); /* send this if sgid is not local */
1046: if (sgid >= my0 && sgid < Iend) { /* I'm stealing this local from a local sgid */
1047: PetscInt hav = 0, slid = sgid - my0, gidj = lidj + my0;
1048: PetscCDIntNd *pos, *last = NULL;
1050: /* looking for local from local so id_llist_2 works */
1051: PetscCall(PetscCDGetHeadPos(aggs_2, slid, &pos));
1052: while (pos) {
1053: PetscInt gid;
1055: PetscCall(PetscCDIntNdGetID(pos, &gid));
1056: if (gid == gidj) {
1057: PetscCheck(last, PETSC_COMM_SELF, PETSC_ERR_PLIB, "last cannot be null");
1058: PetscCall(PetscCDRemoveNextNode(aggs_2, slid, last));
1059: PetscCall(PetscCDAppendNode(aggs_2, lid, pos));
1060: hav = 1;
1061: break;
1062: } else last = pos;
1063: PetscCall(PetscCDGetNextPos(aggs_2, slid, &pos));
1064: }
1065: if (hav != 1) {
1066: PetscCheck(hav, PETSC_COMM_SELF, PETSC_ERR_PLIB, "failed to find adj in 'selected' lists - structurally unsymmetric matrix");
1067: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "found node %" PetscInt_FMT " times???", hav);
1068: }
1069: } else { /* I'm stealing this local, owned by a ghost */
1070: PetscCheck(sgid == -1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Mat has an un-symmetric graph. Use '-%spc_gamg_sym_graph true' to symmetrize the graph or '-%spc_gamg_threshold -1' if the matrix is structurally symmetric.",
1071: ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "", ((PetscObject)pc)->prefix ? ((PetscObject)pc)->prefix : "");
1072: PetscCall(PetscCDAppendID(aggs_2, lid, lidj + my0));
1073: }
1074: }
1075: } /* local neighbors */
1076: } else if (state == DELETED /* && lid_cprowID_1 */) {
1077: PetscInt sgidold = (PetscInt)PetscRealPart(lid_parent_gid[lid]);
1079: /* see if I have a selected ghost neighbor that will steal me */
1080: if ((ix = lid_cprowID_1[lid]) != -1) {
1081: ii = matB_1->compressedrow.i;
1082: n = ii[ix + 1] - ii[ix];
1083: idx = matB_1->j + ii[ix];
1084: for (j = 0; j < n; j++) {
1085: PetscInt cpid = idx[j];
1086: NState statej = (NState)PetscRealPart(cpcol_1_state[cpid]);
1088: if (IS_SELECTED(statej) && sgidold != statej) { /* ghost will steal this, remove from my list */
1089: lid_parent_gid[lid] = (PetscScalar)statej; /* send who selected */
1090: if (sgidold >= my0 && sgidold < Iend) { /* this was mine */
1091: PetscInt hav = 0, oldslidj = sgidold - my0;
1092: PetscCDIntNd *pos, *last = NULL;
1094: /* remove from 'oldslidj' list */
1095: PetscCall(PetscCDGetHeadPos(aggs_2, oldslidj, &pos));
1096: while (pos) {
1097: PetscInt gid;
1099: PetscCall(PetscCDIntNdGetID(pos, &gid));
1100: if (lid + my0 == gid) {
1101: /* id_llist_2[lastid] = id_llist_2[flid]; /\* remove lid from oldslidj list *\/ */
1102: PetscCheck(last, PETSC_COMM_SELF, PETSC_ERR_PLIB, "last cannot be null");
1103: PetscCall(PetscCDRemoveNextNode(aggs_2, oldslidj, last));
1104: /* ghost (PetscScalar)statej will add this later */
1105: hav = 1;
1106: break;
1107: } else last = pos;
1108: PetscCall(PetscCDGetNextPos(aggs_2, oldslidj, &pos));
1109: }
1110: if (hav != 1) {
1111: PetscCheck(hav, PETSC_COMM_SELF, PETSC_ERR_PLIB, "failed to find (hav=%" PetscInt_FMT ") adj in 'selected' lists - structurally unsymmetric matrix", hav);
1112: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "found node %" PetscInt_FMT " times???", hav);
1113: }
1114: } else {
1115: /* TODO: ghosts remove this later */
1116: }
1117: }
1118: }
1119: }
1120: } /* selected/deleted */
1121: } /* node loop */
1123: if (isMPI) {
1124: PetscScalar *cpcol_2_parent, *cpcol_2_gid;
1125: Vec tempVec, ghostgids2, ghostparents2;
1126: PetscInt cpid, nghost_2;
1127: PetscHMapI gid_cpid;
1129: PetscCall(VecGetSize(mpimat_2->lvec, &nghost_2));
1130: PetscCall(MatCreateVecs(Gmat_2, &tempVec, NULL));
1132: /* get 'cpcol_2_parent' */
1133: for (kk = 0, j = my0; kk < nloc; kk++, j++) PetscCall(VecSetValues(tempVec, 1, &j, &lid_parent_gid[kk], INSERT_VALUES));
1134: PetscCall(VecAssemblyBegin(tempVec));
1135: PetscCall(VecAssemblyEnd(tempVec));
1136: PetscCall(VecDuplicate(mpimat_2->lvec, &ghostparents2));
1137: PetscCall(VecScatterBegin(mpimat_2->Mvctx, tempVec, ghostparents2, INSERT_VALUES, SCATTER_FORWARD));
1138: PetscCall(VecScatterEnd(mpimat_2->Mvctx, tempVec, ghostparents2, INSERT_VALUES, SCATTER_FORWARD));
1139: PetscCall(VecGetArray(ghostparents2, &cpcol_2_parent));
1141: /* get 'cpcol_2_gid' */
1142: for (kk = 0, j = my0; kk < nloc; kk++, j++) {
1143: PetscScalar v = (PetscScalar)j;
1145: PetscCall(VecSetValues(tempVec, 1, &j, &v, INSERT_VALUES));
1146: }
1147: PetscCall(VecAssemblyBegin(tempVec));
1148: PetscCall(VecAssemblyEnd(tempVec));
1149: PetscCall(VecDuplicate(mpimat_2->lvec, &ghostgids2));
1150: PetscCall(VecScatterBegin(mpimat_2->Mvctx, tempVec, ghostgids2, INSERT_VALUES, SCATTER_FORWARD));
1151: PetscCall(VecScatterEnd(mpimat_2->Mvctx, tempVec, ghostgids2, INSERT_VALUES, SCATTER_FORWARD));
1152: PetscCall(VecGetArray(ghostgids2, &cpcol_2_gid));
1153: PetscCall(VecDestroy(&tempVec));
1155: /* look for deleted ghosts and add to table */
1156: PetscCall(PetscHMapICreateWithSize(2 * nghost_2 + 1, &gid_cpid));
1157: for (cpid = 0; cpid < nghost_2; cpid++) {
1158: NState state = (NState)PetscRealPart(cpcol_2_state[cpid]);
1160: if (state == DELETED) {
1161: PetscInt sgid_new = (PetscInt)PetscRealPart(cpcol_2_parent[cpid]);
1162: PetscInt sgid_old = (PetscInt)PetscRealPart(cpcol_2_par_orig[cpid]);
1164: if (sgid_old == -1 && sgid_new != -1) {
1165: PetscInt gid = (PetscInt)PetscRealPart(cpcol_2_gid[cpid]);
1167: PetscCall(PetscHMapISet(gid_cpid, gid, cpid));
1168: }
1169: }
1170: }
1172: /* look for deleted ghosts and see if they moved - remove it */
1173: for (lid = 0; lid < nloc; lid++) {
1174: NState state = lid_state[lid];
1176: if (IS_SELECTED(state)) {
1177: PetscCDIntNd *pos, *last = NULL;
1179: /* look for deleted ghosts and see if they moved */
1180: PetscCall(PetscCDGetHeadPos(aggs_2, lid, &pos));
1181: while (pos) {
1182: PetscInt gid;
1184: PetscCall(PetscCDIntNdGetID(pos, &gid));
1185: if (gid < my0 || gid >= Iend) {
1186: PetscCall(PetscHMapIGet(gid_cpid, gid, &cpid));
1187: if (cpid != -1) {
1188: /* a moved ghost - */
1189: /* id_llist_2[lastid] = id_llist_2[flid]; /\* remove 'flid' from list *\/ */
1190: PetscCall(PetscCDRemoveNextNode(aggs_2, lid, last));
1191: } else last = pos;
1192: } else last = pos;
1194: PetscCall(PetscCDGetNextPos(aggs_2, lid, &pos));
1195: } /* loop over list of deleted */
1196: } /* selected */
1197: }
1198: PetscCall(PetscHMapIDestroy(&gid_cpid));
1200: /* look at ghosts, see if they changed - and it */
1201: for (cpid = 0; cpid < nghost_2; cpid++) {
1202: PetscInt sgid_new = (PetscInt)PetscRealPart(cpcol_2_parent[cpid]);
1204: if (sgid_new >= my0 && sgid_new < Iend) { /* this is mine */
1205: PetscInt gid = (PetscInt)PetscRealPart(cpcol_2_gid[cpid]);
1206: PetscInt slid_new = sgid_new - my0, hav = 0;
1207: PetscCDIntNd *pos;
1209: /* search for this gid to see if I have it */
1210: PetscCall(PetscCDGetHeadPos(aggs_2, slid_new, &pos));
1211: while (pos) {
1212: PetscInt gidj;
1214: PetscCall(PetscCDIntNdGetID(pos, &gidj));
1215: PetscCall(PetscCDGetNextPos(aggs_2, slid_new, &pos));
1217: if (gidj == gid) {
1218: hav = 1;
1219: break;
1220: }
1221: }
1222: if (hav != 1) {
1223: /* insert 'flidj' into head of llist */
1224: PetscCall(PetscCDAppendID(aggs_2, slid_new, gid));
1225: }
1226: }
1227: }
1228: PetscCall(VecRestoreArray(mpimat_1->lvec, &cpcol_1_state));
1229: PetscCall(VecRestoreArray(mpimat_2->lvec, &cpcol_2_state));
1230: PetscCall(VecRestoreArray(ghostparents2, &cpcol_2_parent));
1231: PetscCall(VecRestoreArray(ghostgids2, &cpcol_2_gid));
1232: PetscCall(VecDestroy(&ghostgids2));
1233: PetscCall(VecDestroy(&ghostparents2));
1234: PetscCall(VecDestroy(&ghost_par_orig2));
1235: }
1236: PetscCall(PetscFree3(lid_state, lid_parent_gid, lid_cprowID_1));
1237: PetscFunctionReturn(PETSC_SUCCESS);
1238: }
1240: /*
1241: PCGAMGCoarsen_AGG - supports squaring the graph (deprecated) and new graph for
1242: communication of QR data used with HEM and MISk coarsening
1244: Input Parameter:
1245: . a_pc - this
1247: Input/Output Parameter:
1248: . a_Gmat1 - graph to coarsen (in), graph off processor edges for QR gather scatter (out)
1250: Output Parameter:
1251: . agg_lists - list of aggregates
1253: */
1254: static PetscErrorCode PCGAMGCoarsen_AGG(PC a_pc, Mat *a_Gmat1, PetscCoarsenData **agg_lists)
1255: {
1256: PC_MG *mg = (PC_MG *)a_pc->data;
1257: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
1258: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
1259: Mat Gmat2, Gmat1 = *a_Gmat1; /* aggressive graph */
1260: IS perm;
1261: PetscInt Istart, Iend, Ii, nloc, bs, nn;
1262: PetscInt *permute, *degree;
1263: PetscBool *bIndexSet;
1264: PetscReal hashfact;
1265: PetscInt iSwapIndex;
1266: PetscRandom random;
1267: MPI_Comm comm;
1269: PetscFunctionBegin;
1270: PetscCall(PetscObjectGetComm((PetscObject)Gmat1, &comm));
1271: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_COARSEN], 0, 0, 0, 0));
1272: PetscCall(MatGetLocalSize(Gmat1, &nn, NULL));
1273: PetscCall(MatGetBlockSize(Gmat1, &bs));
1274: PetscCheck(bs == 1, PETSC_COMM_SELF, PETSC_ERR_PLIB, "bs %" PetscInt_FMT " must be 1", bs);
1275: nloc = nn / bs;
1276: /* get MIS aggs - randomize */
1277: PetscCall(PetscMalloc2(nloc, &permute, nloc, °ree));
1278: PetscCall(PetscCalloc1(nloc, &bIndexSet));
1279: for (Ii = 0; Ii < nloc; Ii++) permute[Ii] = Ii;
1280: PetscCall(PetscRandomCreate(PETSC_COMM_SELF, &random));
1281: PetscCall(MatGetOwnershipRange(Gmat1, &Istart, &Iend));
1282: for (Ii = 0; Ii < nloc; Ii++) {
1283: PetscInt nc;
1285: PetscCall(MatGetRow(Gmat1, Istart + Ii, &nc, NULL, NULL));
1286: degree[Ii] = nc;
1287: PetscCall(MatRestoreRow(Gmat1, Istart + Ii, &nc, NULL, NULL));
1288: }
1289: for (Ii = 0; Ii < nloc; Ii++) {
1290: PetscCall(PetscRandomGetValueReal(random, &hashfact));
1291: iSwapIndex = (PetscInt)(hashfact * nloc) % nloc;
1292: if (!bIndexSet[iSwapIndex] && iSwapIndex != Ii) {
1293: PetscInt iTemp = permute[iSwapIndex];
1295: permute[iSwapIndex] = permute[Ii];
1296: permute[Ii] = iTemp;
1297: iTemp = degree[iSwapIndex];
1298: degree[iSwapIndex] = degree[Ii];
1299: degree[Ii] = iTemp;
1300: bIndexSet[iSwapIndex] = PETSC_TRUE;
1301: }
1302: }
1303: // apply minimum degree ordering -- NEW
1304: if (pc_gamg_agg->use_minimum_degree_ordering) PetscCall(PetscSortIntWithArray(nloc, degree, permute));
1305: PetscCall(PetscFree(bIndexSet));
1306: PetscCall(PetscRandomDestroy(&random));
1307: PetscCall(ISCreateGeneral(PETSC_COMM_SELF, nloc, permute, PETSC_USE_POINTER, &perm));
1308: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_MIS], 0, 0, 0, 0));
1309: // square graph
1310: if (pc_gamg->current_level < pc_gamg_agg->aggressive_coarsening_levels && pc_gamg_agg->use_aggressive_square_graph) PetscCall(PCGAMGSquareGraph_GAMG(a_pc, Gmat1, &Gmat2));
1311: else Gmat2 = Gmat1;
1312: // switch to old MIS-1 for square graph
1313: if (pc_gamg->current_level < pc_gamg_agg->aggressive_coarsening_levels) {
1314: if (!pc_gamg_agg->use_aggressive_square_graph) PetscCall(MatCoarsenMISKSetDistance(pc_gamg_agg->crs, pc_gamg_agg->aggressive_mis_k)); // hardwire to MIS-2
1315: else PetscCall(MatCoarsenSetType(pc_gamg_agg->crs, MATCOARSENMIS)); // old MIS -- side effect
1316: } else if (pc_gamg_agg->use_aggressive_square_graph && pc_gamg_agg->aggressive_coarsening_levels > 0) { // we reset the MIS
1317: const char *prefix;
1319: PetscCall(PetscObjectGetOptionsPrefix((PetscObject)a_pc, &prefix));
1320: PetscCall(PetscObjectSetOptionsPrefix((PetscObject)pc_gamg_agg->crs, prefix));
1321: PetscCall(MatCoarsenSetFromOptions(pc_gamg_agg->crs)); // get the default back on non-aggressive levels when square graph switched to old MIS
1322: }
1323: PetscCall(MatCoarsenSetAdjacency(pc_gamg_agg->crs, Gmat2));
1324: PetscCall(MatCoarsenSetStrictAggs(pc_gamg_agg->crs, PETSC_TRUE));
1325: PetscCall(MatCoarsenSetGreedyOrdering(pc_gamg_agg->crs, perm));
1326: PetscCall(MatCoarsenApply(pc_gamg_agg->crs));
1327: PetscCall(MatCoarsenGetData(pc_gamg_agg->crs, agg_lists)); /* output */
1329: PetscCall(ISDestroy(&perm));
1330: PetscCall(PetscFree2(permute, degree));
1331: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_MIS], 0, 0, 0, 0));
1333: if (Gmat2 != Gmat1) { // square graph, we need ghosts for selected
1334: PetscCoarsenData *llist = *agg_lists;
1336: PetscCall(fixAggregatesWithSquare(a_pc, Gmat2, Gmat1, *agg_lists));
1337: PetscCall(MatDestroy(&Gmat1));
1338: *a_Gmat1 = Gmat2; /* output */
1339: PetscCall(PetscCDSetMat(llist, *a_Gmat1)); /* Need a graph with ghosts here */
1340: }
1341: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_COARSEN], 0, 0, 0, 0));
1342: PetscFunctionReturn(PETSC_SUCCESS);
1343: }
1345: /*
1346: PCGAMGConstructProlongator_AGG
1348: Input Parameter:
1349: . pc - this
1350: . Amat - matrix on this fine level
1351: . Graph - used to get ghost data for nodes in
1352: . agg_lists - list of aggregates
1353: Output Parameter:
1354: . a_P_out - prolongation operator to the next level
1355: */
1356: static PetscErrorCode PCGAMGConstructProlongator_AGG(PC pc, Mat Amat, PetscCoarsenData *agg_lists, Mat *a_P_out)
1357: {
1358: PC_MG *mg = (PC_MG *)pc->data;
1359: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
1360: const PetscInt col_bs = pc_gamg->data_cell_cols;
1361: PetscInt Istart, Iend, nloc, ii, jj, kk, my0, nLocalSelected, bs;
1362: Mat Gmat, Prol;
1363: PetscMPIInt size;
1364: MPI_Comm comm;
1365: PetscReal *data_w_ghost;
1366: PetscInt myCrs0, nbnodes = 0, *flid_fgid;
1367: MatType mtype;
1369: PetscFunctionBegin;
1370: PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
1371: PetscCheck(col_bs >= 1, comm, PETSC_ERR_PLIB, "Column bs cannot be less than 1");
1372: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_PROL], 0, 0, 0, 0));
1373: PetscCallMPI(MPI_Comm_size(comm, &size));
1374: PetscCall(MatGetOwnershipRange(Amat, &Istart, &Iend));
1375: PetscCall(MatGetBlockSize(Amat, &bs));
1376: nloc = (Iend - Istart) / bs;
1377: my0 = Istart / bs;
1378: PetscCheck((Iend - Istart) % bs == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "(Iend %" PetscInt_FMT " - Istart %" PetscInt_FMT ") not divisible by bs %" PetscInt_FMT, Iend, Istart, bs);
1379: PetscCall(PetscCDGetMat(agg_lists, &Gmat)); // get auxiliary matrix for ghost edges for size > 1
1381: /* get 'nLocalSelected' */
1382: for (ii = 0, nLocalSelected = 0; ii < nloc; ii++) {
1383: PetscBool ise;
1385: /* filter out singletons 0 or 1? */
1386: PetscCall(PetscCDIsEmptyAt(agg_lists, ii, &ise));
1387: if (!ise) nLocalSelected++;
1388: }
1390: /* create prolongator, create P matrix */
1391: PetscCall(MatGetType(Amat, &mtype));
1392: PetscCall(MatCreate(comm, &Prol));
1393: PetscCall(MatSetSizes(Prol, nloc * bs, nLocalSelected * col_bs, PETSC_DETERMINE, PETSC_DETERMINE));
1394: PetscCall(MatSetBlockSizes(Prol, bs, col_bs)); // should this be before MatSetSizes?
1395: PetscCall(MatSetType(Prol, mtype));
1396: #if PetscDefined(HAVE_DEVICE)
1397: PetscBool flg;
1398: PetscCall(MatBoundToCPU(Amat, &flg));
1399: PetscCall(MatBindToCPU(Prol, flg));
1400: if (flg) PetscCall(MatSetBindingPropagates(Prol, PETSC_TRUE));
1401: #endif
1402: PetscCall(MatSeqAIJSetPreallocation(Prol, col_bs, NULL));
1403: PetscCall(MatMPIAIJSetPreallocation(Prol, col_bs, NULL, col_bs, NULL));
1405: /* can get all points "removed" */
1406: PetscCall(MatGetSize(Prol, &kk, &ii));
1407: if (!ii) {
1408: PetscCall(PetscInfo(pc, "%s: No selected points on coarse grid\n", ((PetscObject)pc)->prefix));
1409: PetscCall(MatDestroy(&Prol));
1410: *a_P_out = NULL; /* out */
1411: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_PROL], 0, 0, 0, 0));
1412: PetscFunctionReturn(PETSC_SUCCESS);
1413: }
1414: PetscCall(PetscInfo(pc, "%s: New grid %" PetscInt_FMT " nodes\n", ((PetscObject)pc)->prefix, ii / col_bs));
1415: PetscCall(MatGetOwnershipRangeColumn(Prol, &myCrs0, &kk));
1417: PetscCheck((kk - myCrs0) % col_bs == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "(kk %" PetscInt_FMT " -myCrs0 %" PetscInt_FMT ") not divisible by col_bs %" PetscInt_FMT, kk, myCrs0, col_bs);
1418: myCrs0 = myCrs0 / col_bs;
1419: PetscCheck((kk / col_bs - myCrs0) == nLocalSelected, PETSC_COMM_SELF, PETSC_ERR_PLIB, "(kk %" PetscInt_FMT "/col_bs %" PetscInt_FMT " - myCrs0 %" PetscInt_FMT ") != nLocalSelected %" PetscInt_FMT ")", kk, col_bs, myCrs0, nLocalSelected);
1421: /* create global vector of data in 'data_w_ghost' */
1422: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_PROLA], 0, 0, 0, 0));
1423: if (size > 1) { /* get ghost null space data */
1424: PetscReal *tmp_gdata, *tmp_ldata, *tp2;
1426: PetscCall(PetscMalloc1(nloc, &tmp_ldata));
1427: for (jj = 0; jj < col_bs; jj++) {
1428: for (kk = 0; kk < bs; kk++) {
1429: PetscInt stride;
1430: const PetscReal *tp = PetscSafePointerPlusOffset(pc_gamg->data, jj * bs * nloc + kk);
1432: for (PetscInt ii = 0; ii < nloc; ii++, tp += bs) tmp_ldata[ii] = *tp;
1434: PetscCall(PCGAMGGetDataWithGhosts(Gmat, 1, tmp_ldata, &stride, &tmp_gdata));
1436: if (!jj && !kk) { /* now I know how many total nodes - allocate TODO: move below and do in one 'col_bs' call */
1437: PetscCall(PetscMalloc1(stride * bs * col_bs, &data_w_ghost));
1438: nbnodes = bs * stride;
1439: }
1440: tp2 = PetscSafePointerPlusOffset(data_w_ghost, jj * bs * stride + kk);
1441: for (PetscInt ii = 0; ii < stride; ii++, tp2 += bs) *tp2 = tmp_gdata[ii];
1442: PetscCall(PetscFree(tmp_gdata));
1443: }
1444: }
1445: PetscCall(PetscFree(tmp_ldata));
1446: } else {
1447: nbnodes = bs * nloc;
1448: data_w_ghost = pc_gamg->data;
1449: }
1451: /* get 'flid_fgid' TODO - move up to get 'stride' and do get null space data above in one step (jj loop) */
1452: if (size > 1) {
1453: PetscReal *fid_glid_loc, *fiddata;
1454: PetscInt stride;
1456: PetscCall(PetscMalloc1(nloc, &fid_glid_loc));
1457: for (kk = 0; kk < nloc; kk++) fid_glid_loc[kk] = (PetscReal)(my0 + kk);
1458: PetscCall(PCGAMGGetDataWithGhosts(Gmat, 1, fid_glid_loc, &stride, &fiddata));
1459: PetscCall(PetscMalloc1(stride, &flid_fgid)); /* copy real data to in */
1460: for (kk = 0; kk < stride; kk++) flid_fgid[kk] = (PetscInt)fiddata[kk];
1461: PetscCall(PetscFree(fiddata));
1463: PetscCheck(stride == nbnodes / bs, PETSC_COMM_SELF, PETSC_ERR_PLIB, "stride %" PetscInt_FMT " != nbnodes %" PetscInt_FMT "/bs %" PetscInt_FMT, stride, nbnodes, bs);
1464: PetscCall(PetscFree(fid_glid_loc));
1465: } else {
1466: PetscCall(PetscMalloc1(nloc, &flid_fgid));
1467: for (kk = 0; kk < nloc; kk++) flid_fgid[kk] = my0 + kk;
1468: }
1469: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_PROLA], 0, 0, 0, 0));
1470: /* get P0 */
1471: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_PROLB], 0, 0, 0, 0));
1472: {
1473: PetscReal *data_out = NULL;
1475: PetscCall(formProl0(agg_lists, bs, col_bs, myCrs0, nbnodes, data_w_ghost, flid_fgid, &data_out, Prol));
1476: PetscCall(PetscFree(pc_gamg->data));
1478: pc_gamg->data = data_out;
1479: pc_gamg->data_cell_rows = col_bs;
1480: pc_gamg->data_sz = col_bs * col_bs * nLocalSelected;
1481: }
1482: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_PROLB], 0, 0, 0, 0));
1483: if (size > 1) PetscCall(PetscFree(data_w_ghost));
1484: PetscCall(PetscFree(flid_fgid));
1486: *a_P_out = Prol; /* out */
1487: PetscCall(MatViewFromOptions(Prol, NULL, "-pc_gamg_agg_view_initial_prolongation"));
1489: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_PROL], 0, 0, 0, 0));
1490: PetscFunctionReturn(PETSC_SUCCESS);
1491: }
1493: /*
1494: PCGAMGKernelPreservingFilter_AGG - filter the prolongator while preserving the near-null space constraint P*B_c = B
1496: Applies `MatFilter()` to drop small entries, then corrects each row so that
1497: P_filtered * B_c = B (the fine near-null space) is restored.
1499: For nSAvec == 1: rescale each row by B[i] / (P_filtered[i,:] * B_c[J_i]).
1500: For nSAvec > 1: solve a small nSAvec x nSAvec SPD system per row and add
1501: a rank-nSAvec correction to the row entries.
1502: */
1503: static PetscErrorCode PCGAMGKernelPreservingFilter_AGG(PC pc, Mat Prol, PetscReal threshold)
1504: {
1505: PC_MG *mg = (PC_MG *)pc->data;
1506: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
1507: const PetscInt nSAvec = pc_gamg->data_cell_rows; /* == data_cell_cols after formProl0 */
1508: PetscInt cStart, cEnd, rStart, rEnd;
1509: const PetscReal *Bc_data = pc_gamg->data;
1510: Vec *Bc_vecs, *B_vecs;
1511: PetscScalar *Bc_arr;
1513: PetscFunctionBegin;
1514: PetscCall(PetscInfo(pc, "Kernel-preserving filter of prolongator with threshold %g, nSAvec=%" PetscInt_FMT "\n", (double)threshold, nSAvec));
1516: PetscCall(MatGetOwnershipRange(Prol, &rStart, &rEnd));
1517: PetscCall(MatGetOwnershipRangeColumn(Prol, &cStart, &cEnd));
1519: /* Step 1: build coarse null-space vectors and compute B = P_original * B_c */
1520: PetscCall(PetscMalloc1(nSAvec, &Bc_vecs));
1521: PetscCall(PetscMalloc1(nSAvec, &B_vecs));
1523: {
1524: PetscInt nloc = cEnd - cStart;
1525: for (PetscInt k = 0; k < nSAvec; k++) {
1526: PetscCall(MatCreateVecs(Prol, &Bc_vecs[k], &B_vecs[k]));
1527: /* fill local entries: Bc_data layout is Bc_data[k * nloc + c] (stride == nloc) */
1528: PetscCall(VecGetArray(Bc_vecs[k], &Bc_arr));
1529: for (PetscInt c = 0; c < nloc; c++) Bc_arr[c] = (PetscScalar)Bc_data[k * nloc + c];
1530: PetscCall(VecRestoreArray(Bc_vecs[k], &Bc_arr));
1531: PetscCall(MatMult(Prol, Bc_vecs[k], B_vecs[k]));
1532: }
1533: }
1535: /* Step 2: apply the threshold filter */
1536: {
1537: PetscBool info_active = PETSC_FALSE;
1538: MatInfo info0, info1;
1539: PetscCall(PetscInfoEnabled(((PetscObject)pc)->classid, &info_active));
1540: if (info_active) PetscCall(MatGetInfo(Prol, MAT_GLOBAL_SUM, &info0));
1541: PetscCall(MatFilter(Prol, threshold, PETSC_TRUE, PETSC_TRUE));
1542: if (info_active) {
1543: PetscCall(MatGetInfo(Prol, MAT_GLOBAL_SUM, &info1));
1544: PetscCall(PetscInfo(pc, "Prolongator filter: nnz before=%g after=%g reduction=%g%%\n", info0.nz_used, info1.nz_used, (info0.nz_used > 0) ? 100.0 * (info0.nz_used - info1.nz_used) / info0.nz_used : 0.0));
1545: }
1546: }
1548: /* Step 3: correct rows to restore P_filtered * B_c = B */
1549: if (nSAvec == 1) {
1550: /*
1551: Scalar case: use `MatMult()` + element-wise scaling + `MatDiagonalScale()`.
1552: scale_i = B_i / (P_filtered * Bc)_i, then P_new = diag(scale) * P_filtered.
1553: Guard against zero denominators (empty rows after filter).
1554: No ghost column access needed.
1555: */
1556: Vec d_vec, scale_vec;
1557: PetscInt n_local;
1558: PetscScalar *s_arr;
1559: const PetscScalar *b_arr, *d_arr;
1561: PetscCall(MatCreateVecs(Prol, NULL, &d_vec));
1562: PetscCall(MatMult(Prol, Bc_vecs[0], d_vec));
1563: PetscCall(VecDuplicate(d_vec, &scale_vec));
1564: PetscCall(VecGetLocalSize(d_vec, &n_local));
1565: PetscCall(VecGetArrayRead(B_vecs[0], &b_arr));
1566: PetscCall(VecGetArrayRead(d_vec, &d_arr));
1567: PetscCall(VecGetArray(scale_vec, &s_arr));
1568: for (PetscInt i = 0; i < n_local; i++) s_arr[i] = (PetscAbsScalar(d_arr[i]) > 0.0) ? b_arr[i] / d_arr[i] : 1.0;
1569: PetscCall(VecRestoreArray(scale_vec, &s_arr));
1570: PetscCall(VecRestoreArrayRead(d_vec, &d_arr));
1571: PetscCall(VecRestoreArrayRead(B_vecs[0], &b_arr));
1572: PetscCall(MatDiagonalScale(Prol, scale_vec, NULL));
1573: PetscCall(VecDestroy(&d_vec));
1574: PetscCall(VecDestroy(&scale_vec));
1575: } else {
1576: /*
1577: Vector case (nSAvec > 1): per-row least-squares correction.
1578: Scatter Bc_data to include ghost column values using Prol's Mvctx,
1579: then build a hash map from global ghost column index to local ghost index
1580: so that `MatGetRow()` global column indices can be mapped to the ghosted array.
1581: */
1582: PetscInt nloc = cEnd - cStart;
1583: PetscInt ghost_stride;
1584: PetscReal *Bc_ghosted = NULL;
1585: const PetscReal *Bc_ghosted_ro;
1586: PetscMPIInt comm_size;
1587: PetscHMapI ghost_gid_to_lid; /* global ghost col index -> local ghost index (0-based) */
1588: PetscInt num_ghosts = 0;
1590: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)Prol), &comm_size));
1591: if (comm_size > 1) {
1592: Mat_MPIAIJ *mpimat = (Mat_MPIAIJ *)Prol->data;
1593: Vec tmp_vec;
1594: PetscScalar *data_arr;
1595: PetscInt nnodes;
1597: PetscCall(VecGetLocalSize(mpimat->lvec, &num_ghosts));
1598: nnodes = nloc + num_ghosts;
1599: ghost_stride = nnodes;
1600: /*
1601: Scatter Bc_data to include ghost column values using Prol's Mvctx.
1602: Cannot use PCGAMGGetDataWithGhosts() because it assumes square matrix
1603: (uses MatGetOwnershipRange() for row indices, but Prol is rectangular).
1604: */
1605: PetscCall(MatCreateVecs(Prol, &tmp_vec, NULL));
1606: PetscCall(PetscMalloc1(nSAvec * nnodes, &Bc_ghosted));
1607: for (PetscInt dir = 0; dir < nSAvec; dir++) {
1608: PetscScalar *tmp_arr;
1609: PetscCall(VecGetArray(tmp_vec, &tmp_arr));
1610: for (PetscInt kk = 0; kk < nloc; kk++) {
1611: PetscReal val = Bc_data[dir * nloc + kk];
1612: Bc_ghosted[dir * nnodes + kk] = val;
1613: tmp_arr[kk] = (PetscScalar)val;
1614: }
1615: PetscCall(VecRestoreArray(tmp_vec, &tmp_arr));
1616: PetscCall(VecScatterBegin(mpimat->Mvctx, tmp_vec, mpimat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1617: PetscCall(VecScatterEnd(mpimat->Mvctx, tmp_vec, mpimat->lvec, INSERT_VALUES, SCATTER_FORWARD));
1618: PetscCall(VecGetArray(mpimat->lvec, &data_arr));
1619: for (PetscInt g = 0; g < num_ghosts; g++) Bc_ghosted[dir * nnodes + nloc + g] = PetscRealPart(data_arr[g]);
1620: PetscCall(VecRestoreArray(mpimat->lvec, &data_arr));
1621: }
1622: PetscCall(VecDestroy(&tmp_vec));
1623: Bc_ghosted_ro = Bc_ghosted;
1624: /* build hash: global ghost col index -> local ghost index (0-based into ghost portion) */
1625: PetscCall(PetscHMapICreateWithSize(2 * num_ghosts + 1, &ghost_gid_to_lid));
1626: for (PetscInt g = 0; g < num_ghosts; g++) PetscCall(PetscHMapISet(ghost_gid_to_lid, mpimat->garray[g], g));
1627: } else {
1628: /* sequential: no ghosts, ghost_stride == nloc, use Bc_data directly (read-only) */
1629: ghost_stride = nloc;
1630: Bc_ghosted_ro = Bc_data;
1631: PetscCall(PetscHMapICreateWithSize(1, &ghost_gid_to_lid));
1632: }
1634: {
1635: PetscInt nrows = rEnd - rStart, max_ncols = 0;
1636: const PetscScalar **B_arrays;
1637: PetscScalar *work, *new_vals, *G, *rhs, *x, *bc_col;
1638: PetscInt *ghosted_idx, *col_buf;
1639: PetscBLASInt *ipiv;
1640: PetscBLASInt N_b;
1642: PetscCall(PetscMalloc1(nSAvec, &B_arrays));
1643: for (PetscInt k = 0; k < nSAvec; k++) PetscCall(VecGetArrayRead(B_vecs[k], &B_arrays[k]));
1644: /* work: nSAvec*nSAvec Gram + nSAvec rhs + nSAvec solution + nSAvec bc_col scratch */
1645: PetscCall(PetscMalloc1(nSAvec * nSAvec + 3 * nSAvec, &work));
1646: PetscCall(PetscMalloc1(nSAvec, &ipiv));
1647: PetscCall(PetscBLASIntCast(nSAvec, &N_b));
1648: G = work;
1649: rhs = work + nSAvec * nSAvec;
1650: x = rhs + nSAvec;
1651: bc_col = x + nSAvec;
1653: /* find max row width and total nnz for pre-allocation */
1654: {
1655: PetscInt total_nnz = 0;
1656: for (PetscInt row = 0; row < nrows; row++) {
1657: PetscInt ncols;
1658: PetscCall(MatGetRow(Prol, rStart + row, &ncols, NULL, NULL));
1659: if (ncols > max_ncols) max_ncols = ncols;
1660: total_nnz += ncols;
1661: PetscCall(MatRestoreRow(Prol, rStart + row, &ncols, NULL, NULL));
1662: }
1663: /* allocate flat CSR-like buffers to store all corrections before applying */
1664: PetscCall(PetscMalloc1(total_nnz, &new_vals));
1665: PetscCall(PetscMalloc1(total_nnz, &col_buf));
1666: }
1667: PetscCall(PetscMalloc1(max_ncols, &ghosted_idx));
1669: /* Pass 1: read rows, compute corrections, store in flat buffers */
1670: {
1671: PetscInt *row_offsets;
1672: PetscInt offset = 0, n_singular = 0, n_zero_rows = 0, n_corrected = 0, n_underdetermined = 0;
1673: PetscReal max_xnorm = 0.0;
1675: PetscCall(PetscMalloc1(nrows + 1, &row_offsets));
1676: PetscCall(PetscFPTrapPush(PETSC_FP_TRAP_OFF));
1678: for (PetscInt row = 0; row < nrows; row++) {
1679: PetscInt ncols;
1680: const PetscInt *cols;
1681: const PetscScalar *vals;
1682: PetscInt grow = rStart + row;
1683: PetscBLASInt NRHS = 1, LDA = N_b, LDB = N_b, info;
1685: row_offsets[row] = offset;
1686: PetscCall(MatGetRow(Prol, grow, &ncols, &cols, &vals));
1687: if (ncols == 0) {
1688: n_zero_rows++;
1689: PetscCall(MatRestoreRow(Prol, grow, &ncols, &cols, &vals));
1690: continue;
1691: }
1693: /* When ncols < nSAvec the Gram matrix G is rank-deficient by construction;
1694: skip correction for this row (keep filtered values as-is).
1695: Note: the near-null space constraint P*Bc = B is NOT enforced for these rows.
1696: This typically occurs at boundary or isolated nodes where few coarse neighbors
1697: remain after filtering; the impact on convergence is generally small. */
1698: if (ncols < nSAvec) {
1699: n_underdetermined++;
1700: for (PetscInt j = 0; j < ncols; j++) {
1701: col_buf[offset + j] = cols[j];
1702: new_vals[offset + j] = vals[j];
1703: }
1704: offset += ncols;
1705: PetscCall(MatRestoreRow(Prol, grow, &ncols, &cols, &vals));
1706: continue;
1707: }
1709: /* map global column indices to ghosted array indices and save cols */
1710: for (PetscInt j = 0; j < ncols; j++) {
1711: col_buf[offset + j] = cols[j];
1712: if (cols[j] >= cStart && cols[j] < cEnd) ghosted_idx[j] = cols[j] - cStart;
1713: else {
1714: PetscInt g = -1;
1715: PetscCall(PetscHMapIGet(ghost_gid_to_lid, cols[j], &g));
1716: PetscCheck(g >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Off-diagonal column %" PetscInt_FMT " not found in ghost map for prolongator filter", cols[j]);
1717: ghosted_idx[j] = nloc + g;
1718: }
1719: }
1721: for (PetscInt i = 0; i < nSAvec * nSAvec; i++) G[i] = 0.0;
1723: /* rhs[k] = B[row,k] - sum_j P[row,j] * Bc[ghosted_idx[j], k] */
1724: for (PetscInt k = 0; k < nSAvec; k++) {
1725: PetscScalar dot = 0.0;
1726: for (PetscInt j = 0; j < ncols; j++) dot += vals[j] * (PetscScalar)Bc_ghosted_ro[k * ghost_stride + ghosted_idx[j]];
1727: rhs[k] = B_arrays[k][row] - dot;
1728: }
1730: /* G[k1,k2] = sum_j Bc[j,k1] * Bc[j,k2] using pre-gathered bc_col */
1731: for (PetscInt j = 0; j < ncols; j++) {
1732: PetscInt gidx = ghosted_idx[j];
1733: for (PetscInt k = 0; k < nSAvec; k++) bc_col[k] = (PetscScalar)Bc_ghosted_ro[k * ghost_stride + gidx];
1734: for (PetscInt k1 = 0; k1 < nSAvec; k1++)
1735: for (PetscInt k2 = k1; k2 < nSAvec; k2++) G[k1 * nSAvec + k2] += bc_col[k1] * bc_col[k2];
1736: }
1737: /* fill lower triangle from upper (G is symmetric) */
1738: for (PetscInt k1 = 1; k1 < nSAvec; k1++)
1739: for (PetscInt k2 = 0; k2 < k1; k2++) G[k1 * nSAvec + k2] = G[k2 * nSAvec + k1];
1741: /* solve G * x = rhs */
1742: for (PetscInt i = 0; i < nSAvec; i++) x[i] = rhs[i];
1743: PetscCallBLAS("LAPACKgesv", LAPACKgesv_(&N_b, &NRHS, G, &LDA, ipiv, x, &LDB, &info));
1744: if (info != 0) {
1745: /* G is singular despite ncols >= nSAvec (Bc columns linearly dependent);
1746: keep filtered values as-is (near-null space constraint not enforced for this row) */
1747: n_singular++;
1748: for (PetscInt j = 0; j < ncols; j++) new_vals[offset + j] = vals[j];
1749: offset += ncols;
1750: PetscCall(MatRestoreRow(Prol, grow, &ncols, &cols, &vals));
1751: continue;
1752: }
1754: /* track ||x||^2 */
1755: {
1756: PetscReal xnorm2 = 0.0;
1757: for (PetscInt k = 0; k < nSAvec; k++) xnorm2 += PetscSqr(PetscAbsScalar(x[k]));
1758: if (xnorm2 > max_xnorm) max_xnorm = xnorm2;
1759: }
1760: n_corrected++;
1762: /* new_vals[j] = vals[j] + sum_k Bc[ghosted_idx[j],k] * x[k] */
1763: for (PetscInt j = 0; j < ncols; j++) {
1764: PetscScalar delta = 0.0;
1765: PetscInt gidx = ghosted_idx[j];
1766: for (PetscInt k = 0; k < nSAvec; k++) delta += (PetscScalar)Bc_ghosted_ro[k * ghost_stride + gidx] * x[k];
1767: new_vals[offset + j] = vals[j] + delta;
1768: }
1769: offset += ncols;
1770: PetscCall(MatRestoreRow(Prol, grow, &ncols, &cols, &vals));
1771: }
1772: row_offsets[nrows] = offset;
1773: PetscCall(PetscFPTrapPop());
1774: PetscCall(PetscInfo(pc, "PCGAMGKernelPreservingFilter_AGG: nrows=%" PetscInt_FMT " corrected=%" PetscInt_FMT " zero_rows=%" PetscInt_FMT " underdetermined(ncols<nSAvec)=%" PetscInt_FMT " singular_G=%" PetscInt_FMT " max_xnorm2=%g\n", nrows, n_corrected, n_zero_rows, n_underdetermined, n_singular, (double)max_xnorm));
1776: /* Pass 2: apply all corrections at once */
1777: for (PetscInt row = 0; row < nrows; row++) {
1778: PetscInt grow = rStart + row;
1779: PetscInt nc = row_offsets[row + 1] - row_offsets[row];
1780: if (nc > 0) PetscCall(MatSetValues(Prol, 1, &grow, nc, col_buf + row_offsets[row], new_vals + row_offsets[row], INSERT_VALUES));
1781: }
1782: PetscCall(PetscFree(row_offsets));
1783: }
1785: for (PetscInt k = 0; k < nSAvec; k++) PetscCall(VecRestoreArrayRead(B_vecs[k], &B_arrays[k]));
1786: PetscCall(PetscFree(B_arrays));
1787: PetscCall(PetscFree(work));
1788: PetscCall(PetscFree(ipiv));
1789: PetscCall(PetscFree(ghosted_idx));
1790: PetscCall(PetscFree(new_vals));
1791: PetscCall(PetscFree(col_buf));
1792: }
1794: PetscCall(PetscHMapIDestroy(&ghost_gid_to_lid));
1795: if (comm_size > 1) PetscCall(PetscFree(Bc_ghosted));
1796: }
1798: PetscCall(MatAssemblyBegin(Prol, MAT_FINAL_ASSEMBLY));
1799: PetscCall(MatAssemblyEnd(Prol, MAT_FINAL_ASSEMBLY));
1801: for (PetscInt k = 0; k < nSAvec; k++) {
1802: PetscCall(VecDestroy(&Bc_vecs[k]));
1803: PetscCall(VecDestroy(&B_vecs[k]));
1804: }
1805: PetscCall(PetscFree(Bc_vecs));
1806: PetscCall(PetscFree(B_vecs));
1807: PetscFunctionReturn(PETSC_SUCCESS);
1808: }
1810: /*
1811: PCGAMGOptimizeProlongator_AGG - given the initial prolongator optimizes it by smoothed aggregation pc_gamg_agg->nsmooths times
1813: Input Parameter:
1814: . pc - this
1815: . Amat - matrix on this fine level
1816: In/Output Parameter:
1817: . a_P - prolongation operator to the next level
1818: */
1819: static PetscErrorCode PCGAMGOptimizeProlongator_AGG(PC pc, Mat Amat, Mat *a_P)
1820: {
1821: PC_MG *mg = (PC_MG *)pc->data;
1822: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
1823: PC_GAMG_AGG *pc_gamg_agg = (PC_GAMG_AGG *)pc_gamg->subctx;
1824: Mat Prol = *a_P;
1825: MPI_Comm comm;
1826: KSP eksp;
1827: Vec bb, xx;
1828: PC epc;
1829: PetscReal alpha, emax, emin;
1831: PetscFunctionBegin;
1832: PetscCall(PetscObjectGetComm((PetscObject)Amat, &comm));
1833: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_OPT], 0, 0, 0, 0));
1835: /* compute maximum singular value of operator to be used in smoother */
1836: if (0 < pc_gamg_agg->nsmooths) {
1837: /* get eigen estimates */
1838: if (pc_gamg->emax > 0) {
1839: emin = pc_gamg->emin;
1840: emax = pc_gamg->emax;
1841: } else {
1842: const char *prefix;
1844: PetscCall(MatCreateVecs(Amat, &bb, NULL));
1845: PetscCall(MatCreateVecs(Amat, &xx, NULL));
1846: PetscCall(KSPSetNoisy_Private(Amat, bb));
1848: PetscCall(KSPCreate(comm, &eksp));
1849: PetscCall(KSPSetNestLevel(eksp, pc->kspnestlevel));
1850: PetscCall(PCGetOptionsPrefix(pc, &prefix));
1851: PetscCall(KSPSetOptionsPrefix(eksp, prefix));
1852: PetscCall(KSPAppendOptionsPrefix(eksp, "pc_gamg_esteig_"));
1853: {
1854: PetscBool isset, sflg;
1856: PetscCall(MatIsSPDKnown(Amat, &isset, &sflg));
1857: if (isset && sflg) PetscCall(KSPSetType(eksp, KSPCG));
1858: }
1859: PetscCall(KSPSetErrorIfNotConverged(eksp, pc->erroriffailure));
1860: PetscCall(KSPSetNormType(eksp, KSP_NORM_NONE));
1862: PetscCall(KSPSetInitialGuessNonzero(eksp, PETSC_FALSE));
1863: PetscCall(KSPSetOperators(eksp, Amat, Amat));
1865: PetscCall(KSPGetPC(eksp, &epc));
1866: PetscCall(PCSetType(epc, PCJACOBI)); /* smoother in smoothed agg. */
1868: PetscCall(KSPSetTolerances(eksp, PETSC_CURRENT, PETSC_CURRENT, PETSC_CURRENT, 10)); // 10 is safer, but 5 is often fine, can override with -pc_gamg_esteig_ksp_max_it -mg_levels_ksp_chebyshev_esteig 0,0.25,0,1.2
1870: PetscCall(KSPSetFromOptions(eksp));
1871: PetscCall(KSPSetComputeSingularValues(eksp, PETSC_TRUE));
1872: PetscCall(KSPSolve(eksp, bb, xx));
1873: PetscCall(KSPCheckSolve(eksp, pc, xx));
1875: PetscCall(KSPComputeExtremeSingularValues(eksp, &emax, &emin));
1876: PetscCall(PetscInfo(pc, "%s: Smooth P0: max eigen=%e min=%e PC=%s\n", ((PetscObject)pc)->prefix, (double)emax, (double)emin, PCJACOBI));
1877: PetscCall(VecDestroy(&xx));
1878: PetscCall(VecDestroy(&bb));
1879: PetscCall(KSPDestroy(&eksp));
1880: }
1881: if (pc_gamg->use_sa_esteig) {
1882: mg->min_eigen_DinvA[pc_gamg->current_level] = emin;
1883: mg->max_eigen_DinvA[pc_gamg->current_level] = emax;
1884: PetscCall(PetscInfo(pc, "%s: Smooth P0: level %" PetscInt_FMT ", cache spectra %g %g\n", ((PetscObject)pc)->prefix, pc_gamg->current_level, (double)emin, (double)emax));
1885: } else {
1886: mg->min_eigen_DinvA[pc_gamg->current_level] = 0;
1887: mg->max_eigen_DinvA[pc_gamg->current_level] = 0;
1888: }
1889: } else {
1890: mg->min_eigen_DinvA[pc_gamg->current_level] = 0;
1891: mg->max_eigen_DinvA[pc_gamg->current_level] = 0;
1892: }
1894: /* smooth P0 */
1895: if (pc_gamg_agg->nsmooths > 0) {
1896: Vec diag;
1898: /* TODO: Set a PCFailedReason and exit the building of the AMG preconditioner */
1899: PetscCheck(emax != 0.0, PetscObjectComm((PetscObject)pc), PETSC_ERR_PLIB, "Computed maximum singular value as zero");
1901: PetscCall(MatCreateVecs(Amat, &diag, NULL));
1902: PetscCall(MatGetDiagonal(Amat, diag)); /* effectively PCJACOBI */
1903: PetscCall(VecReciprocal(diag));
1905: for (PetscInt jj = 0; jj < pc_gamg_agg->nsmooths; jj++) {
1906: Mat tMat;
1908: PetscCall(PetscLogEventBegin(petsc_gamg_setup_events[GAMG_OPTSM], 0, 0, 0, 0));
1909: /*
1910: Smooth aggregation on the prolongator
1912: P_{i} := (I - 1.4/emax D^{-1}A) P_i\{i-1}
1913: */
1914: PetscCall(PetscLogEventBegin(petsc_gamg_setup_matmat_events[pc_gamg->current_level][2], 0, 0, 0, 0));
1915: PetscCall(MatMatMult(Amat, Prol, MAT_INITIAL_MATRIX, PETSC_CURRENT, &tMat));
1916: PetscCall(PetscLogEventEnd(petsc_gamg_setup_matmat_events[pc_gamg->current_level][2], 0, 0, 0, 0));
1917: PetscCall(MatProductClear(tMat));
1918: PetscCall(MatDiagonalScale(tMat, diag, NULL));
1920: /* TODO: Document the 1.4 and don't hardwire it in this routine */
1921: alpha = -1.4 / emax;
1922: PetscCall(MatAYPX(tMat, alpha, Prol, SUBSET_NONZERO_PATTERN));
1923: PetscCall(MatDestroy(&Prol));
1924: Prol = tMat;
1925: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_OPTSM], 0, 0, 0, 0));
1926: }
1927: PetscCall(VecDestroy(&diag));
1928: }
1929: if (pc_gamg->prolongator_filter > 0.0) PetscCall(PCGAMGKernelPreservingFilter_AGG(pc, Prol, pc_gamg->prolongator_filter));
1930: PetscCall(PetscLogEventEnd(petsc_gamg_setup_events[GAMG_OPT], 0, 0, 0, 0));
1931: PetscCall(MatViewFromOptions(Prol, NULL, "-pc_gamg_agg_view_prolongation"));
1932: *a_P = Prol;
1933: PetscFunctionReturn(PETSC_SUCCESS);
1934: }
1936: /*MC
1937: PCGAMGAGG - Smooth aggregation, {cite}`vanek1996algebraic`, {cite}`vanek2001convergence`, variant of PETSc's algebraic multigrid (`PCGAMG`) preconditioner
1939: Options Database Keys:
1940: + -pc_gamg_agg_nsmooths nsmooth - number of smoothing steps to use with smooth aggregation to construct prolongation
1941: . -pc_gamg_prolongator_filter thr - filter small entries from the prolongator, preserving the near-null space (0=disabled, 0.0025=typical)
1942: . -pc_gamg_aggressive_coarsening n - number of aggressive coarsening (MIS-2 or square graph) levels from finest.
1943: . -pc_gamg_aggressive_square_graph (true|false) - use square graph ($A^T A$), alternative is MIS-k (k=2), for aggressive coarsening
1944: . -pc_gamg_mis_k_minimum_degree_ordering (true|false) - use minimum degree ordering in greedy MIS algorithm
1945: . -pc_gamg_asm_hem_aggs n - number of HEM aggregation steps for ASM smoother
1946: - -pc_gamg_aggressive_mis_k n - number (k) distance in MIS coarsening (>2 is 'aggressive')
1948: Level: intermediate
1950: Notes:
1951: To obtain good performance for `PCGAMG` for vector valued problems you must
1952: call `MatSetBlockSize()` to indicate the number of degrees of freedom per grid point.
1953: Call `MatSetNearNullSpace()` (or `PCSetCoordinates()` if solving the equations of elasticity) to indicate the near null space of the operator
1955: When `-pc_gamg_aggressive_square_graph` is used, the coarsening is obtained by first squaring the graph and then applying, by default, a
1956: MIS-1 coarsening with `MatCoarsenApply()` on the squared graph.
1958: The many options for `PCMG` and `PCGAMG` such as controlling the smoothers on each level etc. also work for `PCGAMGAGG`
1960: .seealso: `PCGAMG`, [the Users Manual section on PCGAMG](sec_amg), [the Users Manual section on PCMG](sec_mg), [](ch_ksp), `PCCreate()`, `PCSetType()`,
1961: `MatSetBlockSize()`, `PCMGType`, `PCSetCoordinates()`, `MatSetNearNullSpace()`, `PCGAMGSetType()`,
1962: `PCGAMGAGG`, `PCGAMGGEO`, `PCGAMGCLASSICAL`, `PCGAMGSetProcEqLim()`, `PCGAMGSetCoarseEqLim()`, `PCGAMGSetRepartition()`, `PCGAMGRegister()`,
1963: `PCGAMGSetReuseInterpolation()`, `PCGAMGASMSetUseAggs()`, `PCGAMGSetParallelCoarseGridSolve()`, `PCGAMGSetNlevels()`, `PCGAMGSetThreshold()`,
1964: `PCGAMGGetType()`, `PCGAMGSetUseSAEstEig()`
1965: M*/
1966: PetscErrorCode PCCreateGAMG_AGG(PC pc)
1967: {
1968: PC_MG *mg = (PC_MG *)pc->data;
1969: PC_GAMG *pc_gamg = (PC_GAMG *)mg->innerctx;
1970: PC_GAMG_AGG *pc_gamg_agg;
1972: PetscFunctionBegin;
1973: /* create sub context for SA */
1974: PetscCall(PetscNew(&pc_gamg_agg));
1975: pc_gamg->subctx = pc_gamg_agg;
1977: pc_gamg->ops->setfromoptions = PCSetFromOptions_GAMG_AGG;
1978: pc_gamg->ops->destroy = PCDestroy_GAMG_AGG;
1979: /* reset does not do anything; setup not virtual */
1981: /* set internal function pointers */
1982: pc_gamg->ops->creategraph = PCGAMGCreateGraph_AGG;
1983: pc_gamg->ops->coarsen = PCGAMGCoarsen_AGG;
1984: pc_gamg->ops->prolongator = PCGAMGConstructProlongator_AGG;
1985: pc_gamg->ops->optprolongator = PCGAMGOptimizeProlongator_AGG;
1986: pc_gamg->ops->createdefaultdata = PCSetData_AGG;
1987: pc_gamg->ops->view = PCView_GAMG_AGG;
1989: pc_gamg_agg->nsmooths = 1;
1990: pc_gamg_agg->aggressive_coarsening_levels = 1;
1991: pc_gamg_agg->use_aggressive_square_graph = PETSC_TRUE;
1992: pc_gamg_agg->use_minimum_degree_ordering = PETSC_FALSE;
1993: pc_gamg_agg->use_low_mem_filter = PETSC_FALSE;
1994: pc_gamg_agg->aggressive_mis_k = 2;
1995: pc_gamg_agg->graph_symmetrize = PETSC_TRUE;
1997: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetNSmooths_C", PCGAMGSetNSmooths_AGG));
1998: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetAggressiveLevels_C", PCGAMGSetAggressiveLevels_AGG));
1999: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetAggressiveSquareGraph_C", PCGAMGSetAggressiveSquareGraph_AGG));
2000: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGMISkSetMinDegreeOrdering_C", PCGAMGMISkSetMinDegreeOrdering_AGG));
2001: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetLowMemoryFilter_C", PCGAMGSetLowMemoryFilter_AGG));
2002: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGMISkSetAggressive_C", PCGAMGMISkSetAggressive_AGG));
2003: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetGraphSymmetrize_C", PCGAMGSetGraphSymmetrize_AGG));
2004: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGSetProlongatorFilter_C", PCGAMGSetProlongatorFilter_AGG));
2005: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCGAMGGetProlongatorFilter_C", PCGAMGGetProlongatorFilter_AGG));
2006: PetscCall(PetscObjectComposeFunction((PetscObject)pc, "PCSetCoordinates_C", PCSetCoordinates_AGG));
2007: PetscFunctionReturn(PETSC_SUCCESS);
2008: }