Actual source code: sf.c
1: #include <petsc/private/sfimpl.h>
2: #include <petsc/private/hashseti.h>
3: #include <petsc/private/viewerimpl.h>
4: #include <petsc/private/hashmapi.h>
6: #if PetscDefined(HAVE_CUDA)
7: #include <petscdevice_cuda.h>
8: #endif
10: #if PetscDefined(HAVE_HIP)
11: #include <hip/hip_runtime.h>
12: #endif
14: #if PetscDefined(CLANG_STATIC_ANALYZER)
15: extern void PetscSFCheckGraphSet(PetscSF, int);
16: #else
17: #if PetscDefined(USE_DEBUG)
18: #define PetscSFCheckGraphSet(sf, arg) PetscCheck((sf)->graphset, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PetscSFSetGraph() or PetscSFSetGraphWithPattern() on argument %d \"%s\" before %s()", (arg), #sf, PETSC_FUNCTION_NAME)
19: #else
20: #define PetscSFCheckGraphSet(sf, arg) \
21: do { \
22: } while (0)
23: #endif
24: #endif
26: const char *const PetscSFDuplicateOptions[] = {"CONFONLY", "RANKS", "GRAPH", "PetscSFDuplicateOption", "PETSCSF_DUPLICATE_", NULL};
27: const char *const PetscSFConcatenateRootModes[] = {"local", "shared", "global", "PetscSFConcatenateRootMode", "PETSCSF_CONCATENATE_ROOTMODE_", NULL};
29: /*@
30: PetscSFCreate - create a star forest communication context
32: Collective
34: Input Parameter:
35: . comm - communicator on which the star forest will operate
37: Output Parameter:
38: . sf - new star forest context
40: Options Database Key:
41: + -sf_type (basic|window|neighbor) - Use MPI persistent Isend/Irecv, or MPI-3 one-sided window, or MPI-3 neighborhood collectives for communication
42: - -sf_neighbor_persistent (true|false) - Use MPI-4 persistent neighborhood collectives for communication (used along with `-sf_type neighbor`)
44: Level: intermediate
46: Note:
47: When one knows the communication graph is one of the predefined graph, such as `MPI_Alltoall()`, `MPI_Allgatherv()`,
48: `MPI_Gatherv()`, one can create a `PetscSF` and then set its graph with `PetscSFSetGraphWithPattern()`. These special
49: `PetscSF`s are optimized and have better performance than the general `PetscSF`s.
51: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFSetType`, `PetscSFSetGraph()`, `PetscSFSetGraphWithPattern()`, `PetscSFDestroy()`
52: @*/
53: PetscErrorCode PetscSFCreate(MPI_Comm comm, PetscSF *sf)
54: {
55: PetscSF b;
57: PetscFunctionBegin;
58: PetscAssertPointer(sf, 2);
59: PetscCall(PetscSFInitializePackage());
61: PetscCall(PetscHeaderCreate(b, PETSCSF_CLASSID, "PetscSF", "Star Forest", "PetscSF", comm, PetscSFDestroy, PetscSFView));
62: b->nroots = -1;
63: b->nleaves = -1;
64: b->minleaf = PETSC_INT_MAX;
65: b->maxleaf = PETSC_INT_MIN;
66: b->nranks = -1;
67: b->rankorder = PETSC_TRUE;
68: b->ingroup = MPI_GROUP_NULL;
69: b->outgroup = MPI_GROUP_NULL;
70: b->graphset = PETSC_FALSE;
71: #if PetscDefined(HAVE_DEVICE)
72: b->use_gpu_aware_mpi = use_gpu_aware_mpi;
73: b->use_stream_aware_mpi = PETSC_FALSE;
74: b->unknown_input_stream = PETSC_FALSE;
75: #if PetscDefined(HAVE_CUDA)
76: b->backend = PETSCSF_BACKEND_CUDA;
77: #elif PetscDefined(HAVE_HIP)
78: b->backend = PETSCSF_BACKEND_HIP;
79: #elif PetscDefined(HAVE_KOKKOS)
80: b->backend = PETSCSF_BACKEND_KOKKOS;
81: #endif
83: #if PetscDefined(HAVE_NVSHMEM)
84: b->use_nvshmem = PETSC_FALSE; /* Default is not to try NVSHMEM */
85: b->use_nvshmem_get = PETSC_FALSE; /* Default is to use nvshmem_put based protocol */
86: PetscCall(PetscOptionsGetBool(NULL, NULL, "-use_nvshmem", &b->use_nvshmem, NULL));
87: PetscCall(PetscOptionsGetBool(NULL, NULL, "-use_nvshmem_get", &b->use_nvshmem_get, NULL));
88: #endif
89: #endif
90: b->vscat.from_n = -1;
91: b->vscat.to_n = -1;
92: b->vscat.unit = MPIU_SCALAR;
93: *sf = b;
94: PetscFunctionReturn(PETSC_SUCCESS);
95: }
97: /*@
98: PetscSFReset - Reset a star forest so that different sizes or neighbors can be used
100: Collective
102: Input Parameter:
103: . sf - star forest
105: Level: advanced
107: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFCreate()`, `PetscSFSetGraph()`, `PetscSFDestroy()`
108: @*/
109: PetscErrorCode PetscSFReset(PetscSF sf)
110: {
111: PetscFunctionBegin;
113: PetscTryTypeMethod(sf, Reset);
114: PetscCall(PetscSFDestroy(&sf->rankssf));
116: sf->nroots = -1;
117: sf->nleaves = -1;
118: sf->minleaf = PETSC_INT_MAX;
119: sf->maxleaf = PETSC_INT_MIN;
120: sf->mine = NULL;
121: sf->remote = NULL;
122: sf->graphset = PETSC_FALSE;
123: PetscCall(PetscFree(sf->mine_alloc));
124: PetscCall(PetscFree(sf->remote_alloc));
125: sf->nranks = -1;
126: PetscCall(PetscFree4(sf->ranks, sf->roffset, sf->rmine, sf->rremote));
127: sf->degreeknown = PETSC_FALSE;
128: PetscCall(PetscFree(sf->degree));
129: if (sf->ingroup != MPI_GROUP_NULL) PetscCallMPI(MPI_Group_free(&sf->ingroup));
130: if (sf->outgroup != MPI_GROUP_NULL) PetscCallMPI(MPI_Group_free(&sf->outgroup));
132: if (sf->multi) sf->multi->multi = NULL;
133: PetscCall(PetscSFDestroy(&sf->multi));
135: PetscCall(PetscLayoutDestroy(&sf->map));
137: #if PetscDefined(HAVE_DEVICE)
138: for (PetscInt i = 0; i < 2; i++) PetscCall(PetscSFFree(sf, PETSC_MEMTYPE_DEVICE, sf->rmine_d[i]));
139: #endif
141: sf->setupcalled = PETSC_FALSE;
142: PetscFunctionReturn(PETSC_SUCCESS);
143: }
145: /*@
146: PetscSFSetType - Set the `PetscSF` communication implementation
148: Collective
150: Input Parameters:
151: + sf - the `PetscSF` context
152: - type - a known method
153: .vb
154: PETSCSFWINDOW - MPI-2/3 one-sided
155: PETSCSFBASIC - basic implementation using MPI-1 two-sided
156: .ve
158: Options Database Key:
159: . -sf_type (basic|window|neighbor) - Sets the method; see `PetscSFType`
161: Level: intermediate
163: Notes:
164: See `PetscSFType` for possible values
166: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFCreate()`
167: @*/
168: PetscErrorCode PetscSFSetType(PetscSF sf, PetscSFType type)
169: {
170: PetscBool match;
171: PetscErrorCode (*r)(PetscSF);
173: PetscFunctionBegin;
175: PetscAssertPointer(type, 2);
177: PetscCall(PetscObjectTypeCompare((PetscObject)sf, type, &match));
178: if (match) PetscFunctionReturn(PETSC_SUCCESS);
180: PetscCall(PetscFunctionListFind(PetscSFList, type, &r));
181: PetscCheck(r, PetscObjectComm((PetscObject)sf), PETSC_ERR_ARG_UNKNOWN_TYPE, "Unable to find requested PetscSF type %s", type);
182: /* Destroy the previous PetscSF implementation context */
183: PetscTryTypeMethod(sf, Destroy);
184: PetscCall(PetscMemzero(sf->ops, sizeof(*sf->ops)));
185: PetscCall(PetscObjectChangeTypeName((PetscObject)sf, type));
186: PetscCall((*r)(sf));
187: PetscFunctionReturn(PETSC_SUCCESS);
188: }
190: /*@
191: PetscSFGetType - Get the `PetscSF` communication implementation
193: Not Collective
195: Input Parameter:
196: . sf - the `PetscSF` context
198: Output Parameter:
199: . type - the `PetscSF` type name
201: Level: intermediate
203: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFSetType()`, `PetscSFCreate()`
204: @*/
205: PetscErrorCode PetscSFGetType(PetscSF sf, PetscSFType *type)
206: {
207: PetscFunctionBegin;
209: PetscAssertPointer(type, 2);
210: *type = ((PetscObject)sf)->type_name;
211: PetscFunctionReturn(PETSC_SUCCESS);
212: }
214: /*@
215: PetscSFDestroy - destroy a star forest
217: Collective
219: Input Parameter:
220: . sf - address of star forest
222: Level: intermediate
224: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFCreate()`, `PetscSFReset()`
225: @*/
226: PetscErrorCode PetscSFDestroy(PetscSF *sf)
227: {
228: PetscFunctionBegin;
229: if (!*sf) PetscFunctionReturn(PETSC_SUCCESS);
231: if (--((PetscObject)*sf)->refct > 0) {
232: *sf = NULL;
233: PetscFunctionReturn(PETSC_SUCCESS);
234: }
235: PetscCall(PetscSFReset(*sf));
236: PetscTryTypeMethod(*sf, Destroy);
237: PetscCall(PetscSFDestroy(&(*sf)->vscat.lsf));
238: if ((*sf)->vscat.bs > 1) PetscCallMPI(MPI_Type_free(&(*sf)->vscat.unit));
239: #if PetscDefined(HAVE_CUDA) && PetscDefined(HAVE_MPIX_STREAM)
240: if ((*sf)->use_stream_aware_mpi) {
241: PetscCallMPI(MPIX_Stream_free(&(*sf)->mpi_stream));
242: PetscCallMPI(MPI_Comm_free(&(*sf)->stream_comm));
243: }
244: #endif
245: PetscCall(PetscHeaderDestroy(sf));
246: PetscFunctionReturn(PETSC_SUCCESS);
247: }
249: static PetscErrorCode PetscSFCheckGraphValid_Private(PetscSF sf)
250: {
251: PetscInt nleaves;
252: PetscMPIInt size;
253: const PetscInt *ilocal;
254: const PetscSFNode *iremote;
256: PetscFunctionBegin;
257: if (!sf->graphset || !PetscDefined(USE_DEBUG)) PetscFunctionReturn(PETSC_SUCCESS);
258: PetscCall(PetscSFGetGraph(sf, NULL, &nleaves, &ilocal, &iremote));
259: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)sf), &size));
260: for (PetscInt i = 0; i < nleaves; i++) {
261: const PetscInt rank = iremote[i].rank;
262: const PetscInt remote = iremote[i].index;
263: const PetscInt leaf = ilocal ? ilocal[i] : i;
264: PetscCheck(rank >= 0 && rank < size, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Provided rank (%" PetscInt_FMT ") for remote %" PetscInt_FMT " is invalid, should be in [0, %d)", rank, i, size);
265: PetscCheck(remote >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Provided index (%" PetscInt_FMT ") for remote %" PetscInt_FMT " is invalid, should be >= 0", remote, i);
266: PetscCheck(leaf >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Provided location (%" PetscInt_FMT ") for leaf %" PetscInt_FMT " is invalid, should be >= 0", leaf, i);
267: }
268: PetscFunctionReturn(PETSC_SUCCESS);
269: }
271: /*@
272: PetscSFSetUp - set up communication structures for a `PetscSF`, after this is done it may be used to perform communication
274: Collective
276: Input Parameter:
277: . sf - star forest communication object
279: Level: beginner
281: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFSetFromOptions()`, `PetscSFSetType()`
282: @*/
283: PetscErrorCode PetscSFSetUp(PetscSF sf)
284: {
285: PetscFunctionBegin;
287: PetscSFCheckGraphSet(sf, 1);
288: if (sf->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
289: PetscCall(PetscLogEventBegin(PETSCSF_SetUp, sf, 0, 0, 0));
290: PetscCall(PetscSFCheckGraphValid_Private(sf));
291: if (!((PetscObject)sf)->type_name) PetscCall(PetscSFSetType(sf, PETSCSFBASIC)); /* Zero all sf->ops */
292: PetscTryTypeMethod(sf, SetUp);
293: #if PetscDefined(HAVE_CUDA)
294: if (sf->backend == PETSCSF_BACKEND_CUDA) {
295: sf->ops->Malloc = PetscSFMalloc_CUDA;
296: sf->ops->Free = PetscSFFree_CUDA;
297: }
298: #endif
299: #if PetscDefined(HAVE_HIP)
300: if (sf->backend == PETSCSF_BACKEND_HIP) {
301: sf->ops->Malloc = PetscSFMalloc_HIP;
302: sf->ops->Free = PetscSFFree_HIP;
303: }
304: #endif
306: #if PetscDefined(HAVE_KOKKOS)
307: if (sf->backend == PETSCSF_BACKEND_KOKKOS) {
308: sf->ops->Malloc = PetscSFMalloc_Kokkos;
309: sf->ops->Free = PetscSFFree_Kokkos;
310: }
311: #endif
312: PetscCall(PetscLogEventEnd(PETSCSF_SetUp, sf, 0, 0, 0));
313: sf->setupcalled = PETSC_TRUE;
314: PetscFunctionReturn(PETSC_SUCCESS);
315: }
317: /*@
318: PetscSFSetFromOptions - set `PetscSF` options using the options database
320: Logically Collective
322: Input Parameter:
323: . sf - star forest
325: Options Database Keys:
326: + -sf_type (basic|window|neighbor) - implementation type, see `PetscSFSetType()`
327: . -sf_rank_order (true|false) - sort composite points for gathers and scatters in MPI rank order, gathers are non-deterministic otherwise
328: . -sf_use_default_stream - Assume callers of `PetscSF` computed the input root/leafdata with the default CUDA stream. `PetscSF` will also
329: use the default stream to process data. Therefore, no stream synchronization is needed between `PetscSF` and its caller (default: true).
330: If true, this option only works with `-use_gpu_aware_mpi 1`.
331: . -sf_use_stream_aware_mpi - Assume the underlying MPI is aware of GPU streams and `PetscSF` won't sync streams for send/recv buffers passed to MPI (default: false).
332: If true, this option only works with `-use_gpu_aware_mpi 1`.
333: - -sf_backend (cuda|hip|kokkos) - Select the device backend `PetscSF` uses. On CUDA (HIP) devices, one can choose `cuda` (`hip`) or `kokkos` with the default being `cuda` (`hip`).
334: On other devices, the only available backend is `kokkos`.
336: Level: intermediate
338: Notes:
339: With `-sf_backend kokkos`, SF uses PETSc's shared Kokkos execution space. Changing the current
340: `PetscDeviceContext` does not change that execution space. Order input production and output consumption
341: with respect to the Kokkos execution space; synchronizing a different current context is insufficient.
343: MPIX stream support with `-sf_use_stream_aware_mpi` is incomplete and currently limited to CUDA.
344: The MPI communicator is bound to the CUDA stream selected during `PetscSFSetFromOptions()` and is not
345: rebound when the current context changes.
346: In addition, enabling this option does not reliably select the MPIX enqueue operations. Keep this option
347: disabled until stream-ordered MPI communication is supported consistently.
349: With `-use_nvshmem`, use `-sf_backend cuda` and keep a fixed CUDA context. The Kokkos/NVSHMEM path does not
350: bind its dependency events to the Kokkos execution stream. NVSHMEM also uses a separate communication stream;
351: synchronization of the SF device stream, including at barrier-context completion, only waits for communication
352: ordered onto that stream. It does not guarantee completion of all NVSHMEM communication.
354: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFCreate()`, `PetscSFSetType()`
355: @*/
356: PetscErrorCode PetscSFSetFromOptions(PetscSF sf)
357: {
358: PetscSFType deft;
359: char type[256];
360: PetscBool flg;
362: PetscFunctionBegin;
364: PetscObjectOptionsBegin((PetscObject)sf);
365: deft = ((PetscObject)sf)->type_name ? ((PetscObject)sf)->type_name : PETSCSFBASIC;
366: PetscCall(PetscOptionsFList("-sf_type", "PetscSF implementation type", "PetscSFSetType", PetscSFList, deft, type, sizeof(type), &flg));
367: PetscCall(PetscSFSetType(sf, flg ? type : deft));
368: PetscCall(PetscOptionsBool("-sf_rank_order", "sort composite points for gathers and scatters in rank order, gathers are non-deterministic otherwise", "PetscSFSetRankOrder", sf->rankorder, &sf->rankorder, NULL));
369: PetscCall(PetscOptionsBool("-sf_monitor", "monitor the MPI communication in sf", NULL, sf->monitor, &sf->monitor, NULL));
370: #if PetscDefined(HAVE_DEVICE)
371: {
372: char backendstr[32] = {0};
373: PetscBool isCuda = PETSC_FALSE, isHip = PETSC_FALSE, isKokkos = PETSC_FALSE, set;
374: /* Change the defaults set in PetscSFCreate() with command line options */
375: PetscCall(PetscOptionsBool("-sf_unknown_input_stream", "SF root/leafdata is computed on arbitrary streams unknown to SF", "PetscSFSetFromOptions", sf->unknown_input_stream, &sf->unknown_input_stream, NULL));
376: PetscCall(PetscOptionsBool("-sf_use_stream_aware_mpi", "Assume the underlying MPI is aware of GPU streams", "PetscSFSetFromOptions", sf->use_stream_aware_mpi, &sf->use_stream_aware_mpi, NULL));
377: PetscCall(PetscOptionsString("-sf_backend", "Select the device backend SF uses", "PetscSFSetFromOptions", NULL, backendstr, sizeof(backendstr), &set));
378: PetscCall(PetscStrcasecmp("cuda", backendstr, &isCuda));
379: PetscCall(PetscStrcasecmp("kokkos", backendstr, &isKokkos));
380: PetscCall(PetscStrcasecmp("hip", backendstr, &isHip));
381: #if PetscDefined(HAVE_CUDA) || PetscDefined(HAVE_HIP)
382: if (isCuda) sf->backend = PETSCSF_BACKEND_CUDA;
383: else if (isKokkos) sf->backend = PETSCSF_BACKEND_KOKKOS;
384: else if (isHip) sf->backend = PETSCSF_BACKEND_HIP;
385: else PetscCheck(!set, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "-sf_backend %s is not supported. You may choose cuda, hip or kokkos (if installed)", backendstr);
386: #elif PetscDefined(HAVE_KOKKOS)
387: PetscCheck(!set || isKokkos, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "-sf_backend %s is not supported. You can only choose kokkos", backendstr);
388: #endif
390: #if PetscDefined(HAVE_CUDA) && PetscDefined(HAVE_MPIX_STREAM)
391: if (sf->use_stream_aware_mpi) {
392: MPI_Info info;
393: PetscDeviceContext dctx;
394: cudaStream_t *stream;
396: PetscCall(PetscDeviceContextGetCurrentContextAssertType_Internal(&dctx, PETSC_DEVICE_CUDA));
397: PetscCall(PetscDeviceContextGetStreamHandle(dctx, (void **)&stream));
398: PetscCallMPI(MPI_Info_create(&info));
399: PetscCallMPI(MPI_Info_set(info, "type", "cudaStream_t"));
400: PetscCallMPI(MPIX_Info_set_hex(info, "value", stream, sizeof(*stream)));
401: PetscCallMPI(MPIX_Stream_create(info, &sf->mpi_stream));
402: PetscCallMPI(MPI_Info_free(&info));
403: PetscCallMPI(MPIX_Stream_comm_create(PetscObjectComm((PetscObject)sf), sf->mpi_stream, &sf->stream_comm));
404: }
405: #endif
406: }
407: #endif
408: PetscTryTypeMethod(sf, SetFromOptions, PetscOptionsObject);
409: PetscOptionsEnd();
410: PetscFunctionReturn(PETSC_SUCCESS);
411: }
413: /*@
414: PetscSFSetRankOrder - sort multi-points for gathers and scatters by MPI rank order
416: Logically Collective
418: Input Parameters:
419: + sf - star forest
420: - flg - `PETSC_TRUE` to sort, `PETSC_FALSE` to skip sorting (false has a lower setup cost, but is non-deterministic)
422: Level: advanced
424: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFGatherBegin()`, `PetscSFScatterBegin()`
425: @*/
426: PetscErrorCode PetscSFSetRankOrder(PetscSF sf, PetscBool flg)
427: {
428: PetscFunctionBegin;
431: PetscCheck(!sf->multi, PetscObjectComm((PetscObject)sf), PETSC_ERR_ARG_WRONGSTATE, "Rank ordering must be set before first call to PetscSFGatherBegin() or PetscSFScatterBegin()");
432: sf->rankorder = flg;
433: PetscFunctionReturn(PETSC_SUCCESS);
434: }
436: /*@
437: PetscSFSetGraph - Set a parallel star forest
439: Collective
441: Input Parameters:
442: + sf - star forest
443: . nroots - number of root vertices on the current MPI process (these are possible targets for other process to attach leaves)
444: . nleaves - number of leaf vertices on the current MPI process, each of these references a root on any process
445: . ilocal - locations of leaves in leafdata buffers (locations must be >= 0, enforced during setup in debug mode), pass `NULL` for contiguous storage (same as passing (0, 1, 2, ..., nleaves-1))
446: . localmode - copy mode for `ilocal`
447: . iremote - remote locations of root vertices for each leaf on the current process, length is `nleaves' (locations must be >= 0, enforced during setup in debug mode)
448: - remotemode - copy mode for `iremote`
450: Level: intermediate
452: Notes:
453: Leaf indices in `ilocal` must be unique, otherwise an error occurs.
455: Input arrays `ilocal` and `iremote` follow the `PetscCopyMode` semantics.
456: In particular, if `localmode` or `remotemode` is `PETSC_OWN_POINTER` or `PETSC_USE_POINTER`,
457: PETSc might modify the respective array;
458: if `PETSC_USE_POINTER`, the user must delete the array after `PetscSFDestroy()`.
459: If `PETSC_COPY_VALUES` is used, the respective array is guaranteed to stay intact and a const array can be passed (but a cast to non-const is needed).
461: `PetscSFSetGraphWithPattern()` is an alternative approach to provide certain communication patterns that have extra optimizations.
463: Fortran Notes:
464: In Fortran you must use `PETSC_COPY_VALUES` for `localmode` and `remotemode`.
466: Developer Notes:
467: We sort leaves to check for duplicates and contiguousness and to find minleaf/maxleaf.
468: This also allows to compare leaf sets of two `PetscSF`s easily.
470: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFCreate()`, `PetscSFView()`, `PetscSFGetGraph()`, `PetscSFSetGraphWithPattern()`
471: @*/
472: PetscErrorCode PetscSFSetGraph(PetscSF sf, PetscInt nroots, PetscInt nleaves, PetscInt ilocal[], PetscCopyMode localmode, PetscSFNode iremote[], PetscCopyMode remotemode)
473: {
474: PetscBool unique, contiguous;
476: PetscFunctionBegin;
478: if (nleaves > 0 && ilocal) PetscAssertPointer(ilocal, 4);
479: if (nleaves > 0) PetscAssertPointer(iremote, 6);
480: PetscCheck(nroots >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nroots %" PetscInt_FMT ", cannot be negative", nroots);
481: PetscCheck(nleaves >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "nleaves %" PetscInt_FMT ", cannot be negative", nleaves);
482: /* enums may be handled as unsigned by some compilers, NVHPC for example, the int cast
483: * below is to prevent NVHPC from warning about meaningless comparison of unsigned with zero */
484: PetscCheck((int)localmode >= PETSC_COPY_VALUES && localmode <= PETSC_USE_POINTER, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Wrong localmode %d", localmode);
485: PetscCheck((int)remotemode >= PETSC_COPY_VALUES && remotemode <= PETSC_USE_POINTER, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Wrong remotemode %d", remotemode);
487: if (sf->nroots >= 0) { /* Reset only if graph already set */
488: PetscCall(PetscSFReset(sf));
489: }
491: PetscCall(PetscLogEventBegin(PETSCSF_SetGraph, sf, 0, 0, 0));
492: if (PetscDefined(USE_DEBUG)) {
493: PetscMPIInt size;
495: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)sf), &size));
496: for (PetscInt i = 0; i < nleaves; i++) PetscCheck(iremote[i].rank >= -1 && iremote[i].rank < size, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "iremote contains incorrect rank values");
497: }
499: sf->nroots = nroots;
500: sf->nleaves = nleaves;
502: if (localmode == PETSC_COPY_VALUES && ilocal) {
503: PetscInt *tlocal = NULL;
505: PetscCall(PetscMalloc1(nleaves, &tlocal));
506: PetscCall(PetscArraycpy(tlocal, ilocal, nleaves));
507: ilocal = tlocal;
508: }
509: if (remotemode == PETSC_COPY_VALUES) {
510: PetscSFNode *tremote = NULL;
512: PetscCall(PetscMalloc1(nleaves, &tremote));
513: PetscCall(PetscArraycpy(tremote, iremote, nleaves));
514: iremote = tremote;
515: }
517: if (nleaves && ilocal) {
518: PetscSFNode work;
520: PetscCall(PetscSortIntWithDataArray(nleaves, ilocal, iremote, sizeof(PetscSFNode), &work));
521: PetscCall(PetscSortedCheckDupsInt(nleaves, ilocal, &unique));
522: unique = PetscNot(unique);
523: PetscCheck(sf->allow_multi_leaves || unique, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Input ilocal has duplicate entries which is not allowed for this PetscSF");
524: sf->minleaf = ilocal[0];
525: sf->maxleaf = ilocal[nleaves - 1];
526: contiguous = (PetscBool)(unique && ilocal[0] == 0 && ilocal[nleaves - 1] == nleaves - 1);
527: } else {
528: sf->minleaf = 0;
529: sf->maxleaf = nleaves - 1;
530: unique = PETSC_TRUE;
531: contiguous = PETSC_TRUE;
532: }
534: if (contiguous) {
535: if (localmode == PETSC_USE_POINTER) {
536: ilocal = NULL;
537: } else {
538: PetscCall(PetscFree(ilocal));
539: }
540: }
541: sf->mine = ilocal;
542: if (localmode == PETSC_USE_POINTER) {
543: sf->mine_alloc = NULL;
544: } else {
545: sf->mine_alloc = ilocal;
546: }
547: if (PetscDefined(USE_DEBUG)) {
548: PetscMPIInt size;
550: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)sf), &size));
551: for (PetscInt i = 0; i < nleaves; i++) PetscCheck(iremote[i].rank >= -1 && iremote[i].rank < size, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "iremote contains incorrect rank values");
552: }
553: sf->remote = iremote;
554: if (remotemode == PETSC_USE_POINTER) {
555: sf->remote_alloc = NULL;
556: } else {
557: sf->remote_alloc = iremote;
558: }
559: PetscCall(PetscLogEventEnd(PETSCSF_SetGraph, sf, 0, 0, 0));
560: sf->graphset = PETSC_TRUE;
561: PetscFunctionReturn(PETSC_SUCCESS);
562: }
564: /*@
565: PetscSFSetGraphWithPattern - Sets the graph of a `PetscSF` with a specific pattern
567: Collective
569: Input Parameters:
570: + sf - The `PetscSF`
571: . map - Layout of roots over all processes (not used when pattern is `PETSCSF_PATTERN_ALLTOALL`)
572: - pattern - One of `PETSCSF_PATTERN_ALLGATHER`, `PETSCSF_PATTERN_GATHER`, `PETSCSF_PATTERN_ALLTOALL`
574: Level: intermediate
576: Notes:
577: It is easier to explain `PetscSFPattern` using vectors. Suppose we have an MPI vector `root` and its `PetscLayout` is `map`.
578: `n` and `N` are the local and global sizes of `root` respectively.
580: With `PETSCSF_PATTERN_ALLGATHER`, the routine creates a graph that if one does `PetscSFBcastBegin()` and `PetscSFBcastEnd()` on it, it will copy `root` to
581: sequential vectors `leaves` on all MPI processes.
583: With `PETSCSF_PATTERN_GATHER`, the routine creates a graph that if one does `PetscSFBcastBegin()` and `PetscSFBcastEnd()` on it, it will copy `root` to a
584: sequential vector `leaves` on MPI rank 0.
586: With `PETSCSF_PATTERN_ALLTOALL`, map is not used. Suppose NP is the size of `sf`'s communicator. The routine
587: creates a graph where every MPI process has NP leaves and NP roots. On MPI rank i, its leaf j is connected to root i
588: of rank j. Here 0 <=i,j<NP. It is a kind of `MPI_Alltoall()` with sendcount/recvcount being 1. Note that it does
589: not mean one can not send multiple items. One needs to create a new MPI datatype for the multiple data
590: items with `MPI_Type_contiguous` and use that as the <unit> argument in the `PetscSF` routines. In this case, roots and leaves are symmetric.
592: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFCreate()`, `PetscSFView()`, `PetscSFGetGraph()`
593: @*/
594: PetscErrorCode PetscSFSetGraphWithPattern(PetscSF sf, PetscLayout map, PetscSFPattern pattern)
595: {
596: MPI_Comm comm;
597: PetscInt n, N, res[2];
598: PetscMPIInt rank, size;
599: PetscSFType type;
601: PetscFunctionBegin;
604: if (pattern != PETSCSF_PATTERN_ALLTOALL) PetscAssertPointer(map, 2);
605: PetscCall(PetscObjectGetComm((PetscObject)sf, &comm));
606: PetscCheck(pattern >= PETSCSF_PATTERN_ALLGATHER && pattern <= PETSCSF_PATTERN_ALLTOALL, comm, PETSC_ERR_ARG_OUTOFRANGE, "Unsupported PetscSFPattern %d", pattern);
607: PetscCallMPI(MPI_Comm_rank(comm, &rank));
608: PetscCallMPI(MPI_Comm_size(comm, &size));
610: if (pattern == PETSCSF_PATTERN_ALLTOALL) {
611: PetscInt sizei = size;
613: type = PETSCSFALLTOALL;
614: PetscCall(PetscLayoutCreate(comm, &sf->map));
615: PetscCall(PetscLayoutSetLocalSize(sf->map, size));
616: PetscCall(PetscLayoutSetSize(sf->map, PetscSqr(sizei)));
617: PetscCall(PetscLayoutSetUp(sf->map));
618: } else {
619: PetscCall(PetscLayoutGetLocalSize(map, &n));
620: PetscCall(PetscLayoutGetSize(map, &N));
621: res[0] = n;
622: res[1] = -n;
623: /* Check if n are same over all ranks so that we can optimize it */
624: PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, res, 2, MPIU_INT, MPI_MAX, comm));
625: if (res[0] == -res[1]) { /* same n */
626: type = (pattern == PETSCSF_PATTERN_ALLGATHER) ? PETSCSFALLGATHER : PETSCSFGATHER;
627: } else {
628: type = (pattern == PETSCSF_PATTERN_ALLGATHER) ? PETSCSFALLGATHERV : PETSCSFGATHERV;
629: }
630: PetscCall(PetscLayoutReference(map, &sf->map));
631: }
632: PetscCall(PetscSFSetType(sf, type));
634: sf->pattern = pattern;
635: sf->mine = NULL; /* Contiguous */
637: /* Set nleaves, nroots here in case user calls PetscSFGetGraph, which is legal to call even before PetscSFSetUp is called.
638: Also set other easy stuff.
639: */
640: if (pattern == PETSCSF_PATTERN_ALLGATHER) {
641: sf->nleaves = N;
642: sf->nroots = n;
643: sf->nranks = size;
644: sf->minleaf = 0;
645: sf->maxleaf = N - 1;
646: } else if (pattern == PETSCSF_PATTERN_GATHER) {
647: sf->nleaves = rank ? 0 : N;
648: sf->nroots = n;
649: sf->nranks = rank ? 0 : size;
650: sf->minleaf = 0;
651: sf->maxleaf = rank ? -1 : N - 1;
652: } else if (pattern == PETSCSF_PATTERN_ALLTOALL) {
653: sf->nleaves = size;
654: sf->nroots = size;
655: sf->nranks = size;
656: sf->minleaf = 0;
657: sf->maxleaf = size - 1;
658: }
659: sf->ndranks = 0; /* We do not need to separate out distinguished ranks for patterned graphs to improve communication performance */
660: sf->graphset = PETSC_TRUE;
661: PetscFunctionReturn(PETSC_SUCCESS);
662: }
664: /*@
665: PetscSFCreateInverseSF - given a `PetscSF` in which all roots have degree 1 (exactly one leaf), creates the inverse map
667: Collective
669: Input Parameter:
670: . sf - star forest to invert
672: Output Parameter:
673: . isf - inverse of `sf`
675: Level: advanced
677: Notes:
678: All roots must have degree 1.
680: The local space may be a permutation, but cannot be sparse.
682: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFSetGraph()`
683: @*/
684: PetscErrorCode PetscSFCreateInverseSF(PetscSF sf, PetscSF *isf)
685: {
686: PetscMPIInt rank;
687: PetscInt i, nroots, nleaves, maxlocal, count, *newilocal;
688: const PetscInt *ilocal;
689: PetscSFNode *roots, *leaves;
691: PetscFunctionBegin;
693: PetscSFCheckGraphSet(sf, 1);
694: PetscAssertPointer(isf, 2);
696: PetscCall(PetscSFGetGraph(sf, &nroots, &nleaves, &ilocal, NULL));
697: maxlocal = sf->maxleaf + 1; /* TODO: We should use PetscSFGetLeafRange() */
699: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)sf), &rank));
700: PetscCall(PetscMalloc2(nroots, &roots, maxlocal, &leaves));
701: for (i = 0; i < maxlocal; i++) {
702: leaves[i].rank = rank;
703: leaves[i].index = i;
704: }
705: for (i = 0; i < nroots; i++) {
706: roots[i].rank = -1;
707: roots[i].index = -1;
708: }
709: PetscCall(PetscSFReduceBegin(sf, MPIU_SF_NODE, leaves, roots, MPI_REPLACE));
710: PetscCall(PetscSFReduceEnd(sf, MPIU_SF_NODE, leaves, roots, MPI_REPLACE));
712: /* Check whether our leaves are sparse */
713: for (i = 0, count = 0; i < nroots; i++)
714: if (roots[i].rank >= 0) count++;
715: if (count == nroots) newilocal = NULL;
716: else { // Index for sparse leaves and compact "roots" array (which is to become our leaves).
717: PetscCall(PetscMalloc1(count, &newilocal));
718: for (i = 0, count = 0; i < nroots; i++) {
719: if (roots[i].rank >= 0) {
720: newilocal[count] = i;
721: roots[count].rank = roots[i].rank;
722: roots[count].index = roots[i].index;
723: count++;
724: }
725: }
726: }
728: PetscCall(PetscSFDuplicate(sf, PETSCSF_DUPLICATE_CONFONLY, isf));
729: PetscCall(PetscSFSetGraph(*isf, maxlocal, count, newilocal, PETSC_OWN_POINTER, roots, PETSC_COPY_VALUES));
730: PetscCall(PetscFree2(roots, leaves));
731: PetscFunctionReturn(PETSC_SUCCESS);
732: }
734: /*@
735: PetscSFDuplicate - duplicate a `PetscSF`, optionally preserving rank connectivity and graph
737: Collective
739: Input Parameters:
740: + sf - communication object to duplicate
741: - opt - `PETSCSF_DUPLICATE_CONFONLY`, `PETSCSF_DUPLICATE_RANKS`, or `PETSCSF_DUPLICATE_GRAPH` (see `PetscSFDuplicateOption`)
743: Output Parameter:
744: . newsf - new communication object
746: Level: beginner
748: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFCreate()`, `PetscSFSetType()`, `PetscSFSetGraph()`
749: @*/
750: PetscErrorCode PetscSFDuplicate(PetscSF sf, PetscSFDuplicateOption opt, PetscSF *newsf)
751: {
752: PetscSFType type;
753: MPI_Datatype dtype = MPIU_SCALAR;
755: PetscFunctionBegin;
758: PetscAssertPointer(newsf, 3);
759: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)sf), newsf));
760: PetscCall(PetscSFGetType(sf, &type));
761: if (type) PetscCall(PetscSFSetType(*newsf, type));
762: (*newsf)->allow_multi_leaves = sf->allow_multi_leaves; /* Dup this flag earlier since PetscSFSetGraph() below checks on this flag */
763: if (opt == PETSCSF_DUPLICATE_GRAPH) {
764: PetscSFCheckGraphSet(sf, 1);
765: if (sf->pattern == PETSCSF_PATTERN_GENERAL) {
766: PetscInt nroots, nleaves;
767: const PetscInt *ilocal;
768: const PetscSFNode *iremote;
769: PetscCall(PetscSFGetGraph(sf, &nroots, &nleaves, &ilocal, &iremote));
770: PetscCall(PetscSFSetGraph(*newsf, nroots, nleaves, (PetscInt *)ilocal, PETSC_COPY_VALUES, (PetscSFNode *)iremote, PETSC_COPY_VALUES));
771: } else {
772: PetscCall(PetscSFSetGraphWithPattern(*newsf, sf->map, sf->pattern));
773: }
774: }
775: /* Since oldtype is committed, so is newtype, according to MPI */
776: if (sf->vscat.bs > 1) PetscCallMPI(MPI_Type_dup(sf->vscat.unit, &dtype));
777: (*newsf)->vscat.bs = sf->vscat.bs;
778: (*newsf)->vscat.unit = dtype;
779: (*newsf)->vscat.to_n = sf->vscat.to_n;
780: (*newsf)->vscat.from_n = sf->vscat.from_n;
781: /* Do not copy lsf. Build it on demand since it is rarely used */
783: #if PetscDefined(HAVE_DEVICE)
784: (*newsf)->backend = sf->backend;
785: (*newsf)->unknown_input_stream = sf->unknown_input_stream;
786: (*newsf)->use_gpu_aware_mpi = sf->use_gpu_aware_mpi;
787: (*newsf)->use_stream_aware_mpi = sf->use_stream_aware_mpi;
788: #endif
789: PetscTryTypeMethod(sf, Duplicate, opt, *newsf);
790: /* Don't do PetscSFSetUp() since the new sf's graph might have not been set. */
791: PetscFunctionReturn(PETSC_SUCCESS);
792: }
794: /*@
795: PetscSFGetGraph - Get the graph specifying a parallel star forest
797: Not Collective
799: Input Parameter:
800: . sf - star forest
802: Output Parameters:
803: + nroots - number of root vertices on the current process (these are possible targets for other MPI process to attach leaves)
804: . nleaves - number of leaf vertices on the current process, each of these references a root on any MPI process
805: . ilocal - locations of leaves in leafdata buffers (if returned value is `NULL`, it means leaves are in contiguous storage)
806: - iremote - remote locations of root vertices for each leaf on the current process
808: Level: intermediate
810: Notes:
811: We are not currently requiring that the graph is set, thus returning `nroots` = -1 if it has not been set yet
813: The returned `ilocal` and `iremote` might contain values in different order than the input ones in `PetscSFSetGraph()`
815: Fortran Note:
816: Use `PetscSFRestoreGraph()` when access to the arrays is no longer needed
818: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFCreate()`, `PetscSFView()`, `PetscSFSetGraph()`
819: @*/
820: PetscErrorCode PetscSFGetGraph(PetscSF sf, PetscInt *nroots, PetscInt *nleaves, const PetscInt *ilocal[], const PetscSFNode *iremote[])
821: {
822: PetscFunctionBegin;
824: if (sf->ops->GetGraph) {
825: PetscCall(sf->ops->GetGraph(sf, nroots, nleaves, ilocal, iremote));
826: } else {
827: if (nroots) *nroots = sf->nroots;
828: if (nleaves) *nleaves = sf->nleaves;
829: if (ilocal) *ilocal = sf->mine;
830: if (iremote) *iremote = sf->remote;
831: }
832: PetscFunctionReturn(PETSC_SUCCESS);
833: }
835: /*@
836: PetscSFGetLeafRange - Get the active leaf ranges
838: Not Collective
840: Input Parameter:
841: . sf - star forest
843: Output Parameters:
844: + minleaf - minimum active leaf on this MPI process. Returns 0 if there are no leaves.
845: - maxleaf - maximum active leaf on this MPI process. Returns -1 if there are no leaves.
847: Level: developer
849: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFType`, `PetscSFCreate()`, `PetscSFView()`, `PetscSFSetGraph()`, `PetscSFGetGraph()`
850: @*/
851: PetscErrorCode PetscSFGetLeafRange(PetscSF sf, PetscInt *minleaf, PetscInt *maxleaf)
852: {
853: PetscFunctionBegin;
855: PetscSFCheckGraphSet(sf, 1);
856: if (minleaf) *minleaf = sf->minleaf;
857: if (maxleaf) *maxleaf = sf->maxleaf;
858: PetscFunctionReturn(PETSC_SUCCESS);
859: }
861: /*@
862: PetscSFViewFromOptions - View a `PetscSF` based on arguments in the options database
864: Collective
866: Input Parameters:
867: + A - the star forest
868: . obj - optional object that provides the prefix for the option names, pass `NULL` to use the options prefix of `A`
869: - name - command line option
871: Options Database Key:
872: . -name viewer_specification - See `PetscOptionsCreateViewer()` for the values of `viewer_specification`
874: Level: intermediate
876: Note:
877: 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,
878: rather `PetscOptionsCreateViewer()` should be used to construct the viewer once which can then be utilized in the heavily used routine.
880: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFView()`, `PetscObjectViewFromOptions()`, `PetscSFCreate()`, `PetscOptionsCreateViewer()`
881: @*/
882: PetscErrorCode PetscSFViewFromOptions(PetscSF A, PetscObject obj, const char name[])
883: {
884: PetscFunctionBegin;
886: PetscCall(PetscObjectViewFromOptions((PetscObject)A, obj, name));
887: PetscFunctionReturn(PETSC_SUCCESS);
888: }
890: /*@
891: PetscSFView - view a star forest
893: Collective
895: Input Parameters:
896: + sf - star forest
897: - viewer - viewer to display graph, for example `PETSC_VIEWER_STDOUT_WORLD`
899: Level: beginner
901: .seealso: [](sec_petscsf), `PetscSF`, `PetscViewer`, `PetscSFCreate()`, `PetscSFSetGraph()`
902: @*/
903: PetscErrorCode PetscSFView(PetscSF sf, PetscViewer viewer)
904: {
905: PetscBool isascii;
906: PetscViewerFormat format;
908: PetscFunctionBegin;
910: if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)sf), &viewer));
912: PetscCheckSameComm(sf, 1, viewer, 2);
913: if (sf->graphset) PetscCall(PetscSFSetUp(sf));
914: PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
915: if (isascii && viewer->format != PETSC_VIEWER_ASCII_MATLAB) {
916: PetscMPIInt rank;
918: PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)sf, viewer));
919: PetscCall(PetscViewerASCIIPushTab(viewer));
920: if (sf->pattern == PETSCSF_PATTERN_GENERAL) {
921: if (!sf->graphset) {
922: PetscCall(PetscViewerASCIIPrintf(viewer, "PetscSFSetGraph() has not been called yet\n"));
923: PetscCall(PetscViewerASCIIPopTab(viewer));
924: PetscFunctionReturn(PETSC_SUCCESS);
925: }
926: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)sf), &rank));
927: PetscCall(PetscViewerASCIIPushSynchronized(viewer));
928: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Number of roots=%" PetscInt_FMT ", leaves=%" PetscInt_FMT ", remote ranks=%d\n", rank, sf->nroots, sf->nleaves, sf->nranks));
929: for (PetscInt i = 0; i < sf->nleaves; i++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %" PetscInt_FMT " <- (%" PetscInt_FMT ",%" PetscInt_FMT ")\n", rank, sf->mine ? sf->mine[i] : i, sf->remote[i].rank, sf->remote[i].index));
930: PetscCall(PetscViewerFlush(viewer));
931: PetscCall(PetscViewerGetFormat(viewer, &format));
932: if (format == PETSC_VIEWER_ASCII_INFO_DETAIL) {
933: PetscMPIInt *tmpranks, *perm;
935: PetscCall(PetscMalloc2(sf->nranks, &tmpranks, sf->nranks, &perm));
936: PetscCall(PetscArraycpy(tmpranks, sf->ranks, sf->nranks));
937: for (PetscMPIInt i = 0; i < sf->nranks; i++) perm[i] = i;
938: PetscCall(PetscSortMPIIntWithArray(sf->nranks, tmpranks, perm));
939: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Roots referenced by my leaves, by rank\n", rank));
940: for (PetscMPIInt ii = 0; ii < sf->nranks; ii++) {
941: PetscMPIInt i = perm[ii];
943: PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %d: %" PetscInt_FMT " edges\n", rank, sf->ranks[i], sf->roffset[i + 1] - sf->roffset[i]));
944: for (PetscInt j = sf->roffset[i]; j < sf->roffset[i + 1]; j++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %" PetscInt_FMT " <- %" PetscInt_FMT "\n", rank, sf->rmine[j], sf->rremote[j]));
945: }
946: PetscCall(PetscFree2(tmpranks, perm));
947: }
948: PetscCall(PetscViewerFlush(viewer));
949: PetscCall(PetscViewerASCIIPopSynchronized(viewer));
950: }
951: PetscCall(PetscViewerASCIIPopTab(viewer));
952: }
953: PetscTryTypeMethod(sf, View, viewer);
954: PetscFunctionReturn(PETSC_SUCCESS);
955: }
957: /*@
958: PetscSFGetRootRanks - Get the root MPI ranks and number of vertices referenced by leaves on this process
960: Not Collective
962: Input Parameter:
963: . sf - star forest
965: Output Parameters:
966: + nranks - number of MPI processes referenced by local part
967: . ranks - [`nranks`] array of MPI ranks
968: . roffset - [`nranks`+1] offset in `rmine` and `rremote` for each MPI process
969: . rmine - [`roffset`[`nranks`]] concatenated array holding local indices referencing each remote MPI process, or `NULL`
970: - rremote - [`roffset`[`nranks`]] concatenated array holding remote indices referenced for each remote MPI process, or `NULL`
972: Level: developer
974: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFGetLeafRanks()`
975: @*/
976: PetscErrorCode PetscSFGetRootRanks(PetscSF sf, PetscMPIInt *nranks, const PetscMPIInt *ranks[], const PetscInt *roffset[], const PetscInt *rmine[], const PetscInt *rremote[])
977: {
978: PetscFunctionBegin;
980: PetscCheck(sf->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PetscSFSetUp() before obtaining ranks");
981: if (sf->ops->GetRootRanks) {
982: PetscUseTypeMethod(sf, GetRootRanks, nranks, ranks, roffset, rmine, rremote);
983: } else {
984: /* The generic implementation */
985: if (nranks) *nranks = sf->nranks;
986: if (ranks) *ranks = sf->ranks;
987: if (roffset) *roffset = sf->roffset;
988: if (rmine) *rmine = sf->rmine;
989: if (rremote) *rremote = sf->rremote;
990: }
991: PetscFunctionReturn(PETSC_SUCCESS);
992: }
994: /*@
995: PetscSFGetLeafRanks - Get leaf MPI ranks referencing roots on this process
997: Not Collective
999: Input Parameter:
1000: . sf - star forest
1002: Output Parameters:
1003: + niranks - number of leaf MPI processes referencing roots on this process
1004: . iranks - [`niranks`] array of MPI ranks
1005: . ioffset - [`niranks`+1] offset in `irootloc` for each MPI process
1006: - irootloc - [`ioffset`[`niranks`]] concatenated array holding local indices of roots referenced by each leaf MPI process
1008: Level: developer
1010: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFGetRootRanks()`
1011: @*/
1012: PetscErrorCode PetscSFGetLeafRanks(PetscSF sf, PetscMPIInt *niranks, const PetscMPIInt *iranks[], const PetscInt *ioffset[], const PetscInt *irootloc[])
1013: {
1014: PetscFunctionBegin;
1016: PetscCheck(sf->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PetscSFSetUp() before obtaining ranks");
1017: if (sf->ops->GetLeafRanks) {
1018: PetscUseTypeMethod(sf, GetLeafRanks, niranks, iranks, ioffset, irootloc);
1019: } else {
1020: PetscSFType type;
1021: PetscCall(PetscSFGetType(sf, &type));
1022: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "PetscSFGetLeafRanks() is not supported on this StarForest type: %s", type);
1023: }
1024: PetscFunctionReturn(PETSC_SUCCESS);
1025: }
1027: static PetscBool InList(PetscMPIInt needle, PetscMPIInt n, const PetscMPIInt *list)
1028: {
1029: PetscInt i;
1030: for (i = 0; i < n; i++) {
1031: if (needle == list[i]) return PETSC_TRUE;
1032: }
1033: return PETSC_FALSE;
1034: }
1036: /*@
1037: PetscSFSetUpRanks - Set up data structures associated with MPI ranks; this is for internal use by `PetscSF` implementations.
1039: Collective
1041: Input Parameters:
1042: + sf - `PetscSF` to set up; `PetscSFSetGraph()` must have been called
1043: - dgroup - `MPI_Group` of ranks to be distinguished (e.g., for self or shared memory exchange)
1045: Level: developer
1047: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFGetRootRanks()`
1048: @*/
1049: PetscErrorCode PetscSFSetUpRanks(PetscSF sf, MPI_Group dgroup)
1050: {
1051: PetscHMapI table;
1052: PetscHashIter pos;
1053: PetscMPIInt size, groupsize, *groupranks, *ranks;
1054: PetscInt *rcount;
1055: PetscInt irank, sfnrank, ranksi;
1056: PetscMPIInt i, orank = -1;
1058: PetscFunctionBegin;
1060: PetscSFCheckGraphSet(sf, 1);
1061: PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)sf), &size));
1062: PetscCall(PetscHMapICreateWithSize(10, &table));
1063: for (i = 0; i < sf->nleaves; i++) {
1064: /* Log 1-based rank */
1065: PetscCall(PetscHMapISetWithMode(table, sf->remote[i].rank + 1, 1, ADD_VALUES));
1066: }
1067: PetscCall(PetscHMapIGetSize(table, &sfnrank));
1068: PetscCall(PetscMPIIntCast(sfnrank, &sf->nranks));
1069: PetscCall(PetscMalloc4(sf->nranks, &sf->ranks, sf->nranks + 1, &sf->roffset, sf->nleaves, &sf->rmine, sf->nleaves, &sf->rremote));
1070: PetscCall(PetscMalloc2(sf->nranks, &rcount, sf->nranks, &ranks));
1071: PetscHashIterBegin(table, pos);
1072: for (i = 0; i < sf->nranks; i++) {
1073: PetscHashIterGetKey(table, pos, ranksi);
1074: PetscCall(PetscMPIIntCast(ranksi, &ranks[i]));
1075: PetscHashIterGetVal(table, pos, rcount[i]);
1076: PetscHashIterNext(table, pos);
1077: ranks[i]--; /* Convert back to 0-based */
1078: }
1079: PetscCall(PetscHMapIDestroy(&table));
1081: /* We expect that dgroup is reliably "small" while nranks could be large */
1082: {
1083: MPI_Group group = MPI_GROUP_NULL;
1084: PetscMPIInt *dgroupranks;
1086: PetscCallMPI(MPI_Comm_group(PetscObjectComm((PetscObject)sf), &group));
1087: PetscCallMPI(MPI_Group_size(dgroup, &groupsize));
1088: PetscCall(PetscMalloc1(groupsize, &dgroupranks));
1089: PetscCall(PetscMalloc1(groupsize, &groupranks));
1090: for (i = 0; i < groupsize; i++) dgroupranks[i] = i;
1091: if (groupsize) PetscCallMPI(MPI_Group_translate_ranks(dgroup, groupsize, dgroupranks, group, groupranks));
1092: PetscCallMPI(MPI_Group_free(&group));
1093: PetscCall(PetscFree(dgroupranks));
1094: }
1096: /* Partition ranks[] into distinguished (first sf->ndranks) followed by non-distinguished */
1097: for (sf->ndranks = 0, i = sf->nranks; sf->ndranks < i;) {
1098: for (i--; sf->ndranks < i; i--) { /* Scan i backward looking for distinguished rank */
1099: if (InList(ranks[i], groupsize, groupranks)) break;
1100: }
1101: for (; sf->ndranks <= i; sf->ndranks++) { /* Scan sf->ndranks forward looking for non-distinguished rank */
1102: if (!InList(ranks[sf->ndranks], groupsize, groupranks)) break;
1103: }
1104: if (sf->ndranks < i) { /* Swap ranks[sf->ndranks] with ranks[i] */
1105: PetscMPIInt tmprank;
1106: PetscInt tmpcount;
1108: tmprank = ranks[i];
1109: tmpcount = rcount[i];
1110: ranks[i] = ranks[sf->ndranks];
1111: rcount[i] = rcount[sf->ndranks];
1112: ranks[sf->ndranks] = tmprank;
1113: rcount[sf->ndranks] = tmpcount;
1114: sf->ndranks++;
1115: }
1116: }
1117: PetscCall(PetscFree(groupranks));
1118: PetscCall(PetscSortMPIIntWithIntArray(sf->ndranks, ranks, rcount));
1119: if (rcount) PetscCall(PetscSortMPIIntWithIntArray(sf->nranks - sf->ndranks, ranks + sf->ndranks, rcount + sf->ndranks));
1120: sf->roffset[0] = 0;
1121: for (i = 0; i < sf->nranks; i++) {
1122: PetscCall(PetscMPIIntCast(ranks[i], sf->ranks + i));
1123: sf->roffset[i + 1] = sf->roffset[i] + rcount[i];
1124: rcount[i] = 0;
1125: }
1126: for (i = 0, irank = -1, orank = -1; i < sf->nleaves; i++) {
1127: /* short circuit */
1128: if (orank != sf->remote[i].rank) {
1129: /* Search for index of iremote[i].rank in sf->ranks */
1130: PetscCall(PetscMPIIntCast(sf->remote[i].rank, &orank));
1131: PetscCall(PetscFindMPIInt(orank, sf->ndranks, sf->ranks, &irank));
1132: if (irank < 0) {
1133: PetscCall(PetscFindMPIInt(orank, sf->nranks - sf->ndranks, sf->ranks + sf->ndranks, &irank));
1134: if (irank >= 0) irank += sf->ndranks;
1135: }
1136: }
1137: PetscCheck(irank >= 0, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Could not find rank %d in array", orank);
1138: sf->rmine[sf->roffset[irank] + rcount[irank]] = sf->mine ? sf->mine[i] : i;
1139: sf->rremote[sf->roffset[irank] + rcount[irank]] = sf->remote[i].index;
1140: rcount[irank]++;
1141: }
1142: PetscCall(PetscFree2(rcount, ranks));
1143: PetscFunctionReturn(PETSC_SUCCESS);
1144: }
1146: /*@
1147: PetscSFGetGroups - gets incoming and outgoing process groups
1149: Collective
1151: Input Parameter:
1152: . sf - star forest
1154: Output Parameters:
1155: + incoming - group of origin processes for incoming edges (leaves that reference my roots)
1156: - outgoing - group of destination processes for outgoing edges (roots that I reference)
1158: Level: developer
1160: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFGetWindow()`, `PetscSFRestoreWindow()`
1161: @*/
1162: PetscErrorCode PetscSFGetGroups(PetscSF sf, MPI_Group *incoming, MPI_Group *outgoing)
1163: {
1164: MPI_Group group = MPI_GROUP_NULL;
1166: PetscFunctionBegin;
1168: PetscCheck(sf->nranks >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PetscSFSetUpRanks() before obtaining groups");
1169: if (sf->ingroup == MPI_GROUP_NULL) {
1170: PetscInt i;
1171: const PetscInt *indegree;
1172: PetscMPIInt rank, *outranks, *inranks, indegree0;
1173: PetscSFNode *remote;
1174: PetscSF bgcount;
1176: /* Compute the number of incoming ranks */
1177: PetscCall(PetscMalloc1(sf->nranks, &remote));
1178: for (i = 0; i < sf->nranks; i++) {
1179: remote[i].rank = sf->ranks[i];
1180: remote[i].index = 0;
1181: }
1182: PetscCall(PetscSFDuplicate(sf, PETSCSF_DUPLICATE_CONFONLY, &bgcount));
1183: PetscCall(PetscSFSetGraph(bgcount, 1, sf->nranks, NULL, PETSC_COPY_VALUES, remote, PETSC_OWN_POINTER));
1184: PetscCall(PetscSFComputeDegreeBegin(bgcount, &indegree));
1185: PetscCall(PetscSFComputeDegreeEnd(bgcount, &indegree));
1186: /* Enumerate the incoming ranks */
1187: PetscCall(PetscMalloc2(indegree[0], &inranks, sf->nranks, &outranks));
1188: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)sf), &rank));
1189: for (i = 0; i < sf->nranks; i++) outranks[i] = rank;
1190: PetscCall(PetscSFGatherBegin(bgcount, MPI_INT, outranks, inranks));
1191: PetscCall(PetscSFGatherEnd(bgcount, MPI_INT, outranks, inranks));
1192: PetscCallMPI(MPI_Comm_group(PetscObjectComm((PetscObject)sf), &group));
1193: PetscCall(PetscMPIIntCast(indegree[0], &indegree0));
1194: PetscCallMPI(MPI_Group_incl(group, indegree0, inranks, &sf->ingroup));
1195: PetscCallMPI(MPI_Group_free(&group));
1196: PetscCall(PetscFree2(inranks, outranks));
1197: PetscCall(PetscSFDestroy(&bgcount));
1198: }
1199: *incoming = sf->ingroup;
1201: if (sf->outgroup == MPI_GROUP_NULL) {
1202: PetscCallMPI(MPI_Comm_group(PetscObjectComm((PetscObject)sf), &group));
1203: PetscCallMPI(MPI_Group_incl(group, sf->nranks, sf->ranks, &sf->outgroup));
1204: PetscCallMPI(MPI_Group_free(&group));
1205: }
1206: *outgoing = sf->outgroup;
1207: PetscFunctionReturn(PETSC_SUCCESS);
1208: }
1210: /*@
1211: PetscSFGetRanksSF - gets the `PetscSF` to perform communications with root ranks
1213: Collective
1215: Input Parameter:
1216: . sf - star forest
1218: Output Parameter:
1219: . rsf - the star forest with a single root per MPI process to perform communications
1221: Level: developer
1223: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFSetGraph()`, `PetscSFGetRootRanks()`
1224: @*/
1225: PetscErrorCode PetscSFGetRanksSF(PetscSF sf, PetscSF *rsf)
1226: {
1227: PetscFunctionBegin;
1229: PetscAssertPointer(rsf, 2);
1230: if (!sf->rankssf) {
1231: PetscSFNode *rremotes;
1232: const PetscMPIInt *ranks;
1233: PetscMPIInt nranks;
1235: PetscCall(PetscSFGetRootRanks(sf, &nranks, &ranks, NULL, NULL, NULL));
1236: PetscCall(PetscMalloc1(nranks, &rremotes));
1237: for (PetscInt i = 0; i < nranks; i++) {
1238: rremotes[i].rank = ranks[i];
1239: rremotes[i].index = 0;
1240: }
1241: PetscCall(PetscSFDuplicate(sf, PETSCSF_DUPLICATE_CONFONLY, &sf->rankssf));
1242: /* The ranks graph need not retain the collective pattern of the original graph */
1243: if (sf->pattern != PETSCSF_PATTERN_GENERAL) PetscCall(PetscSFSetType(sf->rankssf, PETSCSFBASIC));
1244: PetscCall(PetscSFSetGraph(sf->rankssf, 1, nranks, NULL, PETSC_OWN_POINTER, rremotes, PETSC_OWN_POINTER));
1245: }
1246: *rsf = sf->rankssf;
1247: PetscFunctionReturn(PETSC_SUCCESS);
1248: }
1250: /*@
1251: PetscSFGetMultiSF - gets the inner `PetscSF` implementing gathers and scatters
1253: Collective
1255: Input Parameter:
1256: . sf - star forest that may contain roots with 0 or with more than 1 vertex
1258: Output Parameter:
1259: . multi - star forest with split roots, such that each root has degree exactly 1 (has one leaf)
1261: Level: developer
1263: Note:
1264: In most cases, users should use `PetscSFGatherBegin()` and `PetscSFScatterBegin()` instead of manipulating multi
1265: directly. Since multi satisfies the stronger condition that each entry in the global space has exactly one incoming
1266: edge, it is a candidate for future optimization that might involve its removal.
1268: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFSetGraph()`, `PetscSFGatherBegin()`, `PetscSFScatterBegin()`, `PetscSFComputeMultiRootOriginalNumbering()`
1269: @*/
1270: PetscErrorCode PetscSFGetMultiSF(PetscSF sf, PetscSF *multi)
1271: {
1272: PetscFunctionBegin;
1274: PetscAssertPointer(multi, 2);
1275: if (sf->nroots < 0) { /* Graph has not been set yet; why do we need this? */
1276: PetscCall(PetscSFDuplicate(sf, PETSCSF_DUPLICATE_RANKS, &sf->multi));
1277: *multi = sf->multi;
1278: sf->multi->multi = sf->multi;
1279: PetscFunctionReturn(PETSC_SUCCESS);
1280: }
1281: if (!sf->multi) {
1282: const PetscInt *indegree;
1283: PetscInt i, *inoffset, *outones, *outoffset, maxlocal;
1284: PetscSFNode *remote;
1285: maxlocal = sf->maxleaf + 1; /* TODO: We should use PetscSFGetLeafRange() */
1286: PetscCall(PetscSFComputeDegreeBegin(sf, &indegree));
1287: PetscCall(PetscSFComputeDegreeEnd(sf, &indegree));
1288: PetscCall(PetscMalloc3(sf->nroots + 1, &inoffset, maxlocal, &outones, maxlocal, &outoffset));
1289: inoffset[0] = 0;
1290: for (i = 0; i < sf->nroots; i++) inoffset[i + 1] = inoffset[i] + indegree[i];
1291: for (i = 0; i < maxlocal; i++) outones[i] = 1;
1292: PetscCall(PetscSFFetchAndOpBegin(sf, MPIU_INT, inoffset, outones, outoffset, MPI_SUM));
1293: PetscCall(PetscSFFetchAndOpEnd(sf, MPIU_INT, inoffset, outones, outoffset, MPI_SUM));
1294: for (i = 0; i < sf->nroots; i++) inoffset[i] -= indegree[i]; /* Undo the increment */
1295: if (PetscDefined(USE_DEBUG)) { /* Check that the expected number of increments occurred */
1296: for (i = 0; i < sf->nroots; i++) PetscCheck(inoffset[i] + indegree[i] == inoffset[i + 1], PETSC_COMM_SELF, PETSC_ERR_PLIB, "Incorrect result after PetscSFFetchAndOp");
1297: }
1298: PetscCall(PetscMalloc1(sf->nleaves, &remote));
1299: for (i = 0; i < sf->nleaves; i++) {
1300: remote[i].rank = sf->remote[i].rank;
1301: remote[i].index = outoffset[sf->mine ? sf->mine[i] : i];
1302: }
1303: PetscCall(PetscSFDuplicate(sf, PETSCSF_DUPLICATE_RANKS, &sf->multi));
1304: sf->multi->multi = sf->multi;
1305: PetscCall(PetscSFSetGraph(sf->multi, inoffset[sf->nroots], sf->nleaves, sf->mine, PETSC_COPY_VALUES, remote, PETSC_OWN_POINTER));
1306: if (sf->rankorder) { /* Sort the ranks */
1307: PetscMPIInt rank;
1308: PetscInt *inranks, *newoffset, *outranks, *newoutoffset, *tmpoffset, maxdegree;
1309: PetscSFNode *newremote;
1310: PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)sf), &rank));
1311: for (i = 0, maxdegree = 0; i < sf->nroots; i++) maxdegree = PetscMax(maxdegree, indegree[i]);
1312: PetscCall(PetscMalloc5(sf->multi->nroots, &inranks, sf->multi->nroots, &newoffset, maxlocal, &outranks, maxlocal, &newoutoffset, maxdegree, &tmpoffset));
1313: for (i = 0; i < maxlocal; i++) outranks[i] = rank;
1314: PetscCall(PetscSFReduceBegin(sf->multi, MPIU_INT, outranks, inranks, MPI_REPLACE));
1315: PetscCall(PetscSFReduceEnd(sf->multi, MPIU_INT, outranks, inranks, MPI_REPLACE));
1316: /* Sort the incoming ranks at each vertex, build the inverse map */
1317: for (i = 0; i < sf->nroots; i++) {
1318: for (PetscInt j = 0; j < indegree[i]; j++) tmpoffset[j] = j;
1319: PetscCall(PetscSortIntWithArray(indegree[i], PetscSafePointerPlusOffset(inranks, inoffset[i]), tmpoffset));
1320: for (PetscInt j = 0; j < indegree[i]; j++) newoffset[inoffset[i] + tmpoffset[j]] = inoffset[i] + j;
1321: }
1322: PetscCall(PetscSFBcastBegin(sf->multi, MPIU_INT, newoffset, newoutoffset, MPI_REPLACE));
1323: PetscCall(PetscSFBcastEnd(sf->multi, MPIU_INT, newoffset, newoutoffset, MPI_REPLACE));
1324: PetscCall(PetscMalloc1(sf->nleaves, &newremote));
1325: for (i = 0; i < sf->nleaves; i++) {
1326: newremote[i].rank = sf->remote[i].rank;
1327: newremote[i].index = newoutoffset[sf->mine ? sf->mine[i] : i];
1328: }
1329: PetscCall(PetscSFSetGraph(sf->multi, inoffset[sf->nroots], sf->nleaves, sf->mine, PETSC_COPY_VALUES, newremote, PETSC_OWN_POINTER));
1330: PetscCall(PetscFree5(inranks, newoffset, outranks, newoutoffset, tmpoffset));
1331: }
1332: PetscCall(PetscFree3(inoffset, outones, outoffset));
1333: }
1334: *multi = sf->multi;
1335: PetscFunctionReturn(PETSC_SUCCESS);
1336: }
1338: /*@
1339: PetscSFCreateEmbeddedRootSF - removes edges from all but the selected roots of a `PetscSF`, does not remap indices
1341: Collective
1343: Input Parameters:
1344: + sf - original star forest
1345: . nselected - number of selected roots on this MPI process
1346: - selected - indices of the selected roots on this MPI process
1348: Output Parameter:
1349: . esf - new star forest
1351: Level: advanced
1353: Note:
1354: To use the new `PetscSF`, it may be necessary to know the indices of the leaves that are still participating. This can
1355: be done by calling PetscSFGetGraph().
1357: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFSetGraph()`, `PetscSFGetGraph()`
1358: @*/
1359: PetscErrorCode PetscSFCreateEmbeddedRootSF(PetscSF sf, PetscInt nselected, const PetscInt selected[], PetscSF *esf)
1360: {
1361: PetscInt i, j, n, nroots, nleaves, esf_nleaves, *new_ilocal, minleaf, maxleaf, maxlocal;
1362: const PetscInt *ilocal;
1363: signed char *rootdata, *leafdata, *leafmem;
1364: const PetscSFNode *iremote;
1365: PetscSFNode *new_iremote;
1366: MPI_Comm comm;
1368: PetscFunctionBegin;
1370: PetscSFCheckGraphSet(sf, 1);
1371: if (nselected) PetscAssertPointer(selected, 3);
1372: PetscAssertPointer(esf, 4);
1374: PetscCall(PetscSFSetUp(sf));
1375: PetscCall(PetscLogEventBegin(PETSCSF_EmbedSF, sf, 0, 0, 0));
1376: PetscCall(PetscObjectGetComm((PetscObject)sf, &comm));
1377: PetscCall(PetscSFGetGraph(sf, &nroots, &nleaves, &ilocal, &iremote));
1379: if (PetscDefined(USE_DEBUG)) { /* Error out if selected[] has dups or out of range indices */
1380: PetscBool dups;
1381: PetscCall(PetscCheckDupsInt(nselected, selected, &dups));
1382: PetscCheck(!dups, comm, PETSC_ERR_ARG_WRONG, "selected[] has dups");
1383: for (i = 0; i < nselected; i++) PetscCheck(selected[i] >= 0 && selected[i] < nroots, comm, PETSC_ERR_ARG_OUTOFRANGE, "selected root index %" PetscInt_FMT " is out of [0,%" PetscInt_FMT ")", selected[i], nroots);
1384: }
1386: if (sf->ops->CreateEmbeddedRootSF) PetscUseTypeMethod(sf, CreateEmbeddedRootSF, nselected, selected, esf);
1387: else {
1388: /* A generic version of creating embedded sf */
1389: PetscCall(PetscSFGetLeafRange(sf, &minleaf, &maxleaf));
1390: maxlocal = maxleaf - minleaf + 1;
1391: PetscCall(PetscCalloc2(nroots, &rootdata, maxlocal, &leafmem));
1392: leafdata = PetscSafePointerPlusOffset(leafmem, -minleaf);
1393: /* Tag selected roots and bcast to leaves */
1394: for (i = 0; i < nselected; i++) rootdata[selected[i]] = 1;
1395: PetscCall(PetscSFBcastBegin(sf, MPI_SIGNED_CHAR, rootdata, leafdata, MPI_REPLACE));
1396: PetscCall(PetscSFBcastEnd(sf, MPI_SIGNED_CHAR, rootdata, leafdata, MPI_REPLACE));
1398: /* Build esf with leaves that are still connected */
1399: esf_nleaves = 0;
1400: for (i = 0; i < nleaves; i++) {
1401: j = ilocal ? ilocal[i] : i;
1402: /* esf_nleaves += leafdata[j] should work in theory, but failed with SFWindow bugs
1403: with PetscSFBcast. See https://gitlab.com/petsc/petsc/issues/555
1404: */
1405: esf_nleaves += (leafdata[j] ? 1 : 0);
1406: }
1407: PetscCall(PetscMalloc1(esf_nleaves, &new_ilocal));
1408: PetscCall(PetscMalloc1(esf_nleaves, &new_iremote));
1409: for (i = n = 0; i < nleaves; i++) {
1410: j = ilocal ? ilocal[i] : i;
1411: if (leafdata[j]) {
1412: new_ilocal[n] = j;
1413: new_iremote[n].rank = iremote[i].rank;
1414: new_iremote[n].index = iremote[i].index;
1415: ++n;
1416: }
1417: }
1418: PetscCall(PetscSFCreate(comm, esf));
1419: PetscCall(PetscSFSetFromOptions(*esf));
1420: PetscCall(PetscSFSetGraph(*esf, nroots, esf_nleaves, new_ilocal, PETSC_OWN_POINTER, new_iremote, PETSC_OWN_POINTER));
1421: PetscCall(PetscFree2(rootdata, leafmem));
1422: }
1423: PetscCall(PetscLogEventEnd(PETSCSF_EmbedSF, sf, 0, 0, 0));
1424: PetscFunctionReturn(PETSC_SUCCESS);
1425: }
1427: /*@
1428: PetscSFCreateEmbeddedLeafSF - removes edges from all but the selected leaves of a `PetscSF`, does not remap indices
1430: Collective
1432: Input Parameters:
1433: + sf - original star forest
1434: . nselected - number of selected leaves on this MPI process
1435: - selected - indices of the selected leaves on this MPI process
1437: Output Parameter:
1438: . newsf - new star forest
1440: Level: advanced
1442: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFCreateEmbeddedRootSF()`, `PetscSFSetGraph()`, `PetscSFGetGraph()`
1443: @*/
1444: PetscErrorCode PetscSFCreateEmbeddedLeafSF(PetscSF sf, PetscInt nselected, const PetscInt selected[], PetscSF *newsf)
1445: {
1446: const PetscSFNode *iremote;
1447: PetscSFNode *new_iremote;
1448: const PetscInt *ilocal;
1449: PetscInt i, nroots, *leaves, *new_ilocal;
1450: MPI_Comm comm;
1452: PetscFunctionBegin;
1454: PetscSFCheckGraphSet(sf, 1);
1455: if (nselected) PetscAssertPointer(selected, 3);
1456: PetscAssertPointer(newsf, 4);
1458: /* Uniq selected[] and put results in leaves[] */
1459: PetscCall(PetscObjectGetComm((PetscObject)sf, &comm));
1460: PetscCall(PetscMalloc1(nselected, &leaves));
1461: PetscCall(PetscArraycpy(leaves, selected, nselected));
1462: PetscCall(PetscSortedRemoveDupsInt(&nselected, leaves));
1463: PetscCheck(!nselected || !(leaves[0] < 0 || leaves[nselected - 1] >= sf->nleaves), comm, PETSC_ERR_ARG_OUTOFRANGE, "Min/Max leaf indices %" PetscInt_FMT "/%" PetscInt_FMT " are not in [0,%" PetscInt_FMT ")", leaves[0], leaves[nselected - 1], sf->nleaves);
1465: /* Optimize the routine only when sf is setup and hence we can reuse sf's communication pattern */
1466: if (sf->setupcalled && sf->ops->CreateEmbeddedLeafSF) PetscUseTypeMethod(sf, CreateEmbeddedLeafSF, nselected, leaves, newsf);
1467: else {
1468: PetscCall(PetscSFGetGraph(sf, &nroots, NULL, &ilocal, &iremote));
1469: PetscCall(PetscMalloc1(nselected, &new_ilocal));
1470: PetscCall(PetscMalloc1(nselected, &new_iremote));
1471: for (i = 0; i < nselected; ++i) {
1472: const PetscInt l = leaves[i];
1473: new_ilocal[i] = ilocal ? ilocal[l] : l;
1474: new_iremote[i].rank = iremote[l].rank;
1475: new_iremote[i].index = iremote[l].index;
1476: }
1477: PetscCall(PetscSFDuplicate(sf, PETSCSF_DUPLICATE_CONFONLY, newsf));
1478: PetscCall(PetscSFSetGraph(*newsf, nroots, nselected, new_ilocal, PETSC_OWN_POINTER, new_iremote, PETSC_OWN_POINTER));
1479: }
1480: PetscCall(PetscFree(leaves));
1481: PetscFunctionReturn(PETSC_SUCCESS);
1482: }
1484: /*@
1485: PetscSFBcastBegin - begin pointwise broadcast with root value being reduced to leaf value, to be concluded with call to `PetscSFBcastEnd()`
1487: Collective
1489: Input Parameters:
1490: + sf - star forest on which to communicate
1491: . unit - data type associated with each node
1492: . rootdata - buffer to broadcast
1493: - op - operation to use for reduction
1495: Output Parameter:
1496: . leafdata - buffer to be reduced with values from each leaf's respective root
1498: Level: intermediate
1500: Note:
1501: When PETSc is configured with device support, it will use `PetscGetMemType()` to determine whether the given data pointers
1502: are host pointers or device pointers, which may incur a noticeable cost. If you already knew the memory type, you should
1503: use `PetscSFBcastWithMemTypeBegin()` instead.
1505: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFBcastEnd()`, `PetscSFBcastWithMemTypeBegin()`
1506: @*/
1507: PetscErrorCode PetscSFBcastBegin(PetscSF sf, MPI_Datatype unit, const void *rootdata, void *leafdata, MPI_Op op)
1508: {
1509: PetscMemType rootmtype, leafmtype;
1511: PetscFunctionBegin;
1513: PetscCall(PetscSFSetUp(sf));
1514: if (!sf->vscat.logging) PetscCall(PetscLogEventBegin(PETSCSF_BcastBegin, sf, 0, 0, 0));
1515: PetscCall(PetscGetMemType(rootdata, &rootmtype));
1516: PetscCall(PetscGetMemType(leafdata, &leafmtype));
1517: PetscUseTypeMethod(sf, BcastBegin, unit, rootmtype, rootdata, leafmtype, leafdata, op);
1518: if (!sf->vscat.logging) PetscCall(PetscLogEventEnd(PETSCSF_BcastBegin, sf, 0, 0, 0));
1519: PetscFunctionReturn(PETSC_SUCCESS);
1520: }
1522: /*@
1523: PetscSFBcastWithMemTypeBegin - begin pointwise broadcast with root value being reduced to leaf value with explicit memory types, to be concluded with call
1524: to `PetscSFBcastEnd()`
1526: Collective
1528: Input Parameters:
1529: + sf - star forest on which to communicate
1530: . unit - data type associated with each node
1531: . rootmtype - memory type of `rootdata`
1532: . rootdata - buffer to broadcast
1533: . leafmtype - memory type of `leafdata`
1534: - op - operation to use for reduction
1536: Output Parameter:
1537: . leafdata - buffer to be reduced with values from each leaf's respective root
1539: Level: intermediate
1541: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFBcastEnd()`, `PetscSFBcastBegin()`
1542: @*/
1543: PetscErrorCode PetscSFBcastWithMemTypeBegin(PetscSF sf, MPI_Datatype unit, PetscMemType rootmtype, const void *rootdata, PetscMemType leafmtype, void *leafdata, MPI_Op op)
1544: {
1545: PetscFunctionBegin;
1547: PetscCall(PetscSFSetUp(sf));
1548: if (!sf->vscat.logging) PetscCall(PetscLogEventBegin(PETSCSF_BcastBegin, sf, 0, 0, 0));
1549: PetscUseTypeMethod(sf, BcastBegin, unit, rootmtype, rootdata, leafmtype, leafdata, op);
1550: if (!sf->vscat.logging) PetscCall(PetscLogEventEnd(PETSCSF_BcastBegin, sf, 0, 0, 0));
1551: PetscFunctionReturn(PETSC_SUCCESS);
1552: }
1554: /*@
1555: PetscSFBcastEnd - end a broadcast and reduce operation started with `PetscSFBcastBegin()` or `PetscSFBcastWithMemTypeBegin()`
1557: Collective
1559: Input Parameters:
1560: + sf - star forest
1561: . unit - data type
1562: . rootdata - buffer to broadcast
1563: - op - operation to use for reduction
1565: Output Parameter:
1566: . leafdata - buffer to be reduced with values from each leaf's respective root
1568: Level: intermediate
1570: Notes:
1571: For device buffers, this routine synchronizes the SF device stream when the current `PetscDeviceContext`
1572: uses `PETSC_STREAM_DEFAULT_WITH_BARRIER` or `PETSC_STREAM_NONBLOCKING_WITH_BARRIER`. Otherwise, device work
1573: may remain pending after this routine returns.
1575: Use the same current device context for the matching Begin/End calls. Before using the same `PetscSF` on
1576: a different context, complete all outstanding Begin/End pairs and call `PetscDeviceContextSynchronize()`
1577: on the previous context. This also applies when using different user buffers, since SF may reuse internal buffers.
1578: See `PetscSFSetFromOptions()` for the additional Kokkos, MPIX, and NVSHMEM stream limitations.
1580: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFSetGraph()`, `PetscSFReduceEnd()`
1581: @*/
1582: PetscErrorCode PetscSFBcastEnd(PetscSF sf, MPI_Datatype unit, const void *rootdata, void *leafdata, MPI_Op op)
1583: {
1584: PetscFunctionBegin;
1586: if (!sf->vscat.logging) PetscCall(PetscLogEventBegin(PETSCSF_BcastEnd, sf, 0, 0, 0));
1587: PetscUseTypeMethod(sf, BcastEnd, unit, rootdata, leafdata, op);
1588: if (!sf->vscat.logging) PetscCall(PetscLogEventEnd(PETSCSF_BcastEnd, sf, 0, 0, 0));
1589: PetscFunctionReturn(PETSC_SUCCESS);
1590: }
1592: /*@
1593: PetscSFReduceBegin - begin reduction (communication) of `leafdata` into `rootdata`, to be completed with call to `PetscSFReduceEnd()`
1595: Collective
1597: Input Parameters:
1598: + sf - star forest
1599: . unit - data type
1600: . leafdata - values to reduce (communicate)
1601: - op - reduction operation
1603: Output Parameter:
1604: . rootdata - result of reduction of values (`leafdata`) from all leaves to each root
1606: Level: intermediate
1608: Note:
1609: When PETSc is configured with device support, it will use `PetscGetMemType()` to determine whether the given data pointers
1610: are host pointers or device pointers, which may incur a noticeable cost. If you already knew the memory type, you should
1611: use `PetscSFReduceWithMemTypeBegin()` instead.
1613: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFBcastBegin()`, `PetscSFReduceWithMemTypeBegin()`, `PetscSFReduceEnd()`, `MPI_Datatype`
1614: @*/
1615: PetscErrorCode PetscSFReduceBegin(PetscSF sf, MPI_Datatype unit, const void *leafdata, void *rootdata, MPI_Op op)
1616: {
1617: PetscMemType rootmtype, leafmtype;
1619: PetscFunctionBegin;
1621: PetscCall(PetscSFSetUp(sf));
1622: if (!sf->vscat.logging) PetscCall(PetscLogEventBegin(PETSCSF_ReduceBegin, sf, 0, 0, 0));
1623: PetscCall(PetscGetMemType(rootdata, &rootmtype));
1624: PetscCall(PetscGetMemType(leafdata, &leafmtype));
1625: PetscCall(sf->ops->ReduceBegin(sf, unit, leafmtype, leafdata, rootmtype, rootdata, op));
1626: if (!sf->vscat.logging) PetscCall(PetscLogEventEnd(PETSCSF_ReduceBegin, sf, 0, 0, 0));
1627: PetscFunctionReturn(PETSC_SUCCESS);
1628: }
1630: /*@
1631: PetscSFReduceWithMemTypeBegin - begin reduction of `leafdata` into `rootdata` with explicit memory types, to be completed with call to `PetscSFReduceEnd()`
1633: Collective
1635: Input Parameters:
1636: + sf - star forest
1637: . unit - data type
1638: . leafmtype - memory type of `leafdata`
1639: . leafdata - values to reduce
1640: . rootmtype - memory type of `rootdata`
1641: - op - reduction operation
1643: Output Parameter:
1644: . rootdata - result of reduction of values from all leaves of each root
1646: Level: intermediate
1648: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFBcastBegin()`, `PetscSFReduceBegin()`, `PetscSFReduceEnd()`
1649: @*/
1650: PetscErrorCode PetscSFReduceWithMemTypeBegin(PetscSF sf, MPI_Datatype unit, PetscMemType leafmtype, const void *leafdata, PetscMemType rootmtype, void *rootdata, MPI_Op op)
1651: {
1652: PetscFunctionBegin;
1654: PetscCall(PetscSFSetUp(sf));
1655: if (!sf->vscat.logging) PetscCall(PetscLogEventBegin(PETSCSF_ReduceBegin, sf, 0, 0, 0));
1656: PetscCall(sf->ops->ReduceBegin(sf, unit, leafmtype, leafdata, rootmtype, rootdata, op));
1657: if (!sf->vscat.logging) PetscCall(PetscLogEventEnd(PETSCSF_ReduceBegin, sf, 0, 0, 0));
1658: PetscFunctionReturn(PETSC_SUCCESS);
1659: }
1661: /*@
1662: PetscSFReduceEnd - end a reduction operation started with `PetscSFReduceBegin()` or `PetscSFReduceWithMemTypeBegin()`
1664: Collective
1666: Input Parameters:
1667: + sf - star forest
1668: . unit - data type
1669: . leafdata - values to reduce
1670: - op - reduction operation
1672: Output Parameter:
1673: . rootdata - result of reduction of values from all leaves of each root
1675: Level: intermediate
1677: Notes:
1678: For device buffers, this routine synchronizes the SF device stream when the current `PetscDeviceContext`
1679: uses `PETSC_STREAM_DEFAULT_WITH_BARRIER` or `PETSC_STREAM_NONBLOCKING_WITH_BARRIER`. Otherwise, device work
1680: may remain pending after this routine returns.
1682: Use the same current device context for the matching Begin/End calls. Before using the same `PetscSF` on
1683: a different context, complete all outstanding Begin/End pairs and call `PetscDeviceContextSynchronize()`
1684: on the previous context. This also applies when using different user buffers, since SF may reuse internal buffers.
1685: See `PetscSFSetFromOptions()` for the additional Kokkos, MPIX, and NVSHMEM stream limitations.
1687: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFSetGraph()`, `PetscSFBcastEnd()`, `PetscSFReduceBegin()`, `PetscSFReduceWithMemTypeBegin()`
1688: @*/
1689: PetscErrorCode PetscSFReduceEnd(PetscSF sf, MPI_Datatype unit, const void *leafdata, void *rootdata, MPI_Op op)
1690: {
1691: PetscFunctionBegin;
1693: if (!sf->vscat.logging) PetscCall(PetscLogEventBegin(PETSCSF_ReduceEnd, sf, 0, 0, 0));
1694: PetscUseTypeMethod(sf, ReduceEnd, unit, leafdata, rootdata, op);
1695: if (!sf->vscat.logging) PetscCall(PetscLogEventEnd(PETSCSF_ReduceEnd, sf, 0, 0, 0));
1696: PetscFunctionReturn(PETSC_SUCCESS);
1697: }
1699: /*@
1700: PetscSFFetchAndOpBegin - begin operation that fetches values from `rootdata` and updates it atomically by applying operation using `leafdata`,
1701: to be completed with `PetscSFFetchAndOpEnd()`
1703: Collective
1705: Input Parameters:
1706: + sf - star forest
1707: . unit - data type
1708: . leafdata - leaf values to use in reduction
1709: - op - operation to use for reduction
1711: Output Parameters:
1712: + rootdata - root values to be updated, input state is seen by first process to perform an update
1713: - leafupdate - state at each leaf's respective root immediately prior to atomic update
1715: Level: advanced
1717: Note:
1718: The update is only atomic at the granularity provided by the hardware. Different roots referenced by the same process
1719: might be updated in a different order. Furthermore, if a composite type is used for the unit datatype, atomicity is
1720: not guaranteed across the whole vertex. Therefore, this function is mostly only used with primitive types such as
1721: integers.
1723: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFComputeDegreeBegin()`, `PetscSFReduceBegin()`, `PetscSFSetGraph()`
1724: @*/
1725: PetscErrorCode PetscSFFetchAndOpBegin(PetscSF sf, MPI_Datatype unit, void *rootdata, const void *leafdata, void *leafupdate, MPI_Op op)
1726: {
1727: PetscMemType rootmtype, leafmtype, leafupdatemtype;
1729: PetscFunctionBegin;
1731: PetscCall(PetscSFSetUp(sf));
1732: PetscCall(PetscLogEventBegin(PETSCSF_FetchAndOpBegin, sf, 0, 0, 0));
1733: PetscCall(PetscGetMemType(rootdata, &rootmtype));
1734: PetscCall(PetscGetMemType(leafdata, &leafmtype));
1735: PetscCall(PetscGetMemType(leafupdate, &leafupdatemtype));
1736: PetscCheck(leafmtype == leafupdatemtype, PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for leafdata and leafupdate in different memory types");
1737: PetscUseTypeMethod(sf, FetchAndOpBegin, unit, rootmtype, rootdata, leafmtype, leafdata, leafupdate, op);
1738: PetscCall(PetscLogEventEnd(PETSCSF_FetchAndOpBegin, sf, 0, 0, 0));
1739: PetscFunctionReturn(PETSC_SUCCESS);
1740: }
1742: /*@
1743: PetscSFFetchAndOpWithMemTypeBegin - begin operation with explicit memory types that fetches values from root and updates atomically by
1744: applying operation using `leafdata`, to be completed with `PetscSFFetchAndOpEnd()`
1746: Collective
1748: Input Parameters:
1749: + sf - star forest
1750: . unit - data type
1751: . rootmtype - memory type of `rootdata`
1752: . leafmtype - memory type of `leafdata`
1753: . leafdata - leaf values to use in reduction
1754: . leafupdatemtype - memory type of `leafupdate`
1755: - op - operation to use for reduction
1757: Output Parameters:
1758: + rootdata - root values to be updated, input state is seen by first process to perform an update
1759: - leafupdate - state at each leaf's respective root immediately prior to atomic update
1761: Level: advanced
1763: Note:
1764: See `PetscSFFetchAndOpBegin()` for more details.
1766: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFFetchAndOpBegin()`, `PetscSFComputeDegreeBegin()`, `PetscSFReduceBegin()`, `PetscSFSetGraph()`, `PetscSFFetchAndOpEnd()`
1767: @*/
1768: PetscErrorCode PetscSFFetchAndOpWithMemTypeBegin(PetscSF sf, MPI_Datatype unit, PetscMemType rootmtype, void *rootdata, PetscMemType leafmtype, const void *leafdata, PetscMemType leafupdatemtype, void *leafupdate, MPI_Op op)
1769: {
1770: PetscFunctionBegin;
1772: PetscCall(PetscSFSetUp(sf));
1773: PetscCall(PetscLogEventBegin(PETSCSF_FetchAndOpBegin, sf, 0, 0, 0));
1774: PetscCheck(leafmtype == leafupdatemtype, PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for leafdata and leafupdate in different memory types");
1775: PetscUseTypeMethod(sf, FetchAndOpBegin, unit, rootmtype, rootdata, leafmtype, leafdata, leafupdate, op);
1776: PetscCall(PetscLogEventEnd(PETSCSF_FetchAndOpBegin, sf, 0, 0, 0));
1777: PetscFunctionReturn(PETSC_SUCCESS);
1778: }
1780: /*@
1781: PetscSFFetchAndOpEnd - end operation started in matching call to `PetscSFFetchAndOpBegin()` or `PetscSFFetchAndOpWithMemTypeBegin()`
1782: to fetch values from roots and update atomically by applying operation using `leafdata`
1784: Collective
1786: Input Parameters:
1787: + sf - star forest
1788: . unit - data type
1789: . leafdata - leaf values to use in reduction
1790: - op - operation to use for reduction
1792: Output Parameters:
1793: + rootdata - root values to be updated, input state is seen by first process to perform an update
1794: - leafupdate - state at each leaf's respective root immediately prior to atomic update
1796: Level: advanced
1798: Notes:
1799: For device buffers, this routine synchronizes the SF device stream when the current `PetscDeviceContext`
1800: uses `PETSC_STREAM_DEFAULT_WITH_BARRIER` or `PETSC_STREAM_NONBLOCKING_WITH_BARRIER`. Otherwise, device work
1801: may remain pending after this routine returns.
1803: Use the same current device context for the matching Begin/End calls. Before using the same `PetscSF` on
1804: a different context, complete all outstanding Begin/End pairs and call `PetscDeviceContextSynchronize()`
1805: on the previous context. This also applies when using different user buffers, since SF may reuse internal buffers.
1806: See `PetscSFSetFromOptions()` for the additional Kokkos, MPIX, and NVSHMEM stream limitations.
1808: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFComputeDegreeEnd()`, `PetscSFReduceEnd()`, `PetscSFSetGraph()`, `PetscSFFetchAndOpBegin()`, `PetscSFFetchAndOpWithMemTypeBegin()`
1809: @*/
1810: PetscErrorCode PetscSFFetchAndOpEnd(PetscSF sf, MPI_Datatype unit, void *rootdata, const void *leafdata, void *leafupdate, MPI_Op op)
1811: {
1812: PetscFunctionBegin;
1814: PetscCall(PetscLogEventBegin(PETSCSF_FetchAndOpEnd, sf, 0, 0, 0));
1815: PetscUseTypeMethod(sf, FetchAndOpEnd, unit, rootdata, leafdata, leafupdate, op);
1816: PetscCall(PetscLogEventEnd(PETSCSF_FetchAndOpEnd, sf, 0, 0, 0));
1817: PetscFunctionReturn(PETSC_SUCCESS);
1818: }
1820: /*@
1821: PetscSFComputeDegreeBegin - begin computation of the degree of each root vertex, to be completed with `PetscSFComputeDegreeEnd()`
1823: Collective
1825: Input Parameter:
1826: . sf - star forest
1828: Output Parameter:
1829: . degree - degree (the number of leaves) of each root vertex
1831: Level: advanced
1833: Note:
1834: The returned array is owned by `PetscSF` and automatically freed by `PetscSFDestroy()`. Hence there is no need to call `PetscFree()` on it.
1836: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFGatherBegin()`, `PetscSFComputeDegreeEnd()`
1837: @*/
1838: PetscErrorCode PetscSFComputeDegreeBegin(PetscSF sf, const PetscInt *degree[])
1839: {
1840: PetscFunctionBegin;
1842: PetscSFCheckGraphSet(sf, 1);
1843: PetscAssertPointer(degree, 2);
1844: if (!sf->degreeknown) {
1845: PetscInt i, nroots = sf->nroots, maxlocal;
1846: PetscCheck(!sf->degree, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Calls to PetscSFComputeDegreeBegin() cannot be nested.");
1847: maxlocal = sf->maxleaf - sf->minleaf + 1;
1848: PetscCall(PetscMalloc1(nroots, &sf->degree));
1849: PetscCall(PetscMalloc1(PetscMax(maxlocal, 1), &sf->degreetmp)); /* allocate at least one entry, see check in PetscSFComputeDegreeEnd() */
1850: for (i = 0; i < nroots; i++) sf->degree[i] = 0;
1851: for (i = 0; i < maxlocal; i++) sf->degreetmp[i] = 1;
1852: PetscCall(PetscSFReduceBegin(sf, MPIU_INT, sf->degreetmp - sf->minleaf, sf->degree, MPI_SUM));
1853: }
1854: *degree = NULL;
1855: PetscFunctionReturn(PETSC_SUCCESS);
1856: }
1858: /*@
1859: PetscSFComputeDegreeEnd - complete computation of degree for each root vertex, started with `PetscSFComputeDegreeBegin()`
1861: Collective
1863: Input Parameter:
1864: . sf - star forest
1866: Output Parameter:
1867: . degree - degree of each root vertex
1869: Level: developer
1871: Note:
1872: The returned array is owned by `PetscSF` and automatically freed by `PetscSFDestroy()`. Hence there is no need to call `PetscFree()` on it.
1874: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFGatherBegin()`, `PetscSFComputeDegreeBegin()`
1875: @*/
1876: PetscErrorCode PetscSFComputeDegreeEnd(PetscSF sf, const PetscInt *degree[])
1877: {
1878: PetscFunctionBegin;
1880: PetscSFCheckGraphSet(sf, 1);
1881: PetscAssertPointer(degree, 2);
1882: if (!sf->degreeknown) {
1883: PetscCheck(sf->degreetmp, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PetscSFComputeDegreeBegin() before PetscSFComputeDegreeEnd()");
1884: PetscCall(PetscSFReduceEnd(sf, MPIU_INT, sf->degreetmp - sf->minleaf, sf->degree, MPI_SUM));
1885: PetscCall(PetscFree(sf->degreetmp));
1886: sf->degreeknown = PETSC_TRUE;
1887: }
1888: *degree = sf->degree;
1889: PetscFunctionReturn(PETSC_SUCCESS);
1890: }
1892: /*@
1893: PetscSFComputeMultiRootOriginalNumbering - Returns original numbering of multi-roots (roots of multi-`PetscSF` returned by `PetscSFGetMultiSF()`).
1894: Each multi-root is assigned index of the corresponding original root.
1896: Collective
1898: Input Parameters:
1899: + sf - star forest
1900: - degree - degree of each root vertex, computed with `PetscSFComputeDegreeBegin()` and `PetscSFComputeDegreeEnd()`
1902: Output Parameters:
1903: + nMultiRoots - (optional) number of multi-roots (roots of multi-`PetscSF`)
1904: - multiRootsOrigNumbering - original indices of multi-roots; length of this array is `nMultiRoots`
1906: Level: developer
1908: Note:
1909: The returned array `multiRootsOrigNumbering` should be destroyed with `PetscFree()` when no longer needed.
1911: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFComputeDegreeBegin()`, `PetscSFComputeDegreeEnd()`, `PetscSFGetMultiSF()`
1912: @*/
1913: PetscErrorCode PetscSFComputeMultiRootOriginalNumbering(PetscSF sf, const PetscInt degree[], PetscInt *nMultiRoots, PetscInt *multiRootsOrigNumbering[])
1914: {
1915: PetscSF msf;
1916: PetscInt k = 0, nroots, nmroots;
1918: PetscFunctionBegin;
1920: PetscCall(PetscSFGetGraph(sf, &nroots, NULL, NULL, NULL));
1921: if (nroots) PetscAssertPointer(degree, 2);
1922: if (nMultiRoots) PetscAssertPointer(nMultiRoots, 3);
1923: PetscAssertPointer(multiRootsOrigNumbering, 4);
1924: PetscCall(PetscSFGetMultiSF(sf, &msf));
1925: PetscCall(PetscSFGetGraph(msf, &nmroots, NULL, NULL, NULL));
1926: PetscCall(PetscMalloc1(nmroots, multiRootsOrigNumbering));
1927: for (PetscInt i = 0; i < nroots; i++) {
1928: if (!degree[i]) continue;
1929: for (PetscInt j = 0; j < degree[i]; j++, k++) (*multiRootsOrigNumbering)[k] = i;
1930: }
1931: PetscCheck(k == nmroots, PETSC_COMM_SELF, PETSC_ERR_PLIB, "sanity check fail");
1932: if (nMultiRoots) *nMultiRoots = nmroots;
1933: PetscFunctionReturn(PETSC_SUCCESS);
1934: }
1936: /*@
1937: PetscSFGatherBegin - begin pointwise gather of all leaves into multi-roots, to be completed with `PetscSFGatherEnd()`
1939: Collective
1941: Input Parameters:
1942: + sf - star forest
1943: . unit - data type
1944: - leafdata - leaf data to gather to roots
1946: Output Parameter:
1947: . multirootdata - root buffer to gather into, amount of space per root is equal to its degree (which is the number of leaves that root has)
1949: Level: intermediate
1951: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFComputeDegreeBegin()`, `PetscSFScatterBegin()`
1952: @*/
1953: PetscErrorCode PetscSFGatherBegin(PetscSF sf, MPI_Datatype unit, const void *leafdata, void *multirootdata)
1954: {
1955: PetscSF multi = NULL;
1957: PetscFunctionBegin;
1959: PetscCall(PetscSFSetUp(sf));
1960: PetscCall(PetscSFGetMultiSF(sf, &multi));
1961: PetscCall(PetscSFReduceBegin(multi, unit, leafdata, multirootdata, MPI_REPLACE));
1962: PetscFunctionReturn(PETSC_SUCCESS);
1963: }
1965: /*@
1966: PetscSFGatherEnd - ends pointwise gather operation that was started with `PetscSFGatherBegin()`
1968: Collective
1970: Input Parameters:
1971: + sf - star forest
1972: . unit - data type
1973: - leafdata - leaf data to gather to roots
1975: Output Parameter:
1976: . multirootdata - root buffer to gather into, amount of space per root is equal to its degree (which is the number of leaves that root has)
1978: Level: intermediate
1980: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFComputeDegreeEnd()`, `PetscSFScatterEnd()`
1981: @*/
1982: PetscErrorCode PetscSFGatherEnd(PetscSF sf, MPI_Datatype unit, const void *leafdata, void *multirootdata)
1983: {
1984: PetscSF multi = NULL;
1986: PetscFunctionBegin;
1988: PetscCall(PetscSFGetMultiSF(sf, &multi));
1989: PetscCall(PetscSFReduceEnd(multi, unit, leafdata, multirootdata, MPI_REPLACE));
1990: PetscFunctionReturn(PETSC_SUCCESS);
1991: }
1993: /*@
1994: PetscSFScatterBegin - begin pointwise scatter operation from multi-roots to leaves, to be completed with `PetscSFScatterEnd()`
1996: Collective
1998: Input Parameters:
1999: + sf - star forest
2000: . unit - data type
2001: - multirootdata - root buffer to send to each leaf, one unit of data is provided to each leaf thus the amount of space per root is equal to its degree (which is the number of leaves that root has)
2003: Output Parameter:
2004: . leafdata - leaf data to be update with personal data from each respective root
2006: Level: intermediate
2008: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFComputeDegreeBegin()`, `PetscSFComputeDegreeEnd()`, `PetscSFScatterEnd()`
2009: @*/
2010: PetscErrorCode PetscSFScatterBegin(PetscSF sf, MPI_Datatype unit, const void *multirootdata, void *leafdata)
2011: {
2012: PetscSF multi = NULL;
2014: PetscFunctionBegin;
2016: PetscCall(PetscSFSetUp(sf));
2017: PetscCall(PetscSFGetMultiSF(sf, &multi));
2018: PetscCall(PetscSFBcastBegin(multi, unit, multirootdata, leafdata, MPI_REPLACE));
2019: PetscFunctionReturn(PETSC_SUCCESS);
2020: }
2022: /*@
2023: PetscSFScatterEnd - ends pointwise scatter operation that was started with `PetscSFScatterBegin()`
2025: Collective
2027: Input Parameters:
2028: + sf - star forest
2029: . unit - data type
2030: - multirootdata - root buffer to send to each leaf, one unit of data per leaf
2032: Output Parameter:
2033: . leafdata - leaf data to be update with personal data from each respective root
2035: Level: intermediate
2037: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFComputeDegreeBegin()`, `PetscSFComputeDegreeEnd()`, `PetscSFScatterBegin()`
2038: @*/
2039: PetscErrorCode PetscSFScatterEnd(PetscSF sf, MPI_Datatype unit, const void *multirootdata, void *leafdata)
2040: {
2041: PetscSF multi = NULL;
2043: PetscFunctionBegin;
2045: PetscCall(PetscSFGetMultiSF(sf, &multi));
2046: PetscCall(PetscSFBcastEnd(multi, unit, multirootdata, leafdata, MPI_REPLACE));
2047: PetscFunctionReturn(PETSC_SUCCESS);
2048: }
2050: static PetscErrorCode PetscSFCheckLeavesUnique_Private(PetscSF sf)
2051: {
2052: PetscInt i, n, nleaves;
2053: const PetscInt *ilocal = NULL;
2054: PetscHSetI seen;
2056: PetscFunctionBegin;
2057: if (PetscDefined(USE_DEBUG)) {
2058: PetscCall(PetscSFGetGraph(sf, NULL, &nleaves, &ilocal, NULL));
2059: PetscCall(PetscHSetICreate(&seen));
2060: for (i = 0; i < nleaves; i++) {
2061: const PetscInt leaf = ilocal ? ilocal[i] : i;
2062: PetscCall(PetscHSetIAdd(seen, leaf));
2063: }
2064: PetscCall(PetscHSetIGetSize(seen, &n));
2065: PetscCheck(n == nleaves, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Provided leaves have repeated values: all leaves must be unique");
2066: PetscCall(PetscHSetIDestroy(&seen));
2067: }
2068: PetscFunctionReturn(PETSC_SUCCESS);
2069: }
2071: /*@
2072: PetscSFCompose - Compose a new `PetscSF` by putting the second `PetscSF` under the first one in a top (roots) down (leaves) view
2074: Input Parameters:
2075: + sfA - The first `PetscSF`
2076: - sfB - The second `PetscSF`
2078: Output Parameter:
2079: . sfBA - The composite `PetscSF`
2081: Level: developer
2083: Notes:
2084: Currently, the two `PetscSF`s must be defined on congruent communicators and they must be true star
2085: forests, i.e. the same leaf is not connected with different roots.
2087: `sfA`'s leaf space and `sfB`'s root space might be partially overlapped. The composition builds
2088: a graph with `sfA`'s roots and `sfB`'s leaves only when there is a path between them. Unconnected
2089: nodes (roots or leaves) are not in `sfBA`. Doing a `PetscSFBcastBegin()` and `PetscSFBcastEnd()` on the new `PetscSF` is equivalent to doing a
2090: `PetscSFBcastBegin()` and `PetscSFBcastEnd()` on `sfA`, then a `PetscSFBcastBegin()` and `PetscSFBcastEnd()` on `sfB`, on connected nodes.
2092: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFComposeInverse()`, `PetscSFGetGraph()`, `PetscSFSetGraph()`
2093: @*/
2094: PetscErrorCode PetscSFCompose(PetscSF sfA, PetscSF sfB, PetscSF *sfBA)
2095: {
2096: const PetscSFNode *remotePointsA, *remotePointsB;
2097: PetscSFNode *remotePointsBA = NULL, *reorderedRemotePointsA = NULL, *leafdataB;
2098: const PetscInt *localPointsA, *localPointsB;
2099: PetscInt *localPointsBA;
2100: PetscInt i, numRootsA, numLeavesA, numRootsB, numLeavesB, minleaf, maxleaf, numLeavesBA;
2101: PetscBool denseB;
2103: PetscFunctionBegin;
2105: PetscSFCheckGraphSet(sfA, 1);
2107: PetscSFCheckGraphSet(sfB, 2);
2108: PetscCheckSameComm(sfA, 1, sfB, 2);
2109: PetscAssertPointer(sfBA, 3);
2110: PetscCall(PetscSFCheckLeavesUnique_Private(sfA));
2111: PetscCall(PetscSFCheckLeavesUnique_Private(sfB));
2113: PetscCall(PetscSFGetGraph(sfA, &numRootsA, &numLeavesA, &localPointsA, &remotePointsA));
2114: PetscCall(PetscSFGetGraph(sfB, &numRootsB, &numLeavesB, &localPointsB, &remotePointsB));
2115: /* Make sure that PetscSFBcast{Begin, End}(sfB, ...) works with root data of size
2116: numRootsB; otherwise, garbage will be broadcasted.
2117: Example (comm size = 1):
2118: sfA: 0 <- (0, 0)
2119: sfB: 100 <- (0, 0)
2120: 101 <- (0, 1)
2121: Here, we have remotePointsA = [(0, 0)], but for remotePointsA to be a valid tartget
2122: of sfB, it has to be recasted as [(0, 0), (-1, -1)] so that points 100 and 101 would
2123: receive (0, 0) and (-1, -1), respectively, when PetscSFBcast(sfB, ...) is called on
2124: remotePointsA; if not recasted, point 101 would receive a garbage value. */
2125: PetscCall(PetscMalloc1(numRootsB, &reorderedRemotePointsA));
2126: for (i = 0; i < numRootsB; i++) {
2127: reorderedRemotePointsA[i].rank = -1;
2128: reorderedRemotePointsA[i].index = -1;
2129: }
2130: for (i = 0; i < numLeavesA; i++) {
2131: PetscInt localp = localPointsA ? localPointsA[i] : i;
2133: if (localp >= numRootsB) continue;
2134: reorderedRemotePointsA[localp] = remotePointsA[i];
2135: }
2136: remotePointsA = reorderedRemotePointsA;
2137: PetscCall(PetscSFGetLeafRange(sfB, &minleaf, &maxleaf));
2138: PetscCall(PetscMalloc1(maxleaf - minleaf + 1, &leafdataB));
2139: for (i = 0; i < maxleaf - minleaf + 1; i++) {
2140: leafdataB[i].rank = -1;
2141: leafdataB[i].index = -1;
2142: }
2143: PetscCall(PetscSFBcastBegin(sfB, MPIU_SF_NODE, remotePointsA, PetscSafePointerPlusOffset(leafdataB, -minleaf), MPI_REPLACE));
2144: PetscCall(PetscSFBcastEnd(sfB, MPIU_SF_NODE, remotePointsA, PetscSafePointerPlusOffset(leafdataB, -minleaf), MPI_REPLACE));
2145: PetscCall(PetscFree(reorderedRemotePointsA));
2147: denseB = (PetscBool)!localPointsB;
2148: for (i = 0, numLeavesBA = 0; i < numLeavesB; i++) {
2149: if (leafdataB[localPointsB ? localPointsB[i] - minleaf : i].rank == -1) denseB = PETSC_FALSE;
2150: else numLeavesBA++;
2151: }
2152: if (denseB) {
2153: localPointsBA = NULL;
2154: remotePointsBA = leafdataB;
2155: } else {
2156: PetscCall(PetscMalloc1(numLeavesBA, &localPointsBA));
2157: PetscCall(PetscMalloc1(numLeavesBA, &remotePointsBA));
2158: for (i = 0, numLeavesBA = 0; i < numLeavesB; i++) {
2159: const PetscInt l = localPointsB ? localPointsB[i] : i;
2161: if (leafdataB[l - minleaf].rank == -1) continue;
2162: remotePointsBA[numLeavesBA] = leafdataB[l - minleaf];
2163: localPointsBA[numLeavesBA] = l;
2164: numLeavesBA++;
2165: }
2166: PetscCall(PetscFree(leafdataB));
2167: }
2168: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)sfA), sfBA));
2169: PetscCall(PetscSFSetFromOptions(*sfBA));
2170: PetscCall(PetscSFSetGraph(*sfBA, numRootsA, numLeavesBA, localPointsBA, PETSC_OWN_POINTER, remotePointsBA, PETSC_OWN_POINTER));
2171: PetscFunctionReturn(PETSC_SUCCESS);
2172: }
2174: /*@
2175: PetscSFComposeInverse - Compose a new `PetscSF` by putting the inverse of the second `PetscSF` under the first one
2177: Input Parameters:
2178: + sfA - The first `PetscSF`
2179: - sfB - The second `PetscSF`
2181: Output Parameter:
2182: . sfBA - The composite `PetscSF`.
2184: Level: developer
2186: Notes:
2187: Currently, the two `PetscSF`s must be defined on congruent communicators and they must be true star
2188: forests, i.e. the same leaf is not connected with different roots. Even more, all roots of the
2189: second `PetscSF` must have a degree of 1, i.e., no roots have more than one leaf connected.
2191: `sfA`'s leaf space and `sfB`'s leaf space might be partially overlapped. The composition builds
2192: a graph with `sfA`'s roots and `sfB`'s roots only when there is a path between them. Unconnected
2193: roots are not in `sfBA`. Doing a `PetscSFBcastBegin()` and `PetscSFBcastEnd()` on the new `PetscSF` is equivalent to doing a `PetscSFBcastBegin()` and `PetscSFBcastEnd()`
2194: on `sfA`, then
2195: a `PetscSFReduceBegin()` and `PetscSFReduceEnd()` on `sfB`, on connected roots.
2197: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFCompose()`, `PetscSFGetGraph()`, `PetscSFSetGraph()`, `PetscSFCreateInverseSF()`
2198: @*/
2199: PetscErrorCode PetscSFComposeInverse(PetscSF sfA, PetscSF sfB, PetscSF *sfBA)
2200: {
2201: const PetscSFNode *remotePointsA, *remotePointsB;
2202: PetscSFNode *remotePointsBA;
2203: const PetscInt *localPointsA, *localPointsB;
2204: PetscSFNode *reorderedRemotePointsA = NULL;
2205: PetscInt i, numRootsA, numLeavesA, numLeavesBA, numRootsB, numLeavesB, minleaf, maxleaf, *localPointsBA;
2206: MPI_Op op;
2207: #if PetscDefined(USE_64BIT_INDICES)
2208: PetscBool iswin;
2209: #endif
2211: PetscFunctionBegin;
2213: PetscSFCheckGraphSet(sfA, 1);
2215: PetscSFCheckGraphSet(sfB, 2);
2216: PetscCheckSameComm(sfA, 1, sfB, 2);
2217: PetscAssertPointer(sfBA, 3);
2218: PetscCall(PetscSFCheckLeavesUnique_Private(sfA));
2219: PetscCall(PetscSFCheckLeavesUnique_Private(sfB));
2221: PetscCall(PetscSFGetGraph(sfA, &numRootsA, &numLeavesA, &localPointsA, &remotePointsA));
2222: PetscCall(PetscSFGetGraph(sfB, &numRootsB, &numLeavesB, &localPointsB, &remotePointsB));
2224: /* TODO: Check roots of sfB have degree of 1 */
2225: /* Once we implement it, we can replace the MPI_MAXLOC
2226: with MPI_REPLACE. In that case, MPI_MAXLOC and MPI_REPLACE have the same effect.
2227: We use MPI_MAXLOC only to have a deterministic output from this routine if
2228: the root condition is not meet.
2229: */
2230: op = MPI_MAXLOC;
2231: #if PetscDefined(USE_64BIT_INDICES)
2232: /* we accept a non-deterministic output (if any) with PETSCSFWINDOW, since MPI_MAXLOC cannot operate on MPIU_2INT with MPI_Accumulate */
2233: PetscCall(PetscObjectTypeCompare((PetscObject)sfB, PETSCSFWINDOW, &iswin));
2234: if (iswin) op = MPI_REPLACE;
2235: #endif
2237: PetscCall(PetscSFGetLeafRange(sfB, &minleaf, &maxleaf));
2238: PetscCall(PetscMalloc1(maxleaf - minleaf + 1, &reorderedRemotePointsA));
2239: for (i = 0; i < maxleaf - minleaf + 1; i++) {
2240: reorderedRemotePointsA[i].rank = -1;
2241: reorderedRemotePointsA[i].index = -1;
2242: }
2243: if (localPointsA) {
2244: for (i = 0; i < numLeavesA; i++) {
2245: if (localPointsA[i] > maxleaf || localPointsA[i] < minleaf) continue;
2246: reorderedRemotePointsA[localPointsA[i] - minleaf] = remotePointsA[i];
2247: }
2248: } else {
2249: for (i = 0; i < numLeavesA; i++) {
2250: if (i > maxleaf || i < minleaf) continue;
2251: reorderedRemotePointsA[i - minleaf] = remotePointsA[i];
2252: }
2253: }
2255: PetscCall(PetscMalloc1(numRootsB, &localPointsBA));
2256: PetscCall(PetscMalloc1(numRootsB, &remotePointsBA));
2257: for (i = 0; i < numRootsB; i++) {
2258: remotePointsBA[i].rank = -1;
2259: remotePointsBA[i].index = -1;
2260: }
2262: PetscCall(PetscSFReduceBegin(sfB, MPIU_SF_NODE, PetscSafePointerPlusOffset(reorderedRemotePointsA, -minleaf), remotePointsBA, op));
2263: PetscCall(PetscSFReduceEnd(sfB, MPIU_SF_NODE, PetscSafePointerPlusOffset(reorderedRemotePointsA, -minleaf), remotePointsBA, op));
2264: PetscCall(PetscFree(reorderedRemotePointsA));
2265: for (i = 0, numLeavesBA = 0; i < numRootsB; i++) {
2266: if (remotePointsBA[i].rank == -1) continue;
2267: remotePointsBA[numLeavesBA].rank = remotePointsBA[i].rank;
2268: remotePointsBA[numLeavesBA].index = remotePointsBA[i].index;
2269: localPointsBA[numLeavesBA] = i;
2270: numLeavesBA++;
2271: }
2272: PetscCall(PetscSFCreate(PetscObjectComm((PetscObject)sfA), sfBA));
2273: PetscCall(PetscSFSetFromOptions(*sfBA));
2274: PetscCall(PetscSFSetGraph(*sfBA, numRootsA, numLeavesBA, localPointsBA, PETSC_OWN_POINTER, remotePointsBA, PETSC_OWN_POINTER));
2275: PetscFunctionReturn(PETSC_SUCCESS);
2276: }
2278: /*
2279: PetscSFCreateLocalSF_Private - Creates a local `PetscSF` that only has intra-process edges of the global `PetscSF`
2281: Input Parameter:
2282: . sf - The global `PetscSF`
2284: Output Parameter:
2285: . out - The local `PetscSF`
2287: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFCreate()`
2288: */
2289: PetscErrorCode PetscSFCreateLocalSF_Private(PetscSF sf, PetscSF *out)
2290: {
2291: MPI_Comm comm;
2292: PetscMPIInt myrank;
2293: const PetscInt *ilocal;
2294: const PetscSFNode *iremote;
2295: PetscInt i, j, nroots, nleaves, lnleaves, *lilocal;
2296: PetscSFNode *liremote;
2297: PetscSF lsf;
2299: PetscFunctionBegin;
2301: if (sf->ops->CreateLocalSF) PetscUseTypeMethod(sf, CreateLocalSF, out);
2302: else {
2303: PetscMPIInt irank;
2305: /* Could use PetscSFCreateEmbeddedLeafSF, but since we know the comm is PETSC_COMM_SELF, we can make it fast */
2306: PetscCall(PetscObjectGetComm((PetscObject)sf, &comm));
2307: PetscCallMPI(MPI_Comm_rank(comm, &myrank));
2309: /* Find out local edges and build a local SF */
2310: PetscCall(PetscSFGetGraph(sf, &nroots, &nleaves, &ilocal, &iremote));
2311: for (i = lnleaves = 0; i < nleaves; i++) {
2312: PetscCall(PetscMPIIntCast(iremote[i].rank, &irank));
2313: if (irank == myrank) lnleaves++;
2314: }
2315: PetscCall(PetscMalloc1(lnleaves, &lilocal));
2316: PetscCall(PetscMalloc1(lnleaves, &liremote));
2318: for (i = j = 0; i < nleaves; i++) {
2319: PetscCall(PetscMPIIntCast(iremote[i].rank, &irank));
2320: if (irank == myrank) {
2321: lilocal[j] = ilocal ? ilocal[i] : i; /* ilocal=NULL for contiguous storage */
2322: liremote[j].rank = 0; /* rank in PETSC_COMM_SELF */
2323: liremote[j].index = iremote[i].index;
2324: j++;
2325: }
2326: }
2327: PetscCall(PetscSFCreate(PETSC_COMM_SELF, &lsf));
2328: PetscCall(PetscSFSetFromOptions(lsf));
2329: PetscCall(PetscSFSetGraph(lsf, nroots, lnleaves, lilocal, PETSC_OWN_POINTER, liremote, PETSC_OWN_POINTER));
2330: PetscCall(PetscSFSetUp(lsf));
2331: *out = lsf;
2332: }
2333: PetscFunctionReturn(PETSC_SUCCESS);
2334: }
2336: /* Similar to PetscSFBcast, but only Bcast to leaves on rank 0 */
2337: PetscErrorCode PetscSFBcastToZero_Private(PetscSF sf, MPI_Datatype unit, const void *rootdata, void *leafdata)
2338: {
2339: PetscMemType rootmtype, leafmtype;
2341: PetscFunctionBegin;
2343: PetscCall(PetscSFSetUp(sf));
2344: PetscCall(PetscLogEventBegin(PETSCSF_BcastBegin, sf, 0, 0, 0));
2345: PetscCall(PetscGetMemType(rootdata, &rootmtype));
2346: PetscCall(PetscGetMemType(leafdata, &leafmtype));
2347: PetscUseTypeMethod(sf, BcastToZero, unit, rootmtype, rootdata, leafmtype, leafdata);
2348: PetscCall(PetscLogEventEnd(PETSCSF_BcastBegin, sf, 0, 0, 0));
2349: PetscFunctionReturn(PETSC_SUCCESS);
2350: }
2352: /*@
2353: PetscSFConcatenate - concatenate multiple `PetscSF` into a new `PetscSF`
2355: Input Parameters:
2356: + comm - the communicator
2357: . nsfs - the number of input `PetscSF`
2358: . sfs - the array of input `PetscSF`
2359: . rootMode - the root mode specifying how roots are handled
2360: - leafOffsets - the array of local leaf offsets, one for each input `PetscSF`, or `NULL` for contiguous storage
2362: Output Parameter:
2363: . newsf - The resulting `PetscSF`
2365: Level: advanced
2367: Notes:
2368: The communicator of all `PetscSF`s in `sfs` must be comm.
2370: Leaves are always concatenated locally, keeping them ordered by the input `PetscSF` index and original local order.
2372: The offsets in `leafOffsets` are added to the original leaf indices.
2374: If all input `PetscSF`s use contiguous leaf storage (`ilocal` = `NULL`), `leafOffsets` can be passed as `NULL` as well.
2375: In this case, `NULL` is also passed as `ilocal` to the resulting `PetscSF`.
2377: If any input `PetscSF` has non-null `ilocal`, `leafOffsets` is needed to distinguish leaves from different input `PetscSF`s.
2378: In this case, user is responsible to provide correct offsets so that the resulting leaves are unique (otherwise an error occurs).
2380: All root modes retain the essential connectivity condition.
2382: If two leaves of the same input `PetscSF` are connected (sharing the same root), they are also connected in the output `PetscSF`.
2384: Parameter `rootMode` controls how the input root spaces are combined.
2385: For `PETSCSF_CONCATENATE_ROOTMODE_SHARED`, the root space is considered the same for each input `PetscSF` (checked in debug mode)
2386: and is also the same in the output `PetscSF`.
2388: For `PETSCSF_CONCATENATE_ROOTMODE_LOCAL` and `PETSCSF_CONCATENATE_ROOTMODE_GLOBAL`, the input root spaces are taken as separate and joined.
2389: `PETSCSF_CONCATENATE_ROOTMODE_LOCAL` joins the root spaces locally;
2390: roots of sfs[0], sfs[1], sfs[2], ... are joined on each MPI process separately, ordered by input `PetscSF` and original local index, and renumbered contiguously.
2391: `PETSCSF_CONCATENATE_ROOTMODE_GLOBAL` joins the root spaces globally;
2392: roots of sfs[0], sfs[1], sfs[2], ... are joined globally, ordered by input `PetscSF` index and original global index, and renumbered contiguously;
2393: the original root MPI processes are ignored.
2394: For both `PETSCSF_CONCATENATE_ROOTMODE_LOCAL` and `PETSCSF_CONCATENATE_ROOTMODE_GLOBAL`,
2395: the output `PetscSF`'s root layout is such that the local number of roots is a sum of the input `PetscSF`'s local numbers of roots on each MPI process
2396: to keep the load balancing.
2397: However, for `PETSCSF_CONCATENATE_ROOTMODE_GLOBAL`, roots can move to different MPI processes.
2399: Example:
2400: We can use src/vec/is/sf/tests/ex18.c to compare the root modes. By running
2401: .vb
2402: make -C $PETSC_DIR/src/vec/is/sf/tests ex18
2403: for m in {local,global,shared}; do
2404: mpiexec -n 2 $PETSC_DIR/src/vec/is/sf/tests/ex18 -nsfs 2 -n 2 -root_mode $m -sf_view
2405: done
2406: .ve
2407: we generate two identical `PetscSF`s sf_0 and sf_1,
2408: .vb
2409: PetscSF Object: sf_0 2 MPI processes
2410: type: basic
2411: rank #leaves #roots
2412: [ 0] 4 2
2413: [ 1] 4 2
2414: leaves roots roots in global numbering
2415: ( 0, 0) <- ( 0, 0) = 0
2416: ( 0, 1) <- ( 0, 1) = 1
2417: ( 0, 2) <- ( 1, 0) = 2
2418: ( 0, 3) <- ( 1, 1) = 3
2419: ( 1, 0) <- ( 0, 0) = 0
2420: ( 1, 1) <- ( 0, 1) = 1
2421: ( 1, 2) <- ( 1, 0) = 2
2422: ( 1, 3) <- ( 1, 1) = 3
2423: .ve
2424: and pass them to `PetscSFConcatenate()` along with different choices of `rootMode`, yielding different result_sf\:
2425: .vb
2426: rootMode = local:
2427: PetscSF Object: result_sf 2 MPI processes
2428: type: basic
2429: rank #leaves #roots
2430: [ 0] 8 4
2431: [ 1] 8 4
2432: leaves roots roots in global numbering
2433: ( 0, 0) <- ( 0, 0) = 0
2434: ( 0, 1) <- ( 0, 1) = 1
2435: ( 0, 2) <- ( 1, 0) = 4
2436: ( 0, 3) <- ( 1, 1) = 5
2437: ( 0, 4) <- ( 0, 2) = 2
2438: ( 0, 5) <- ( 0, 3) = 3
2439: ( 0, 6) <- ( 1, 2) = 6
2440: ( 0, 7) <- ( 1, 3) = 7
2441: ( 1, 0) <- ( 0, 0) = 0
2442: ( 1, 1) <- ( 0, 1) = 1
2443: ( 1, 2) <- ( 1, 0) = 4
2444: ( 1, 3) <- ( 1, 1) = 5
2445: ( 1, 4) <- ( 0, 2) = 2
2446: ( 1, 5) <- ( 0, 3) = 3
2447: ( 1, 6) <- ( 1, 2) = 6
2448: ( 1, 7) <- ( 1, 3) = 7
2450: rootMode = global:
2451: PetscSF Object: result_sf 2 MPI processes
2452: type: basic
2453: rank #leaves #roots
2454: [ 0] 8 4
2455: [ 1] 8 4
2456: leaves roots roots in global numbering
2457: ( 0, 0) <- ( 0, 0) = 0
2458: ( 0, 1) <- ( 0, 1) = 1
2459: ( 0, 2) <- ( 0, 2) = 2
2460: ( 0, 3) <- ( 0, 3) = 3
2461: ( 0, 4) <- ( 1, 0) = 4
2462: ( 0, 5) <- ( 1, 1) = 5
2463: ( 0, 6) <- ( 1, 2) = 6
2464: ( 0, 7) <- ( 1, 3) = 7
2465: ( 1, 0) <- ( 0, 0) = 0
2466: ( 1, 1) <- ( 0, 1) = 1
2467: ( 1, 2) <- ( 0, 2) = 2
2468: ( 1, 3) <- ( 0, 3) = 3
2469: ( 1, 4) <- ( 1, 0) = 4
2470: ( 1, 5) <- ( 1, 1) = 5
2471: ( 1, 6) <- ( 1, 2) = 6
2472: ( 1, 7) <- ( 1, 3) = 7
2474: rootMode = shared:
2475: PetscSF Object: result_sf 2 MPI processes
2476: type: basic
2477: rank #leaves #roots
2478: [ 0] 8 2
2479: [ 1] 8 2
2480: leaves roots roots in global numbering
2481: ( 0, 0) <- ( 0, 0) = 0
2482: ( 0, 1) <- ( 0, 1) = 1
2483: ( 0, 2) <- ( 1, 0) = 2
2484: ( 0, 3) <- ( 1, 1) = 3
2485: ( 0, 4) <- ( 0, 0) = 0
2486: ( 0, 5) <- ( 0, 1) = 1
2487: ( 0, 6) <- ( 1, 0) = 2
2488: ( 0, 7) <- ( 1, 1) = 3
2489: ( 1, 0) <- ( 0, 0) = 0
2490: ( 1, 1) <- ( 0, 1) = 1
2491: ( 1, 2) <- ( 1, 0) = 2
2492: ( 1, 3) <- ( 1, 1) = 3
2493: ( 1, 4) <- ( 0, 0) = 0
2494: ( 1, 5) <- ( 0, 1) = 1
2495: ( 1, 6) <- ( 1, 0) = 2
2496: ( 1, 7) <- ( 1, 1) = 3
2497: .ve
2499: .seealso: [](sec_petscsf), `PetscSF`, `PetscSFCompose()`, `PetscSFGetGraph()`, `PetscSFSetGraph()`, `PetscSFConcatenateRootMode`
2500: @*/
2501: PetscErrorCode PetscSFConcatenate(MPI_Comm comm, PetscInt nsfs, PetscSF sfs[], PetscSFConcatenateRootMode rootMode, PetscInt leafOffsets[], PetscSF *newsf)
2502: {
2503: PetscInt i, s, nLeaves, nRoots;
2504: PetscInt *leafArrayOffsets;
2505: PetscInt *ilocal_new;
2506: PetscSFNode *iremote_new;
2507: PetscBool all_ilocal_null = PETSC_FALSE;
2508: PetscLayout glayout = NULL;
2509: PetscInt *gremote = NULL;
2510: PetscMPIInt rank, size;
2512: PetscFunctionBegin;
2513: if (PetscDefined(USE_DEBUG)) {
2514: PetscSF dummy; /* just to have a PetscObject on comm for input validation */
2516: PetscCall(PetscSFCreate(comm, &dummy));
2518: PetscAssertPointer(sfs, 3);
2519: for (i = 0; i < nsfs; i++) {
2521: PetscCheckSameComm(dummy, 1, sfs[i], 3);
2522: }
2524: if (leafOffsets) PetscAssertPointer(leafOffsets, 5);
2525: PetscAssertPointer(newsf, 6);
2526: PetscCall(PetscSFDestroy(&dummy));
2527: }
2528: if (!nsfs) {
2529: PetscCall(PetscSFCreate(comm, newsf));
2530: PetscCall(PetscSFSetGraph(*newsf, 0, 0, NULL, PETSC_OWN_POINTER, NULL, PETSC_OWN_POINTER));
2531: PetscFunctionReturn(PETSC_SUCCESS);
2532: }
2533: PetscCallMPI(MPI_Comm_rank(comm, &rank));
2534: PetscCallMPI(MPI_Comm_size(comm, &size));
2536: /* Calculate leaf array offsets */
2537: PetscCall(PetscMalloc1(nsfs + 1, &leafArrayOffsets));
2538: leafArrayOffsets[0] = 0;
2539: for (s = 0; s < nsfs; s++) {
2540: PetscInt nl;
2542: PetscCall(PetscSFGetGraph(sfs[s], NULL, &nl, NULL, NULL));
2543: leafArrayOffsets[s + 1] = leafArrayOffsets[s] + nl;
2544: }
2545: nLeaves = leafArrayOffsets[nsfs];
2547: /* Calculate number of roots */
2548: switch (rootMode) {
2549: case PETSCSF_CONCATENATE_ROOTMODE_SHARED: {
2550: PetscCall(PetscSFGetGraph(sfs[0], &nRoots, NULL, NULL, NULL));
2551: if (PetscDefined(USE_DEBUG)) {
2552: for (s = 1; s < nsfs; s++) {
2553: PetscInt nr;
2555: PetscCall(PetscSFGetGraph(sfs[s], &nr, NULL, NULL, NULL));
2556: PetscCheck(nr == nRoots, comm, PETSC_ERR_ARG_SIZ, "rootMode = %s but sfs[%" PetscInt_FMT "] has a different number of roots (%" PetscInt_FMT ") than sfs[0] (%" PetscInt_FMT ")", PetscSFConcatenateRootModes[rootMode], s, nr, nRoots);
2557: }
2558: }
2559: } break;
2560: case PETSCSF_CONCATENATE_ROOTMODE_GLOBAL: {
2561: /* Calculate also global layout in this case */
2562: PetscInt *nls;
2563: PetscLayout *lts;
2564: PetscInt **inds;
2565: PetscInt j;
2566: PetscInt rootOffset = 0;
2568: PetscCall(PetscCalloc3(nsfs, <s, nsfs, &nls, nsfs, &inds));
2569: PetscCall(PetscLayoutCreate(comm, &glayout));
2570: glayout->bs = 1;
2571: glayout->n = 0;
2572: glayout->N = 0;
2573: for (s = 0; s < nsfs; s++) {
2574: PetscCall(PetscSFGetGraphLayout(sfs[s], <s[s], &nls[s], NULL, &inds[s]));
2575: glayout->n += lts[s]->n;
2576: glayout->N += lts[s]->N;
2577: }
2578: PetscCall(PetscLayoutSetUp(glayout));
2579: PetscCall(PetscMalloc1(nLeaves, &gremote));
2580: for (s = 0, j = 0; s < nsfs; s++) {
2581: for (i = 0; i < nls[s]; i++, j++) gremote[j] = inds[s][i] + rootOffset;
2582: rootOffset += lts[s]->N;
2583: PetscCall(PetscLayoutDestroy(<s[s]));
2584: PetscCall(PetscFree(inds[s]));
2585: }
2586: PetscCall(PetscFree3(lts, nls, inds));
2587: nRoots = glayout->N;
2588: } break;
2589: case PETSCSF_CONCATENATE_ROOTMODE_LOCAL:
2590: /* nRoots calculated later in this case */
2591: break;
2592: default:
2593: SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Invalid PetscSFConcatenateRootMode %d", rootMode);
2594: }
2596: if (!leafOffsets) {
2597: all_ilocal_null = PETSC_TRUE;
2598: for (s = 0; s < nsfs; s++) {
2599: const PetscInt *ilocal;
2601: PetscCall(PetscSFGetGraph(sfs[s], NULL, NULL, &ilocal, NULL));
2602: if (ilocal) {
2603: all_ilocal_null = PETSC_FALSE;
2604: break;
2605: }
2606: }
2607: PetscCheck(all_ilocal_null, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "leafOffsets can be passed as NULL only if all SFs have ilocal = NULL");
2608: }
2610: /* Renumber and concatenate local leaves */
2611: ilocal_new = NULL;
2612: if (!all_ilocal_null) {
2613: PetscCall(PetscMalloc1(nLeaves, &ilocal_new));
2614: for (i = 0; i < nLeaves; i++) ilocal_new[i] = -1;
2615: for (s = 0; s < nsfs; s++) {
2616: const PetscInt *ilocal;
2617: PetscInt *ilocal_l = PetscSafePointerPlusOffset(ilocal_new, leafArrayOffsets[s]);
2618: PetscInt nleaves_l;
2620: PetscCall(PetscSFGetGraph(sfs[s], NULL, &nleaves_l, &ilocal, NULL));
2621: for (PetscInt i = 0; i < nleaves_l; i++) ilocal_l[i] = (ilocal ? ilocal[i] : i) + leafOffsets[s];
2622: }
2623: }
2625: /* Renumber and concatenate remote roots */
2626: if (rootMode == PETSCSF_CONCATENATE_ROOTMODE_LOCAL || rootMode == PETSCSF_CONCATENATE_ROOTMODE_SHARED) {
2627: PetscInt rootOffset = 0;
2629: PetscCall(PetscMalloc1(nLeaves, &iremote_new));
2630: for (i = 0; i < nLeaves; i++) {
2631: iremote_new[i].rank = -1;
2632: iremote_new[i].index = -1;
2633: }
2634: for (s = 0; s < nsfs; s++) {
2635: PetscInt i, nl, nr;
2636: PetscSF tmp_sf;
2637: const PetscSFNode *iremote;
2638: PetscSFNode *tmp_rootdata;
2639: PetscSFNode *tmp_leafdata = PetscSafePointerPlusOffset(iremote_new, leafArrayOffsets[s]);
2641: PetscCall(PetscSFGetGraph(sfs[s], &nr, &nl, NULL, &iremote));
2642: PetscCall(PetscSFCreate(comm, &tmp_sf));
2643: /* create helper SF with contiguous leaves */
2644: PetscCall(PetscSFSetGraph(tmp_sf, nr, nl, NULL, PETSC_USE_POINTER, (PetscSFNode *)iremote, PETSC_COPY_VALUES));
2645: PetscCall(PetscSFSetUp(tmp_sf));
2646: PetscCall(PetscMalloc1(nr, &tmp_rootdata));
2647: if (rootMode == PETSCSF_CONCATENATE_ROOTMODE_LOCAL) {
2648: for (i = 0; i < nr; i++) {
2649: tmp_rootdata[i].index = i + rootOffset;
2650: tmp_rootdata[i].rank = rank;
2651: }
2652: rootOffset += nr;
2653: } else {
2654: for (i = 0; i < nr; i++) {
2655: tmp_rootdata[i].index = i;
2656: tmp_rootdata[i].rank = rank;
2657: }
2658: }
2659: PetscCall(PetscSFBcastBegin(tmp_sf, MPIU_SF_NODE, tmp_rootdata, tmp_leafdata, MPI_REPLACE));
2660: PetscCall(PetscSFBcastEnd(tmp_sf, MPIU_SF_NODE, tmp_rootdata, tmp_leafdata, MPI_REPLACE));
2661: PetscCall(PetscSFDestroy(&tmp_sf));
2662: PetscCall(PetscFree(tmp_rootdata));
2663: }
2664: if (rootMode == PETSCSF_CONCATENATE_ROOTMODE_LOCAL) nRoots = rootOffset; // else nRoots already calculated above
2666: /* Build the new SF */
2667: PetscCall(PetscSFCreate(comm, newsf));
2668: PetscCall(PetscSFSetGraph(*newsf, nRoots, nLeaves, ilocal_new, PETSC_OWN_POINTER, iremote_new, PETSC_OWN_POINTER));
2669: } else {
2670: /* Build the new SF */
2671: PetscCall(PetscSFCreate(comm, newsf));
2672: PetscCall(PetscSFSetGraphLayout(*newsf, glayout, nLeaves, ilocal_new, PETSC_OWN_POINTER, gremote));
2673: }
2674: PetscCall(PetscSFSetUp(*newsf));
2675: PetscCall(PetscSFViewFromOptions(*newsf, NULL, "-sf_concat_view"));
2676: PetscCall(PetscLayoutDestroy(&glayout));
2677: PetscCall(PetscFree(gremote));
2678: PetscCall(PetscFree(leafArrayOffsets));
2679: PetscFunctionReturn(PETSC_SUCCESS);
2680: }
2682: /*@
2683: PetscSFRegisterPersistent - Register root and leaf data as memory regions that will be used for repeated `PetscSF` communications.
2685: Collective
2687: Input Parameters:
2688: + sf - star forest
2689: . unit - the data type contained within `rootdata` and `leafdata`
2690: . rootdata - root data that will be used for multiple `PetscSF` communications
2691: - leafdata - leaf data that will be used for multiple `PetscSF` communications
2693: Level: advanced
2695: Notes:
2696: Implementations of `PetscSF` can make optimizations
2697: for repeated communication using the same memory regions, but these optimizations
2698: can be unsound if `rootdata` or `leafdata` is deallocated and the `PetscSF` is not informed.
2699: The intended pattern is
2701: .vb
2702: PetscMalloc2(nroots, &rootdata, nleaves, &leafdata);
2704: PetscSFRegisterPersistent(sf, unit, rootdata, leafdata);
2705: // repeated use of rootdata and leafdata will now be optimized
2707: PetscSFBcastBegin(sf, unit, rootdata, leafdata, MPI_REPLACE);
2708: PetscSFBcastEnd(sf, unit, rootdata, leafdata, MPI_REPLACE);
2709: // ...
2710: PetscSFReduceBegin(sf, unit, leafdata, rootdata, MPI_SUM);
2711: PetscSFReduceEnd(sf, unit, leafdata, rootdata, MPI_SUM);
2712: // ... (other communications)
2714: // rootdata and leafdata must be deregistered before freeing
2715: // skipping this can lead to undefined behavior including
2716: // deadlocks
2717: PetscSFDeregisterPersistent(sf, unit, rootdata, leafdata);
2719: // it is now safe to free rootdata and leafdata
2720: PetscFree2(rootdata, leafdata);
2721: .ve
2723: If you do not register `rootdata` and `leafdata` it will not cause an error,
2724: but optimizations that reduce the setup time for each communication cannot be
2725: made. Currently, the only implementation of `PetscSF` that benefits from
2726: `PetscSFRegisterPersistent()` is `PETSCSFWINDOW`. For the default
2727: `PETSCSFBASIC` there is no benefit to using `PetscSFRegisterPersistent()`.
2729: .seealso: [](sec_petscsf), `PetscSF`, `PETSCSFWINDOW`, `PetscSFDeregisterPersistent()`
2730: @*/
2731: PetscErrorCode PetscSFRegisterPersistent(PetscSF sf, MPI_Datatype unit, const void *rootdata, const void *leafdata)
2732: {
2733: PetscFunctionBegin;
2735: PetscTryMethod(sf, "PetscSFRegisterPersistent_C", (PetscSF, MPI_Datatype, const void *, const void *), (sf, unit, rootdata, leafdata));
2736: PetscFunctionReturn(PETSC_SUCCESS);
2737: }
2739: /*@
2740: PetscSFDeregisterPersistent - Signal that repeated usage of `rootdata` and `leafdata` for `PetscSF` communication has concluded.
2742: Collective
2744: Input Parameters:
2745: + sf - star forest
2746: . unit - the data type contained within the `rootdata` and `leafdata`
2747: . rootdata - root data that was previously registered with `PetscSFRegisterPersistent()`
2748: - leafdata - leaf data that was previously registered with `PetscSFRegisterPersistent()`
2750: Level: advanced
2752: Note:
2753: See `PetscSFRegisterPersistent()` for when and how to use this function.
2755: .seealso: [](sec_petscsf), `PetscSF`, `PETSCSFWINDOW`, `PetscSFRegisterPersistent()`
2756: @*/
2757: PetscErrorCode PetscSFDeregisterPersistent(PetscSF sf, MPI_Datatype unit, const void *rootdata, const void *leafdata)
2758: {
2759: PetscFunctionBegin;
2761: PetscTryMethod(sf, "PetscSFDeregisterPersistent_C", (PetscSF, MPI_Datatype, const void *, const void *), (sf, unit, rootdata, leafdata));
2762: PetscFunctionReturn(PETSC_SUCCESS);
2763: }
2765: PETSC_INTERN PetscErrorCode PetscSFGetDatatypeSize_Internal(MPI_Comm comm, MPI_Datatype unit, MPI_Aint *size)
2766: {
2767: MPI_Aint lb, lb_true, bytes, bytes_true;
2769: PetscFunctionBegin;
2770: PetscCallMPI(MPI_Type_get_extent(unit, &lb, &bytes));
2771: PetscCallMPI(MPI_Type_get_true_extent(unit, &lb_true, &bytes_true));
2772: PetscCheck(lb == 0 && lb_true == 0, comm, PETSC_ERR_SUP, "No support for unit type with nonzero lower bound, write petsc-maint@mcs.anl.gov if you want this feature");
2773: *size = bytes;
2774: PetscFunctionReturn(PETSC_SUCCESS);
2775: }