Actual source code: partition.c

  1: #include <petsc/private/matimpl.h>

  3: /* Logging support */
  4: PetscClassId MAT_PARTITIONING_CLASSID;

  6: /*
  7:    Simplest partitioning, keeps the current partitioning.
  8: */
  9: static PetscErrorCode MatPartitioningApply_Current(MatPartitioning part, IS *partitioning)
 10: {
 11:   PetscInt    m;
 12:   PetscMPIInt rank, size;

 14:   PetscFunctionBegin;
 15:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)part), &size));
 16:   if (part->n != size) {
 17:     const char *prefix;
 18:     PetscCall(PetscObjectGetOptionsPrefix((PetscObject)part, &prefix));
 19:     SETERRQ(PetscObjectComm((PetscObject)part), PETSC_ERR_SUP, "This is the DEFAULT NO-OP partitioner, it currently only supports one domain per processor\nuse -%smat_partitioning_type (parmetis|chaco|ptscotch) for more than one subdomain per processor", prefix ? prefix : "");
 20:   }
 21:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)part), &rank));

 23:   PetscCall(MatGetLocalSize(part->adj, &m, NULL));
 24:   PetscCall(ISCreateStride(PetscObjectComm((PetscObject)part), m, rank, 0, partitioning));
 25:   PetscFunctionReturn(PETSC_SUCCESS);
 26: }

 28: /*
 29:    partition an index to rebalance the computation
 30: */
 31: static PetscErrorCode MatPartitioningApply_Average(MatPartitioning part, IS *partitioning)
 32: {
 33:   PetscInt m, M, nparts, *indices, r, d, *parts, i, start, end, loc;

 35:   PetscFunctionBegin;
 36:   PetscCall(MatGetSize(part->adj, &M, NULL));
 37:   PetscCall(MatGetLocalSize(part->adj, &m, NULL));
 38:   nparts = part->n;
 39:   PetscCall(PetscMalloc1(nparts, &parts));
 40:   d = M / nparts;
 41:   for (i = 0; i < nparts; i++) parts[i] = d;
 42:   r = M % nparts;
 43:   for (i = 0; i < r; i++) parts[i] += 1;
 44:   for (i = 1; i < nparts; i++) parts[i] += parts[i - 1];
 45:   PetscCall(PetscMalloc1(m, &indices));
 46:   PetscCall(MatGetOwnershipRange(part->adj, &start, &end));
 47:   for (i = start; i < end; i++) {
 48:     PetscCall(PetscFindInt(i, nparts, parts, &loc));
 49:     if (loc < 0) loc = -(loc + 1);
 50:     else loc = loc + 1;
 51:     indices[i - start] = loc;
 52:   }
 53:   PetscCall(PetscFree(parts));
 54:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)part), m, indices, PETSC_OWN_POINTER, partitioning));
 55:   PetscFunctionReturn(PETSC_SUCCESS);
 56: }

 58: static PetscErrorCode MatPartitioningApply_Square(MatPartitioning part, IS *partitioning)
 59: {
 60:   PetscInt    cell, n, N, p, rstart, rend, *color;
 61:   PetscMPIInt size;

 63:   PetscFunctionBegin;
 64:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)part), &size));
 65:   PetscCheck(part->n == size, PetscObjectComm((PetscObject)part), PETSC_ERR_SUP, "Currently only supports one domain per processor");
 66:   p = (PetscInt)PetscSqrtReal((PetscReal)part->n);
 67:   PetscCheck(p * p == part->n, PetscObjectComm((PetscObject)part), PETSC_ERR_SUP, "Square partitioning requires \"perfect square\" number of domains");

 69:   PetscCall(MatGetSize(part->adj, &N, NULL));
 70:   n = (PetscInt)PetscSqrtReal((PetscReal)N);
 71:   PetscCheck(n * n == N, PetscObjectComm((PetscObject)part), PETSC_ERR_SUP, "Square partitioning requires square domain");
 72:   PetscCheck(n % p == 0, PETSC_COMM_SELF, PETSC_ERR_SUP, "Square partitioning requires p to divide n");
 73:   PetscCall(MatGetOwnershipRange(part->adj, &rstart, &rend));
 74:   PetscCall(PetscMalloc1(rend - rstart, &color));
 75:   /* for (int cell=rstart; cell<rend; cell++) color[cell-rstart] = ((cell%n) < (n/2)) + 2 * ((cell/n) < (n/2)); */
 76:   for (cell = rstart; cell < rend; cell++) color[cell - rstart] = ((cell % n) / (n / p)) + p * ((cell / n) / (n / p));
 77:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)part), rend - rstart, color, PETSC_OWN_POINTER, partitioning));
 78:   PetscFunctionReturn(PETSC_SUCCESS);
 79: }

 81: PETSC_EXTERN PetscErrorCode MatPartitioningCreate_Current(MatPartitioning part)
 82: {
 83:   PetscFunctionBegin;
 84:   part->ops->apply = MatPartitioningApply_Current;
 85:   PetscFunctionReturn(PETSC_SUCCESS);
 86: }

 88: PETSC_EXTERN PetscErrorCode MatPartitioningCreate_Average(MatPartitioning part)
 89: {
 90:   PetscFunctionBegin;
 91:   part->ops->apply = MatPartitioningApply_Average;
 92:   PetscFunctionReturn(PETSC_SUCCESS);
 93: }

 95: PETSC_EXTERN PetscErrorCode MatPartitioningCreate_Square(MatPartitioning part)
 96: {
 97:   PetscFunctionBegin;
 98:   part->ops->apply = MatPartitioningApply_Square;
 99:   PetscFunctionReturn(PETSC_SUCCESS);
100: }

102: /* gets as input the "sizes" array computed by ParMETIS_*_NodeND and returns
103:        seps[  0 :         2*p) : the start and end node of each subdomain
104:        seps[2*p : 2*p+2*(p-1)) : the start and end node of each separator
105:      levels[  0 :         p-1) : level in the tree for each separator (-1 root, -2 and -3 first level and so on)
106:    The arrays must be large enough
107: */
108: PETSC_INTERN PetscErrorCode MatPartitioningSizesToSep_Private(PetscInt p, PetscInt sizes[], PetscInt seps[], PetscInt level[])
109: {
110:   PetscInt l2p, i, pTree, pStartTree;

112:   PetscFunctionBegin;
113:   l2p = PetscLog2Real(p);
114:   PetscCheck(!(l2p - (PetscInt)PetscLog2Real(p)), PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%" PetscInt_FMT " is not a power of 2", p);
115:   if (!p) PetscFunctionReturn(PETSC_SUCCESS);
116:   PetscCall(PetscArrayzero(seps, 2 * p - 2));
117:   PetscCall(PetscArrayzero(level, p - 1));
118:   seps[2 * p - 2] = sizes[2 * p - 2];
119:   pTree           = p;
120:   pStartTree      = 0;
121:   while (pTree != 1) {
122:     for (i = pStartTree; i < pStartTree + pTree; i++) {
123:       seps[i] += sizes[i];
124:       seps[pStartTree + pTree + (i - pStartTree) / 2] += seps[i];
125:     }
126:     pStartTree += pTree;
127:     pTree = pTree / 2;
128:   }
129:   seps[2 * p - 2] -= sizes[2 * p - 2];

131:   pStartTree = 2 * p - 2;
132:   pTree      = 1;
133:   while (pStartTree > 0) {
134:     for (i = pStartTree; i < pStartTree + pTree; i++) {
135:       PetscInt k = 2 * i - (pStartTree + 2 * pTree);
136:       PetscInt n = seps[k + 1];

138:       seps[k + 1]  = seps[i] - sizes[k + 1];
139:       seps[k]      = seps[k + 1] + sizes[k + 1] - n - sizes[k];
140:       level[i - p] = -pTree - i + pStartTree;
141:     }
142:     pTree *= 2;
143:     pStartTree -= pTree;
144:   }
145:   /* I know there should be a formula */
146:   PetscCall(PetscSortIntWithArrayPair(p - 1, seps + p, sizes + p, level));
147:   for (i = 2 * p - 2; i >= 0; i--) {
148:     seps[2 * i]     = seps[i];
149:     seps[2 * i + 1] = seps[i] + PetscMax(sizes[i] - 1, 0);
150:   }
151:   PetscFunctionReturn(PETSC_SUCCESS);
152: }

154: PetscFunctionList MatPartitioningList              = NULL;
155: PetscBool         MatPartitioningRegisterAllCalled = PETSC_FALSE;

157: PetscFunctionList MatMeshToCellGraphList              = NULL;
158: PetscBool         MatMeshToCellGraphRegisterAllCalled = PETSC_FALSE;

160: /*@
161:   MatPartitioningRegister - Adds a new sparse matrix partitioning to the  matrix package.

163:   Not Collective, No Fortran Support

165:   Input Parameters:
166: + sname    - name of partitioning (for example `MATPARTITIONINGCURRENT`) or `MATPARTITIONINGPARMETIS`
167: - function - function pointer that creates the partitioning type

169:   Level: developer

171:   Example Usage:
172: .vb
173:    MatPartitioningRegister("my_part", MyPartCreate);
174: .ve

176:   Then, your partitioner can be chosen with the procedural interface via `MatPartitioningSetType(part, "my_part")` or at runtime via the option
177:   `-mat_partitioning_type my_part`

179: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningType`, `MatPartitioningCreate()`, `MatPartitioningRegisterDestroy()`, `MatPartitioningRegisterAll()`
180: @*/
181: PetscErrorCode MatPartitioningRegister(const char sname[], PetscErrorCode (*function)(MatPartitioning))
182: {
183:   PetscFunctionBegin;
184:   PetscCall(MatInitializePackage());
185:   PetscCall(PetscFunctionListAdd(&MatPartitioningList, sname, function));
186:   PetscFunctionReturn(PETSC_SUCCESS);
187: }

189: /*@
190:   MatMeshToCellGraphRegister - Registers a mesh-to-cell-graph conversion routine.

192:   Not Collective, No Fortran Support

194:   Input Parameters:
195: + sname    - name of the converter (for example `MATMESHTOCELLGRAPHMETIS` or `MATMESHTOCELLGRAPHPARMETIS`)
196: - function - function pointer that performs the conversion

198:   Level: developer

200:   Example Usage:
201: .vb
202:    MatMeshToCellGraphRegister("metis", MatMeshToCellGraph_METIS);
203: .ve

205:   Then, the converter can be selected at runtime via the option `-mat_mesh_to_cell_graph_type metis`

207: .seealso: [](ch_matrices), `Mat`, `MatMeshToCellGraph()`, `MatMeshToCellGraphType`, `MatMeshToCellGraphRegisterAll()`
208: @*/
209: PetscErrorCode MatMeshToCellGraphRegister(const char sname[], PetscErrorCode (*function)(Mat, PetscInt, Mat *))
210: {
211:   PetscFunctionBegin;
212:   PetscCall(MatInitializePackage());
213:   PetscCall(PetscFunctionListAdd(&MatMeshToCellGraphList, sname, function));
214:   PetscFunctionReturn(PETSC_SUCCESS);
215: }

217: /*@
218:   MatMeshToCellGraph - Convert a mesh to a cell graph.

220:   Collective

222:   Input Parameters:
223: + mesh         - the graph that represents the coupling of the vertices of the mesh
224: - ncommonnodes - mesh elements that share this number of common nodes are considered neighbors, use 2 for triangles and
225:                  quadrilaterials, 3 for tetrahedrals and 4 for hexahedrals

227:   Output Parameter:
228: . dual - the dual graph

230:   Options Database Key:
231: . -mat_mesh_to_cell_graph_type (parmetis|metis) - the conversion package to use; default is ParMETIS if available, otherwise METIS

233:   Level: advanced

235:   Notes:
236:   Converts a `Mat` that represents coupling of vertices of a mesh to a `Mat` that represents the graph of the coupling
237:   between cells (the "dual" graph) and is suitable for partitioning with the `MatPartitioning` object. Use this to
238:   partition cells of a mesh.

240:   Each row of the mesh object represents a single cell in the mesh. For triangles it has 3 entries, quadrilaterials 4 entries,
241:   tetrahedrals 4 entries and hexahedrals 8 entries. You can mix triangles and quadrilaterals in the same mesh, but cannot
242:   mix tetrahedrals and hexahedrals.
243:   The columns of each row of the `Mat` mesh are the global vertex numbers of the vertices of that row's cell.
244:   The number of rows in mesh is number of cells, the number of columns is the number of vertices.

246: .seealso: `MatCreateMPIAdj()`, `MatPartitioningCreate()`, `MatMeshToCellGraphRegister()`
247: @*/
248: PetscErrorCode MatMeshToCellGraph(Mat mesh, PetscInt ncommonnodes, Mat *dual)
249: {
250:   char      type[256];
251:   PetscBool found;
252:   PetscErrorCode (*fn)(Mat, PetscInt, Mat *);
253:   MatMeshToCellGraphType def = NULL;

255:   PetscFunctionBegin;
256:   PetscCall(MatInitializePackage());
257:   if (PetscDefined(HAVE_PARMETIS)) def = MATMESHTOCELLGRAPHPARMETIS;
258:   else if (PetscDefined(HAVE_METIS)) def = MATMESHTOCELLGRAPHMETIS;
259:   PetscCall(PetscOptionsGetString(NULL, NULL, "-mat_mesh_to_cell_graph_type", type, sizeof(type), &found));
260:   if (!found) {
261:     PetscCheck(def, PetscObjectComm((PetscObject)mesh), PETSC_ERR_SUP, "No MatMeshToCellGraph implementations registered. Configure with METIS or ParMETIS");
262:     PetscCall(PetscStrncpy(type, def, sizeof(type)));
263:   }
264:   PetscCall(PetscFunctionListFind(MatMeshToCellGraphList, type, &fn));
265:   PetscCheck(fn, PetscObjectComm((PetscObject)mesh), PETSC_ERR_SUP, "MatMeshToCellGraph type \"%s\" is not available. Configure PETSc with the appropriate package (e.g., --download-metis or --download-parmetis)", type);
266:   PetscCall((*fn)(mesh, ncommonnodes, dual));
267:   PetscFunctionReturn(PETSC_SUCCESS);
268: }

270: /*@
271:   MatPartitioningGetType - Gets the Partitioning method type and name (as a string)
272:   from the partitioning context.

274:   Not Collective

276:   Input Parameter:
277: . partitioning - the partitioning context

279:   Output Parameter:
280: . type - partitioner type

282:   Level: intermediate

284: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningType`, `MatPartitioningCreate()`, `MatPartitioningRegisterDestroy()`, `MatPartitioningRegisterAll()`
285: @*/
286: PetscErrorCode MatPartitioningGetType(MatPartitioning partitioning, MatPartitioningType *type)
287: {
288:   PetscFunctionBegin;
290:   PetscAssertPointer(type, 2);
291:   *type = ((PetscObject)partitioning)->type_name;
292:   PetscFunctionReturn(PETSC_SUCCESS);
293: }

295: /*@
296:   MatPartitioningSetNParts - Set how many partitions need to be created;
297:   by default this is one per processor. Certain partitioning schemes may
298:   in fact only support that option.

300:   Collective

302:   Input Parameters:
303: + part - the partitioning context
304: - n    - the number of partitions

306:   Level: intermediate

308: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningCreate()`, `MatPartitioningApply()`
309: @*/
310: PetscErrorCode MatPartitioningSetNParts(MatPartitioning part, PetscInt n)
311: {
312:   PetscFunctionBegin;
313:   part->n = n;
314:   PetscFunctionReturn(PETSC_SUCCESS);
315: }

317: /*@
318:   MatPartitioningApplyND - Gets a nested dissection partitioning for a matrix.

320:   Collective

322:   Input Parameter:
323: . matp - the matrix partitioning object

325:   Output Parameter:
326: . partitioning - the partitioning. For each local node, a positive value indicates the processor
327:                    number the node has been assigned to. Negative x values indicate the separator level -(x+1).

329:   Level: intermediate

331:   Note:
332:   The user can define additional partitionings; see `MatPartitioningRegister()`.

334: .seealso: [](ch_matrices), `Mat`, `MatPartitioningRegister()`, `MatPartitioningCreate()`,
335:           `MatPartitioningDestroy()`, `MatPartitioningSetAdjacency()`, `ISPartitioningToNumbering()`,
336:           `ISPartitioningCount()`
337: @*/
338: PetscErrorCode MatPartitioningApplyND(MatPartitioning matp, IS *partitioning)
339: {
340:   PetscFunctionBegin;
342:   PetscAssertPointer(partitioning, 2);
343:   PetscCheck(matp->adj->assembled, PetscObjectComm((PetscObject)matp), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
344:   PetscCheck(!matp->adj->factortype, PetscObjectComm((PetscObject)matp), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
345:   PetscCall(PetscLogEventBegin(MAT_PartitioningND, matp, 0, 0, 0));
346:   PetscUseTypeMethod(matp, applynd, partitioning);
347:   PetscCall(PetscLogEventEnd(MAT_PartitioningND, matp, 0, 0, 0));

349:   PetscCall(MatPartitioningViewFromOptions(matp, NULL, "-mat_partitioning_view"));
350:   PetscCall(ISViewFromOptions(*partitioning, (PetscObject)matp, "-mat_partitioning_view"));
351:   PetscFunctionReturn(PETSC_SUCCESS);
352: }

354: /*@
355:   MatPartitioningApply - Gets a partitioning for the graph represented by a sparse matrix.

357:   Collective

359:   Input Parameter:
360: . matp - the matrix partitioning object

362:   Output Parameter:
363: . partitioning - the partitioning. For each local node this tells the MPI rank that that node is assigned to.

365:   Options Database Keys:
366: + -mat_partitioning_type (current|average|square|parmetis|chaco|party|ptscotch|hierarch) - set the partitioning package or algorithm to use, see `MatPartitioningType`
367: - -mat_partitioning_view                                                                 - display information about the partitioning object

369:   Level: beginner

371:    The user can define additional partitionings; see `MatPartitioningRegister()`.

373: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningType`, `MatPartitioningRegister()`, `MatPartitioningCreate()`,
374:           `MatPartitioningDestroy()`, `MatPartitioningSetAdjacency()`, `ISPartitioningToNumbering()`,
375:           `ISPartitioningCount()`
376: @*/
377: PetscErrorCode MatPartitioningApply(MatPartitioning matp, IS *partitioning)
378: {
379:   PetscBool viewbalance, improve;

381:   PetscFunctionBegin;
383:   PetscAssertPointer(partitioning, 2);
384:   PetscCheck(matp->adj->assembled, PetscObjectComm((PetscObject)matp), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
385:   PetscCheck(!matp->adj->factortype, PetscObjectComm((PetscObject)matp), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
386:   PetscCall(PetscLogEventBegin(MAT_Partitioning, matp, 0, 0, 0));
387:   PetscUseTypeMethod(matp, apply, partitioning);
388:   PetscCall(PetscLogEventEnd(MAT_Partitioning, matp, 0, 0, 0));

390:   PetscCall(MatPartitioningViewFromOptions(matp, NULL, "-mat_partitioning_view"));
391:   PetscCall(ISViewFromOptions(*partitioning, (PetscObject)matp, "-mat_partitioning_view"));

393:   PetscObjectOptionsBegin((PetscObject)matp);
394:   viewbalance = PETSC_FALSE;
395:   PetscCall(PetscOptionsBool("-mat_partitioning_view_imbalance", "Display imbalance information of a partition", NULL, PETSC_FALSE, &viewbalance, NULL));
396:   improve = PETSC_FALSE;
397:   PetscCall(PetscOptionsBool("-mat_partitioning_improve", "Improve the quality of a partition", NULL, PETSC_FALSE, &improve, NULL));
398:   PetscOptionsEnd();

400:   if (improve) PetscCall(MatPartitioningImprove(matp, partitioning));

402:   if (viewbalance) PetscCall(MatPartitioningViewImbalance(matp, *partitioning));
403:   PetscFunctionReturn(PETSC_SUCCESS);
404: }

406: /*@
407:   MatPartitioningImprove - Improves the quality of a given partition.

409:   Collective

411:   Input Parameters:
412: + matp         - the matrix partitioning object
413: - partitioning - the original partitioning. For each local node this tells the processor
414:                    number that that node is assigned to.

416:   Options Database Key:
417: . -mat_partitioning_improve (true|false) - improve the quality of the given partition

419:   Level: beginner

421: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningType`, `MatPartitioningApply()`, `MatPartitioningCreate()`,
422:           `MatPartitioningDestroy()`, `MatPartitioningSetAdjacency()`, `ISPartitioningToNumbering()`,
423:           `ISPartitioningCount()`
424: @*/
425: PetscErrorCode MatPartitioningImprove(MatPartitioning matp, IS *partitioning)
426: {
427:   PetscFunctionBegin;
429:   PetscAssertPointer(partitioning, 2);
430:   PetscCheck(matp->adj->assembled, PetscObjectComm((PetscObject)matp), PETSC_ERR_ARG_WRONGSTATE, "Not for unassembled matrix");
431:   PetscCheck(!matp->adj->factortype, PetscObjectComm((PetscObject)matp), PETSC_ERR_ARG_WRONGSTATE, "Not for factored matrix");
432:   PetscCall(PetscLogEventBegin(MAT_Partitioning, matp, 0, 0, 0));
433:   PetscTryTypeMethod(matp, improve, partitioning);
434:   PetscCall(PetscLogEventEnd(MAT_Partitioning, matp, 0, 0, 0));
435:   PetscFunctionReturn(PETSC_SUCCESS);
436: }

438: /*@
439:   MatPartitioningViewImbalance - Display partitioning imbalance information.

441:   Collective

443:   Input Parameters:
444: + matp         - the matrix partitioning object
445: - partitioning - the partitioning. For each local node this tells the MPI rank that that node is assigned to.

447:   Options Database Key:
448: . -mat_partitioning_view_imbalance (true|false) - view the balance information from the last partitioning

450:   Level: beginner

452: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningType`, `MatPartitioningApply()`, `MatPartitioningView()`
453: @*/
454: PetscErrorCode MatPartitioningViewImbalance(MatPartitioning matp, IS partitioning)
455: {
456:   PetscMPIInt     nparts;
457:   PetscInt       *subdomainsizes, nlocal, maxsub, minsub, avgsub;
458:   const PetscInt *indices;
459:   PetscViewer     viewer;

461:   PetscFunctionBegin;
464:   PetscCall(PetscMPIIntCast(matp->n, &nparts));
465:   PetscCall(PetscCalloc1(nparts, &subdomainsizes));
466:   PetscCall(ISGetLocalSize(partitioning, &nlocal));
467:   PetscCall(ISGetIndices(partitioning, &indices));
468:   for (PetscInt i = 0; i < nlocal; i++) subdomainsizes[indices[i]] += matp->vertex_weights ? matp->vertex_weights[i] : 1;
469:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, subdomainsizes, nparts, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)matp)));
470:   PetscCall(ISRestoreIndices(partitioning, &indices));
471:   minsub = PETSC_INT_MAX, maxsub = PETSC_INT_MIN, avgsub = 0;
472:   for (PetscMPIInt i = 0; i < nparts; i++) {
473:     minsub = PetscMin(minsub, subdomainsizes[i]);
474:     maxsub = PetscMax(maxsub, subdomainsizes[i]);
475:     avgsub += subdomainsizes[i];
476:   }
477:   avgsub /= nparts;
478:   PetscCall(PetscFree(subdomainsizes));
479:   PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)matp), &viewer));
480:   PetscCall(MatPartitioningView(matp, viewer));
481:   PetscCall(PetscViewerASCIIPrintf(viewer, "Partitioning Imbalance Info: Max %" PetscInt_FMT ", Min %" PetscInt_FMT ", Avg %" PetscInt_FMT ", R %g\n", maxsub, minsub, avgsub, (double)(maxsub / (PetscReal)minsub)));
482:   PetscFunctionReturn(PETSC_SUCCESS);
483: }

485: /*@
486:   MatPartitioningSetAdjacency - Sets the adjacency graph (matrix) of the thing to be
487:   partitioned.

489:   Collective

491:   Input Parameters:
492: + part - the partitioning context
493: - adj  - the adjacency matrix, this can be any `MatType` but the natural representation is `MATMPIADJ`

495:   Level: beginner

497: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningType`, `MatPartitioningCreate()`
498: @*/
499: PetscErrorCode MatPartitioningSetAdjacency(MatPartitioning part, Mat adj)
500: {
501:   PetscFunctionBegin;
504:   part->adj = adj;
505:   PetscFunctionReturn(PETSC_SUCCESS);
506: }

508: /*@
509:   MatPartitioningDestroy - Destroys the partitioning context.

511:   Collective

513:   Input Parameter:
514: . part - the partitioning context

516:   Level: beginner

518: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningType`, `MatPartitioningCreate()`
519: @*/
520: PetscErrorCode MatPartitioningDestroy(MatPartitioning *part)
521: {
522:   PetscFunctionBegin;
523:   if (!*part) PetscFunctionReturn(PETSC_SUCCESS);
525:   if (--((PetscObject)*part)->refct > 0) {
526:     *part = NULL;
527:     PetscFunctionReturn(PETSC_SUCCESS);
528:   }

530:   PetscTryTypeMethod(*part, destroy);
531:   PetscCall(PetscFree((*part)->vertex_weights));
532:   PetscCall(PetscFree((*part)->part_weights));
533:   PetscCall(PetscHeaderDestroy(part));
534:   PetscFunctionReturn(PETSC_SUCCESS);
535: }

537: /*@
538:   MatPartitioningSetVertexWeights - Sets the weights for vertices for a partitioning.

540:   Logically Collective

542:   Input Parameters:
543: + part    - the partitioning context
544: - weights - the weights, on each process this array must have the same size as the number of local rows times the value passed with `MatPartitioningSetNumberVertexWeights()` or
545:             1 if that is not provided

547:   Level: beginner

549:   Notes:
550:   The array weights is freed by PETSc so the user should not free the array. In C/C++
551:   the array must be obtained with a call to `PetscMalloc()`, not malloc().

553:   The weights may not be used by some partitioners

555:   Fortran Note:
556:   The array `weights` is copied during this function call.

558: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningCreate()`, `MatPartitioningSetType()`, `MatPartitioningSetPartitionWeights()`, `MatPartitioningSetNumberVertexWeights()`
559: @*/
560: PetscErrorCode MatPartitioningSetVertexWeights(MatPartitioning part, const PetscInt weights[])
561: {
562:   PetscFunctionBegin;
564:   PetscCall(PetscFree(part->vertex_weights));
565:   part->vertex_weights = (PetscInt *)weights;
566:   PetscFunctionReturn(PETSC_SUCCESS);
567: }

569: /*@
570:   MatPartitioningSetPartitionWeights - Sets the weights for each partition.

572:   Logically Collective

574:   Input Parameters:
575: + part    - the partitioning context
576: - weights - An array of size nparts that is used to specify the fraction of
577:             vertex weight that should be distributed to each sub-domain for
578:             the balance constraint. If all of the sub-domains are to be of
579:             the same size, then each of the nparts elements should be set
580:             to a value of 1/nparts. Note that the sum of all of the weights
581:             should be one.

583:   Level: beginner

585:   Note:
586:   The array weights is freed by PETSc so the user should not free the array. In C/C++
587:   the array must be obtained with a call to `PetscMalloc()`, not malloc().

589:   Fortran Note:
590:   The array `weights` is copied during this function call.

592: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningSetVertexWeights()`, `MatPartitioningCreate()`, `MatPartitioningSetType()`
593: @*/
594: PetscErrorCode MatPartitioningSetPartitionWeights(MatPartitioning part, const PetscReal weights[])
595: {
596:   PetscFunctionBegin;
598:   PetscCall(PetscFree(part->part_weights));
599:   part->part_weights = (PetscReal *)weights;
600:   PetscFunctionReturn(PETSC_SUCCESS);
601: }

603: /*@
604:   MatPartitioningSetUseEdgeWeights - Set a flag to indicate whether or not to use edge weights.

606:   Logically Collective

608:   Input Parameters:
609: + part             - the partitioning context
610: - use_edge_weights - the flag indicateing whether or not to use edge weights. By default no edge weights will be used,
611:                      that is, use_edge_weights is set to FALSE. If set use_edge_weights to TRUE, users need to make sure legal
612:                      edge weights are stored in an ADJ matrix.

614:   Options Database Key:
615: . -mat_partitioning_use_edge_weights (true|false) - use edge weights stored in the adjacency matrix

617:   Level: beginner

619: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningCreate()`, `MatPartitioningSetType()`, `MatPartitioningSetVertexWeights()`, `MatPartitioningSetPartitionWeights()`
620: @*/
621: PetscErrorCode MatPartitioningSetUseEdgeWeights(MatPartitioning part, PetscBool use_edge_weights)
622: {
623:   PetscFunctionBegin;
625:   part->use_edge_weights = use_edge_weights;
626:   PetscFunctionReturn(PETSC_SUCCESS);
627: }

629: /*@
630:   MatPartitioningGetUseEdgeWeights - Get a flag that indicates whether or not to edge weights are used.

632:   Logically Collective

634:   Input Parameter:
635: . part - the partitioning context

637:   Output Parameter:
638: . use_edge_weights - the flag indicateing whether or not to edge weights are used.

640:   Level: beginner

642: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningCreate()`, `MatPartitioningSetType()`, `MatPartitioningSetVertexWeights()`, `MatPartitioningSetPartitionWeights()`,
643:           `MatPartitioningSetUseEdgeWeights`
644: @*/
645: PetscErrorCode MatPartitioningGetUseEdgeWeights(MatPartitioning part, PetscBool *use_edge_weights)
646: {
647:   PetscFunctionBegin;
649:   PetscAssertPointer(use_edge_weights, 2);
650:   *use_edge_weights = part->use_edge_weights;
651:   PetscFunctionReturn(PETSC_SUCCESS);
652: }

654: /*@
655:   MatPartitioningCreate - Creates a partitioning context.

657:   Collective

659:   Input Parameter:
660: . comm - MPI communicator

662:   Output Parameter:
663: . newp - location to put the context

665:   Level: beginner

667: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningSetType()`, `MatPartitioningApply()`, `MatPartitioningDestroy()`,
668:           `MatPartitioningSetAdjacency()`
669: @*/
670: PetscErrorCode MatPartitioningCreate(MPI_Comm comm, MatPartitioning *newp)
671: {
672:   MatPartitioning part;
673:   PetscMPIInt     size;

675:   PetscFunctionBegin;
676:   PetscAssertPointer(newp, 2);
677:   PetscCall(MatInitializePackage());

679:   PetscCall(PetscHeaderCreate(part, MAT_PARTITIONING_CLASSID, "MatPartitioning", "Matrix/graph partitioning", "MatGraphOperations", comm, MatPartitioningDestroy, MatPartitioningView));
680:   part->vertex_weights   = NULL;
681:   part->part_weights     = NULL;
682:   part->use_edge_weights = PETSC_FALSE; /* By default we don't use edge weights */

684:   PetscCallMPI(MPI_Comm_size(comm, &size));
685:   part->n    = size;
686:   part->ncon = 1;

688:   *newp = part;
689:   PetscFunctionReturn(PETSC_SUCCESS);
690: }

692: /*@
693:   MatPartitioningViewFromOptions - View a partitioning context from the options database

695:   Collective

697:   Input Parameters:
698: + A    - the partitioning context
699: . obj  - optional object that provides the prefix used in the options database check, pass `NULL` to use the options prefix of `A`
700: - name - command line option

702:   Options Database Key:
703: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`

705:   Level: intermediate

707:   Note:
708:   This checks the options database, creates the viewer on-the-fly, uses it and then destroys it. Hence it should not be called in heavily used routines,
709:   rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.

711: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningView()`, `PetscObjectViewFromOptions()`, `MatPartitioningCreate()`, `PetscOptionsCreateViewer()`
712: @*/
713: PetscErrorCode MatPartitioningViewFromOptions(MatPartitioning A, PetscObject obj, const char name[])
714: {
715:   PetscFunctionBegin;
717:   PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
718:   PetscFunctionReturn(PETSC_SUCCESS);
719: }

721: /*@
722:   MatPartitioningView - Prints the partitioning data structure.

724:   Collective

726:   Input Parameters:
727: + part   - the partitioning context
728: - viewer - optional visualization context

730:   Level: intermediate

732:   Note:
733:   The available visualization contexts include
734: +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
735: -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
736:   output where only the first processor opens
737:   the file.  All other processors send their
738:   data to the first processor to print.

740:   The user can open alternative visualization contexts with
741: .     `PetscViewerASCIIOpen()` - output to a specified file

743: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `PetscViewer`, `PetscViewerASCIIOpen()`
744: @*/
745: PetscErrorCode MatPartitioningView(MatPartitioning part, PetscViewer viewer)
746: {
747:   PetscBool isascii;

749:   PetscFunctionBegin;
751:   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)part), &viewer));
753:   PetscCheckSameComm(part, 1, viewer, 2);

755:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
756:   if (isascii) {
757:     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)part, viewer));
758:     if (part->vertex_weights) PetscCall(PetscViewerASCIIPrintf(viewer, "  Using vertex weights\n"));
759:   }
760:   PetscCall(PetscViewerASCIIPushTab(viewer));
761:   PetscTryTypeMethod(part, view, viewer);
762:   PetscCall(PetscViewerASCIIPopTab(viewer));
763:   PetscFunctionReturn(PETSC_SUCCESS);
764: }

766: /*@
767:   MatPartitioningSetType - Sets the type of partitioner to use

769:   Collective

771:   Input Parameters:
772: + part - the partitioning context.
773: - type - a known method

775:   Options Database Key:
776: . -mat_partitioning_type (current|average|square|parmetis|chaco|party|ptscotch|hierarch) - see `MatPartitioningType`

778:   Level: intermediate

780: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningCreate()`, `MatPartitioningApply()`, `MatPartitioningType`
781: @*/
782: PetscErrorCode MatPartitioningSetType(MatPartitioning part, MatPartitioningType type)
783: {
784:   PetscBool match;
785:   PetscErrorCode (*r)(MatPartitioning);

787:   PetscFunctionBegin;
789:   PetscAssertPointer(type, 2);

791:   PetscCall(PetscObjectTypeCompare((PetscObject)part, type, &match));
792:   if (match) PetscFunctionReturn(PETSC_SUCCESS);

794:   PetscTryTypeMethod(part, destroy);

796:   part->data = NULL;
797:   PetscCall(PetscMemzero(part->ops, sizeof(struct _MatPartitioningOps)));

799:   PetscCall(PetscFunctionListFind(MatPartitioningList, type, &r));
800:   PetscCheck(r, PetscObjectComm((PetscObject)part), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown partitioning type %s", type);

802:   PetscCall((*r)(part));

804:   PetscCall(PetscFree(((PetscObject)part)->type_name));
805:   PetscCall(PetscStrallocpy(type, &((PetscObject)part)->type_name));
806:   PetscFunctionReturn(PETSC_SUCCESS);
807: }

809: /*@
810:   MatPartitioningSetFromOptions - Sets various partitioning options from the
811:   options database for the partitioning object

813:   Collective

815:   Input Parameter:
816: . part - the partitioning context.

818:   Options Database Keys:
819: + -mat_partitioning_type (current|average|square|parmetis|chaco|party|ptscotch|hierarch) - see `MatPartitioningType`
820: - -mat_partitioning_nparts                                                               - number of subgraphs

822:   Level: beginner

824:   Note:
825:   If the partitioner has not been set by the user it uses one of the installed partitioner such as ParMETIS. If there are
826:   no installed partitioners it does no repartioning.

828: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`
829: @*/
830: PetscErrorCode MatPartitioningSetFromOptions(MatPartitioning part)
831: {
832:   PetscBool   flag;
833:   char        type[256];
834:   const char *def;

836:   PetscFunctionBegin;
837:   PetscObjectOptionsBegin((PetscObject)part);
838:   if (!((PetscObject)part)->type_name) {
839: #if PetscDefined(HAVE_PARMETIS)
840:     def = MATPARTITIONINGPARMETIS;
841: #elif PetscDefined(HAVE_CHACO)
842:     def = MATPARTITIONINGCHACO;
843: #elif PetscDefined(HAVE_PARTY)
844:     def = MATPARTITIONINGPARTY;
845: #elif PetscDefined(HAVE_PTSCOTCH)
846:     def = MATPARTITIONINGPTSCOTCH;
847: #else
848:     def = MATPARTITIONINGCURRENT;
849: #endif
850:   } else {
851:     def = ((PetscObject)part)->type_name;
852:   }
853:   PetscCall(PetscOptionsFList("-mat_partitioning_type", "Type of partitioner", "MatPartitioningSetType", MatPartitioningList, def, type, sizeof(type), &flag));
854:   if (flag) PetscCall(MatPartitioningSetType(part, type));

856:   PetscCall(PetscOptionsInt("-mat_partitioning_nparts", "number of fine parts", NULL, part->n, &part->n, &flag));

858:   PetscCall(PetscOptionsBool("-mat_partitioning_use_edge_weights", "whether or not to use edge weights", NULL, part->use_edge_weights, &part->use_edge_weights, &flag));

860:   /*
861:     Set the type if it was never set.
862:   */
863:   if (!((PetscObject)part)->type_name) PetscCall(MatPartitioningSetType(part, def));

865:   PetscTryTypeMethod(part, setfromoptions, PetscOptionsObject);
866:   PetscOptionsEnd();
867:   PetscFunctionReturn(PETSC_SUCCESS);
868: }

870: /*@
871:   MatPartitioningSetNumberVertexWeights - Sets the number of weights per vertex

873:   Not Collective

875:   Input Parameters:
876: + partitioning - the partitioning context
877: - ncon         - the number of weights

879:   Level: intermediate

881: .seealso: [](ch_matrices), `Mat`, `MatPartitioning`, `MatPartitioningSetVertexWeights()`
882: @*/
883: PetscErrorCode MatPartitioningSetNumberVertexWeights(MatPartitioning partitioning, PetscInt ncon)
884: {
885:   PetscFunctionBegin;
887:   partitioning->ncon = ncon;
888:   PetscFunctionReturn(PETSC_SUCCESS);
889: }