Actual source code: plexdistribute.c

petsc-3.9.2 2018-05-20
Report Typos and Errors
  1:  #include <petsc/private/dmpleximpl.h>
  2:  #include <petsc/private/dmlabelimpl.h>

  4: /*@C
  5:   DMPlexSetAdjacencyUser - Define adjacency in the mesh using a user-provided callback

  7:   Input Parameters:
  8: + dm      - The DM object
  9: . user    - The user callback, may be NULL (to clear the callback)
 10: - ctx     - context for callback evaluation, may be NULL

 12:   Level: advanced

 14:   Notes:
 15:      The caller of DMPlexGetAdjacency may need to arrange that a large enough array is available for the adjacency.

 17:      Any setting here overrides other configuration of DMPlex adjacency determination.

 19: .seealso: DMPlexSetAdjacencyUseCone(), DMPlexSetAdjacencyUseClosure(), DMPlexDistribute(), DMPlexPreallocateOperator(), DMPlexGetAdjacency(), DMPlexGetAdjacencyUser()
 20: @*/
 21: PetscErrorCode DMPlexSetAdjacencyUser(DM dm,PetscErrorCode (*user)(DM,PetscInt,PetscInt*,PetscInt[],void*),void *ctx)
 22: {
 23:   DM_Plex *mesh = (DM_Plex *)dm->data;

 27:   mesh->useradjacency = user;
 28:   mesh->useradjacencyctx = ctx;
 29:   return(0);
 30: }

 32: /*@C
 33:   DMPlexGetAdjacencyUser - get the user-defined adjacency callback

 35:   Input Parameter:
 36: . dm      - The DM object

 38:   Output Parameters:
 39: - user    - The user callback
 40: - ctx     - context for callback evaluation

 42:   Level: advanced

 44: .seealso: DMPlexSetAdjacencyUseCone(), DMPlexSetAdjacencyUseClosure(), DMPlexDistribute(), DMPlexPreallocateOperator(), DMPlexGetAdjacency(), DMPlexSetAdjacencyUser()
 45: @*/
 46: PetscErrorCode DMPlexGetAdjacencyUser(DM dm, PetscErrorCode (**user)(DM,PetscInt,PetscInt*,PetscInt[],void*), void **ctx)
 47: {
 48:   DM_Plex *mesh = (DM_Plex *)dm->data;

 52:   if (user) *user = mesh->useradjacency;
 53:   if (ctx) *ctx = mesh->useradjacencyctx;
 54:   return(0);
 55: }

 57: /*@
 58:   DMPlexSetAdjacencyUseCone - Define adjacency in the mesh using either the cone or the support first

 60:   Input Parameters:
 61: + dm      - The DM object
 62: - useCone - Flag to use the cone first

 64:   Level: intermediate

 66:   Notes:
 67: $     FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
 68: $     FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
 69: $     FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE

 71: .seealso: DMPlexGetAdjacencyUseCone(), DMPlexSetAdjacencyUseClosure(), DMPlexGetAdjacencyUseClosure(), DMPlexDistribute(), DMPlexPreallocateOperator()
 72: @*/
 73: PetscErrorCode DMPlexSetAdjacencyUseCone(DM dm, PetscBool useCone)
 74: {
 75:   PetscDS        prob;
 76:   PetscBool      useClosure;
 77:   PetscInt       Nf;

 81:   DMGetDS(dm, &prob);
 82:   PetscDSGetNumFields(prob, &Nf);
 83:   if (!Nf) {
 84:     PetscDSGetAdjacency(prob, PETSC_DEFAULT, NULL, &useClosure);
 85:     PetscDSSetAdjacency(prob, PETSC_DEFAULT, useCone, useClosure);
 86:   } else {
 87:     PetscDSGetAdjacency(prob, 0, NULL, &useClosure);
 88:     PetscDSSetAdjacency(prob, 0, useCone, useClosure);
 89:   }
 90:   return(0);
 91: }

 93: /*@
 94:   DMPlexGetAdjacencyUseCone - Query whether adjacency in the mesh uses the cone or the support first

 96:   Input Parameter:
 97: . dm      - The DM object

 99:   Output Parameter:
100: . useCone - Flag to use the cone first

102:   Level: intermediate

104:   Notes:
105: $     FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
106: $     FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
107: $     FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE

109: .seealso: DMPlexSetAdjacencyUseCone(), DMPlexSetAdjacencyUseClosure(), DMPlexGetAdjacencyUseClosure(), DMPlexDistribute(), DMPlexPreallocateOperator()
110: @*/
111: PetscErrorCode DMPlexGetAdjacencyUseCone(DM dm, PetscBool *useCone)
112: {
113:   PetscDS        prob;
114:   PetscInt       Nf;

118:   DMGetDS(dm, &prob);
119:   PetscDSGetNumFields(prob, &Nf);
120:   if (!Nf) {
121:     PetscDSGetAdjacency(prob, PETSC_DEFAULT, useCone, NULL);
122:   } else {
123:     PetscDSGetAdjacency(prob, 0, useCone, NULL);
124:   }
125:   return(0);
126: }

128: /*@
129:   DMPlexSetAdjacencyUseClosure - Define adjacency in the mesh using the transitive closure

131:   Input Parameters:
132: + dm      - The DM object
133: - useClosure - Flag to use the closure

135:   Level: intermediate

137:   Notes:
138: $     FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
139: $     FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
140: $     FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE

142: .seealso: DMPlexGetAdjacencyUseClosure(), DMPlexSetAdjacencyUseCone(), DMPlexGetAdjacencyUseCone(), DMPlexDistribute(), DMPlexPreallocateOperator()
143: @*/
144: PetscErrorCode DMPlexSetAdjacencyUseClosure(DM dm, PetscBool useClosure)
145: {
146:   PetscDS        prob;
147:   PetscBool      useCone;
148:   PetscInt       Nf;

152:   DMGetDS(dm, &prob);
153:   PetscDSGetNumFields(prob, &Nf);
154:   if (!Nf) {
155:     PetscDSGetAdjacency(prob, PETSC_DEFAULT, &useCone, NULL);
156:     PetscDSSetAdjacency(prob, PETSC_DEFAULT, useCone, useClosure);
157:   } else {
158:     PetscDSGetAdjacency(prob, 0, &useCone, NULL);
159:     PetscDSSetAdjacency(prob, 0, useCone, useClosure);
160:   }
161:   return(0);
162: }

164: /*@
165:   DMPlexGetAdjacencyUseClosure - Query whether adjacency in the mesh uses the transitive closure

167:   Input Parameter:
168: . dm      - The DM object

170:   Output Parameter:
171: . useClosure - Flag to use the closure

173:   Level: intermediate

175:   Notes:
176: $     FEM:   Two points p and q are adjacent if q \in closure(star(p)),   useCone = PETSC_FALSE, useClosure = PETSC_TRUE
177: $     FVM:   Two points p and q are adjacent if q \in support(p+cone(p)), useCone = PETSC_TRUE,  useClosure = PETSC_FALSE
178: $     FVM++: Two points p and q are adjacent if q \in star(closure(p)),   useCone = PETSC_TRUE,  useClosure = PETSC_TRUE

180: .seealso: DMPlexSetAdjacencyUseClosure(), DMPlexSetAdjacencyUseCone(), DMPlexGetAdjacencyUseCone(), DMPlexDistribute(), DMPlexPreallocateOperator()
181: @*/
182: PetscErrorCode DMPlexGetAdjacencyUseClosure(DM dm, PetscBool *useClosure)
183: {
184:   PetscDS        prob;
185:   PetscInt       Nf;

189:   DMGetDS(dm, &prob);
190:   PetscDSGetNumFields(prob, &Nf);
191:   if (!Nf) {
192:     PetscDSGetAdjacency(prob, PETSC_DEFAULT, NULL, useClosure);
193:   } else {
194:     PetscDSGetAdjacency(prob, 0, NULL, useClosure);
195:   }
196:   return(0);
197: }

199: /*@
200:   DMPlexSetAdjacencyUseAnchors - Define adjacency in the mesh using the point-to-point constraints.

202:   Input Parameters:
203: + dm      - The DM object
204: - useAnchors - Flag to use the constraints.  If PETSC_TRUE, then constrained points are omitted from DMPlexGetAdjacency(), and their anchor points appear in their place.

206:   Level: intermediate

208: .seealso: DMPlexGetAdjacencyUseClosure(), DMPlexSetAdjacencyUseCone(), DMPlexGetAdjacencyUseCone(), DMPlexDistribute(), DMPlexPreallocateOperator(), DMPlexSetAnchors()
209: @*/
210: PetscErrorCode DMPlexSetAdjacencyUseAnchors(DM dm, PetscBool useAnchors)
211: {
212:   DM_Plex *mesh = (DM_Plex *) dm->data;

216:   mesh->useAnchors = useAnchors;
217:   return(0);
218: }

220: /*@
221:   DMPlexGetAdjacencyUseAnchors - Query whether adjacency in the mesh uses the point-to-point constraints.

223:   Input Parameter:
224: . dm      - The DM object

226:   Output Parameter:
227: . useAnchors - Flag to use the closure.  If PETSC_TRUE, then constrained points are omitted from DMPlexGetAdjacency(), and their anchor points appear in their place.

229:   Level: intermediate

231: .seealso: DMPlexSetAdjacencyUseAnchors(), DMPlexSetAdjacencyUseCone(), DMPlexGetAdjacencyUseCone(), DMPlexDistribute(), DMPlexPreallocateOperator(), DMPlexSetAnchors()
232: @*/
233: PetscErrorCode DMPlexGetAdjacencyUseAnchors(DM dm, PetscBool *useAnchors)
234: {
235:   DM_Plex *mesh = (DM_Plex *) dm->data;

240:   *useAnchors = mesh->useAnchors;
241:   return(0);
242: }

244: static PetscErrorCode DMPlexGetAdjacency_Cone_Internal(DM dm, PetscInt p, PetscInt *adjSize, PetscInt adj[])
245: {
246:   const PetscInt *cone = NULL;
247:   PetscInt        numAdj = 0, maxAdjSize = *adjSize, coneSize, c;
248:   PetscErrorCode  ierr;

251:   DMPlexGetConeSize(dm, p, &coneSize);
252:   DMPlexGetCone(dm, p, &cone);
253:   for (c = 0; c <= coneSize; ++c) {
254:     const PetscInt  point   = !c ? p : cone[c-1];
255:     const PetscInt *support = NULL;
256:     PetscInt        supportSize, s, q;

258:     DMPlexGetSupportSize(dm, point, &supportSize);
259:     DMPlexGetSupport(dm, point, &support);
260:     for (s = 0; s < supportSize; ++s) {
261:       for (q = 0; q < numAdj || ((void)(adj[numAdj++] = support[s]),0); ++q) {
262:         if (support[s] == adj[q]) break;
263:       }
264:       if (numAdj > maxAdjSize) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid mesh exceeded adjacency allocation (%D)", maxAdjSize);
265:     }
266:   }
267:   *adjSize = numAdj;
268:   return(0);
269: }

271: static PetscErrorCode DMPlexGetAdjacency_Support_Internal(DM dm, PetscInt p, PetscInt *adjSize, PetscInt adj[])
272: {
273:   const PetscInt *support = NULL;
274:   PetscInt        numAdj   = 0, maxAdjSize = *adjSize, supportSize, s;
275:   PetscErrorCode  ierr;

278:   DMPlexGetSupportSize(dm, p, &supportSize);
279:   DMPlexGetSupport(dm, p, &support);
280:   for (s = 0; s <= supportSize; ++s) {
281:     const PetscInt  point = !s ? p : support[s-1];
282:     const PetscInt *cone  = NULL;
283:     PetscInt        coneSize, c, q;

285:     DMPlexGetConeSize(dm, point, &coneSize);
286:     DMPlexGetCone(dm, point, &cone);
287:     for (c = 0; c < coneSize; ++c) {
288:       for (q = 0; q < numAdj || ((void)(adj[numAdj++] = cone[c]),0); ++q) {
289:         if (cone[c] == adj[q]) break;
290:       }
291:       if (numAdj > maxAdjSize) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid mesh exceeded adjacency allocation (%D)", maxAdjSize);
292:     }
293:   }
294:   *adjSize = numAdj;
295:   return(0);
296: }

298: static PetscErrorCode DMPlexGetAdjacency_Transitive_Internal(DM dm, PetscInt p, PetscBool useClosure, PetscInt *adjSize, PetscInt adj[])
299: {
300:   PetscInt      *star = NULL;
301:   PetscInt       numAdj = 0, maxAdjSize = *adjSize, starSize, s;

305:   DMPlexGetTransitiveClosure(dm, p, useClosure, &starSize, &star);
306:   for (s = 0; s < starSize*2; s += 2) {
307:     const PetscInt *closure = NULL;
308:     PetscInt        closureSize, c, q;

310:     DMPlexGetTransitiveClosure(dm, star[s], (PetscBool)!useClosure, &closureSize, (PetscInt**) &closure);
311:     for (c = 0; c < closureSize*2; c += 2) {
312:       for (q = 0; q < numAdj || ((void)(adj[numAdj++] = closure[c]),0); ++q) {
313:         if (closure[c] == adj[q]) break;
314:       }
315:       if (numAdj > maxAdjSize) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid mesh exceeded adjacency allocation (%D)", maxAdjSize);
316:     }
317:     DMPlexRestoreTransitiveClosure(dm, star[s], (PetscBool)!useClosure, &closureSize, (PetscInt**) &closure);
318:   }
319:   DMPlexRestoreTransitiveClosure(dm, p, useClosure, &starSize, &star);
320:   *adjSize = numAdj;
321:   return(0);
322: }

324: PetscErrorCode DMPlexGetAdjacency_Internal(DM dm, PetscInt p, PetscBool useCone, PetscBool useTransitiveClosure, PetscBool useAnchors, PetscInt *adjSize, PetscInt *adj[])
325: {
326:   static PetscInt asiz = 0;
327:   PetscInt maxAnchors = 1;
328:   PetscInt aStart = -1, aEnd = -1;
329:   PetscInt maxAdjSize;
330:   PetscSection aSec = NULL;
331:   IS aIS = NULL;
332:   const PetscInt *anchors;
333:   DM_Plex *mesh = (DM_Plex *)dm->data;
334:   PetscErrorCode  ierr;

337:   if (useAnchors) {
338:     DMPlexGetAnchors(dm,&aSec,&aIS);
339:     if (aSec) {
340:       PetscSectionGetMaxDof(aSec,&maxAnchors);
341:       maxAnchors = PetscMax(1,maxAnchors);
342:       PetscSectionGetChart(aSec,&aStart,&aEnd);
343:       ISGetIndices(aIS,&anchors);
344:     }
345:   }
346:   if (!*adj) {
347:     PetscInt depth, coneSeries, supportSeries, maxC, maxS, pStart, pEnd;

349:     DMPlexGetChart(dm, &pStart,&pEnd);
350:     DMPlexGetDepth(dm, &depth);
351:     DMPlexGetMaxSizes(dm, &maxC, &maxS);
352:     coneSeries    = (maxC > 1) ? ((PetscPowInt(maxC,depth+1)-1)/(maxC-1)) : depth+1;
353:     supportSeries = (maxS > 1) ? ((PetscPowInt(maxS,depth+1)-1)/(maxS-1)) : depth+1;
354:     asiz  = PetscMax(PetscPowInt(maxS,depth)*coneSeries,PetscPowInt(maxC,depth)*supportSeries);
355:     asiz *= maxAnchors;
356:     asiz  = PetscMin(asiz,pEnd-pStart);
357:     PetscMalloc1(asiz,adj);
358:   }
359:   if (*adjSize < 0) *adjSize = asiz;
360:   maxAdjSize = *adjSize;
361:   if (mesh->useradjacency) {
362:     mesh->useradjacency(dm, p, adjSize, *adj, mesh->useradjacencyctx);
363:   } else if (useTransitiveClosure) {
364:     DMPlexGetAdjacency_Transitive_Internal(dm, p, useCone, adjSize, *adj);
365:   } else if (useCone) {
366:     DMPlexGetAdjacency_Cone_Internal(dm, p, adjSize, *adj);
367:   } else {
368:     DMPlexGetAdjacency_Support_Internal(dm, p, adjSize, *adj);
369:   }
370:   if (useAnchors && aSec) {
371:     PetscInt origSize = *adjSize;
372:     PetscInt numAdj = origSize;
373:     PetscInt i = 0, j;
374:     PetscInt *orig = *adj;

376:     while (i < origSize) {
377:       PetscInt p = orig[i];
378:       PetscInt aDof = 0;

380:       if (p >= aStart && p < aEnd) {
381:         PetscSectionGetDof(aSec,p,&aDof);
382:       }
383:       if (aDof) {
384:         PetscInt aOff;
385:         PetscInt s, q;

387:         for (j = i + 1; j < numAdj; j++) {
388:           orig[j - 1] = orig[j];
389:         }
390:         origSize--;
391:         numAdj--;
392:         PetscSectionGetOffset(aSec,p,&aOff);
393:         for (s = 0; s < aDof; ++s) {
394:           for (q = 0; q < numAdj || ((void)(orig[numAdj++] = anchors[aOff+s]),0); ++q) {
395:             if (anchors[aOff+s] == orig[q]) break;
396:           }
397:           if (numAdj > maxAdjSize) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid mesh exceeded adjacency allocation (%D)", maxAdjSize);
398:         }
399:       }
400:       else {
401:         i++;
402:       }
403:     }
404:     *adjSize = numAdj;
405:     ISRestoreIndices(aIS,&anchors);
406:   }
407:   return(0);
408: }

410: /*@
411:   DMPlexGetAdjacency - Return all points adjacent to the given point

413:   Input Parameters:
414: + dm - The DM object
415: . p  - The point
416: . adjSize - The maximum size of adj if it is non-NULL, or PETSC_DETERMINE
417: - adj - Either NULL so that the array is allocated, or an existing array with size adjSize

419:   Output Parameters:
420: + adjSize - The number of adjacent points
421: - adj - The adjacent points

423:   Level: advanced

425:   Notes: The user must PetscFree the adj array if it was not passed in.

427: .seealso: DMPlexSetAdjacencyUseCone(), DMPlexSetAdjacencyUseClosure(), DMPlexDistribute(), DMCreateMatrix(), DMPlexPreallocateOperator()
428: @*/
429: PetscErrorCode DMPlexGetAdjacency(DM dm, PetscInt p, PetscInt *adjSize, PetscInt *adj[])
430: {
431:   PetscBool      useCone, useClosure, useAnchors;

438:   DMPlexGetAdjacencyUseCone(dm, &useCone);
439:   DMPlexGetAdjacencyUseClosure(dm, &useClosure);
440:   DMPlexGetAdjacencyUseAnchors(dm, &useAnchors);
441:   DMPlexGetAdjacency_Internal(dm, p, useCone, useClosure, useAnchors, adjSize, adj);
442:   return(0);
443: }

445: /*@
446:   DMPlexCreateTwoSidedProcessSF - Create an SF which just has process connectivity

448:   Collective on DM

450:   Input Parameters:
451: + dm      - The DM
452: - sfPoint - The PetscSF which encodes point connectivity

454:   Output Parameters:
455: + processRanks - A list of process neighbors, or NULL
456: - sfProcess    - An SF encoding the two-sided process connectivity, or NULL

458:   Level: developer

460: .seealso: PetscSFCreate(), DMPlexCreateProcessSF()
461: @*/
462: PetscErrorCode DMPlexCreateTwoSidedProcessSF(DM dm, PetscSF sfPoint, PetscSection rootRankSection, IS rootRanks, PetscSection leafRankSection, IS leafRanks, IS *processRanks, PetscSF *sfProcess)
463: {
464:   const PetscSFNode *remotePoints;
465:   PetscInt          *localPointsNew;
466:   PetscSFNode       *remotePointsNew;
467:   const PetscInt    *nranks;
468:   PetscInt          *ranksNew;
469:   PetscBT            neighbors;
470:   PetscInt           pStart, pEnd, p, numLeaves, l, numNeighbors, n;
471:   PetscMPIInt        size, proc, rank;
472:   PetscErrorCode     ierr;

479:   MPI_Comm_size(PetscObjectComm((PetscObject) dm), &size);
480:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
481:   PetscSFGetGraph(sfPoint, NULL, &numLeaves, NULL, &remotePoints);
482:   PetscBTCreate(size, &neighbors);
483:   PetscBTMemzero(size, neighbors);
484:   /* Compute root-to-leaf process connectivity */
485:   PetscSectionGetChart(rootRankSection, &pStart, &pEnd);
486:   ISGetIndices(rootRanks, &nranks);
487:   for (p = pStart; p < pEnd; ++p) {
488:     PetscInt ndof, noff, n;

490:     PetscSectionGetDof(rootRankSection, p, &ndof);
491:     PetscSectionGetOffset(rootRankSection, p, &noff);
492:     for (n = 0; n < ndof; ++n) {PetscBTSet(neighbors, nranks[noff+n]);}
493:   }
494:   ISRestoreIndices(rootRanks, &nranks);
495:   /* Compute leaf-to-neighbor process connectivity */
496:   PetscSectionGetChart(leafRankSection, &pStart, &pEnd);
497:   ISGetIndices(leafRanks, &nranks);
498:   for (p = pStart; p < pEnd; ++p) {
499:     PetscInt ndof, noff, n;

501:     PetscSectionGetDof(leafRankSection, p, &ndof);
502:     PetscSectionGetOffset(leafRankSection, p, &noff);
503:     for (n = 0; n < ndof; ++n) {PetscBTSet(neighbors, nranks[noff+n]);}
504:   }
505:   ISRestoreIndices(leafRanks, &nranks);
506:   /* Compute leaf-to-root process connectivity */
507:   for (l = 0; l < numLeaves; ++l) {PetscBTSet(neighbors, remotePoints[l].rank);}
508:   /* Calculate edges */
509:   PetscBTClear(neighbors, rank);
510:   for(proc = 0, numNeighbors = 0; proc < size; ++proc) {if (PetscBTLookup(neighbors, proc)) ++numNeighbors;}
511:   PetscMalloc1(numNeighbors, &ranksNew);
512:   PetscMalloc1(numNeighbors, &localPointsNew);
513:   PetscMalloc1(numNeighbors, &remotePointsNew);
514:   for(proc = 0, n = 0; proc < size; ++proc) {
515:     if (PetscBTLookup(neighbors, proc)) {
516:       ranksNew[n]              = proc;
517:       localPointsNew[n]        = proc;
518:       remotePointsNew[n].index = rank;
519:       remotePointsNew[n].rank  = proc;
520:       ++n;
521:     }
522:   }
523:   PetscBTDestroy(&neighbors);
524:   if (processRanks) {ISCreateGeneral(PetscObjectComm((PetscObject)dm), numNeighbors, ranksNew, PETSC_OWN_POINTER, processRanks);}
525:   else              {PetscFree(ranksNew);}
526:   if (sfProcess) {
527:     PetscSFCreate(PetscObjectComm((PetscObject)dm), sfProcess);
528:     PetscObjectSetName((PetscObject) *sfProcess, "Two-Sided Process SF");
529:     PetscSFSetFromOptions(*sfProcess);
530:     PetscSFSetGraph(*sfProcess, size, numNeighbors, localPointsNew, PETSC_OWN_POINTER, remotePointsNew, PETSC_OWN_POINTER);
531:   }
532:   return(0);
533: }

535: /*@
536:   DMPlexDistributeOwnership - Compute owner information for shared points. This basically gets two-sided for an SF.

538:   Collective on DM

540:   Input Parameter:
541: . dm - The DM

543:   Output Parameters:
544: + rootSection - The number of leaves for a given root point
545: . rootrank    - The rank of each edge into the root point
546: . leafSection - The number of processes sharing a given leaf point
547: - leafrank    - The rank of each process sharing a leaf point

549:   Level: developer

551: .seealso: DMPlexCreateOverlap()
552: @*/
553: PetscErrorCode DMPlexDistributeOwnership(DM dm, PetscSection rootSection, IS *rootrank, PetscSection leafSection, IS *leafrank)
554: {
555:   MPI_Comm        comm;
556:   PetscSF         sfPoint;
557:   const PetscInt *rootdegree;
558:   PetscInt       *myrank, *remoterank;
559:   PetscInt        pStart, pEnd, p, nedges;
560:   PetscMPIInt     rank;
561:   PetscErrorCode  ierr;

564:   PetscObjectGetComm((PetscObject) dm, &comm);
565:   MPI_Comm_rank(comm, &rank);
566:   DMPlexGetChart(dm, &pStart, &pEnd);
567:   DMGetPointSF(dm, &sfPoint);
568:   /* Compute number of leaves for each root */
569:   PetscObjectSetName((PetscObject) rootSection, "Root Section");
570:   PetscSectionSetChart(rootSection, pStart, pEnd);
571:   PetscSFComputeDegreeBegin(sfPoint, &rootdegree);
572:   PetscSFComputeDegreeEnd(sfPoint, &rootdegree);
573:   for (p = pStart; p < pEnd; ++p) {PetscSectionSetDof(rootSection, p, rootdegree[p-pStart]);}
574:   PetscSectionSetUp(rootSection);
575:   /* Gather rank of each leaf to root */
576:   PetscSectionGetStorageSize(rootSection, &nedges);
577:   PetscMalloc1(pEnd-pStart, &myrank);
578:   PetscMalloc1(nedges,  &remoterank);
579:   for (p = 0; p < pEnd-pStart; ++p) myrank[p] = rank;
580:   PetscSFGatherBegin(sfPoint, MPIU_INT, myrank, remoterank);
581:   PetscSFGatherEnd(sfPoint, MPIU_INT, myrank, remoterank);
582:   PetscFree(myrank);
583:   ISCreateGeneral(comm, nedges, remoterank, PETSC_OWN_POINTER, rootrank);
584:   /* Distribute remote ranks to leaves */
585:   PetscObjectSetName((PetscObject) leafSection, "Leaf Section");
586:   DMPlexDistributeFieldIS(dm, sfPoint, rootSection, *rootrank, leafSection, leafrank);
587:   return(0);
588: }

590: /*@C
591:   DMPlexCreateOverlap - Compute owner information for shared points. This basically gets two-sided for an SF.

593:   Collective on DM

595:   Input Parameters:
596: + dm          - The DM
597: . levels      - Number of overlap levels
598: . rootSection - The number of leaves for a given root point
599: . rootrank    - The rank of each edge into the root point
600: . leafSection - The number of processes sharing a given leaf point
601: - leafrank    - The rank of each process sharing a leaf point

603:   Output Parameters:
604: + ovLabel     - DMLabel containing remote overlap contributions as point/rank pairings

606:   Level: developer

608: .seealso: DMPlexDistributeOwnership(), DMPlexDistribute()
609: @*/
610: PetscErrorCode DMPlexCreateOverlap(DM dm, PetscInt levels, PetscSection rootSection, IS rootrank, PetscSection leafSection, IS leafrank, DMLabel *ovLabel)
611: {
612:   MPI_Comm           comm;
613:   DMLabel            ovAdjByRank; /* A DMLabel containing all points adjacent to shared points, separated by rank (value in label) */
614:   PetscSF            sfPoint, sfProc;
615:   const PetscSFNode *remote;
616:   const PetscInt    *local;
617:   const PetscInt    *nrank, *rrank;
618:   PetscInt          *adj = NULL;
619:   PetscInt           pStart, pEnd, p, sStart, sEnd, nleaves, l;
620:   PetscMPIInt        rank, size;
621:   PetscBool          useCone, useClosure, flg;
622:   PetscErrorCode     ierr;

625:   PetscObjectGetComm((PetscObject) dm, &comm);
626:   MPI_Comm_size(comm, &size);
627:   MPI_Comm_rank(comm, &rank);
628:   DMGetPointSF(dm, &sfPoint);
629:   DMPlexGetChart(dm, &pStart, &pEnd);
630:   PetscSectionGetChart(leafSection, &sStart, &sEnd);
631:   PetscSFGetGraph(sfPoint, NULL, &nleaves, &local, &remote);
632:   DMLabelCreate("Overlap adjacency", &ovAdjByRank);
633:   /* Handle leaves: shared with the root point */
634:   for (l = 0; l < nleaves; ++l) {
635:     PetscInt adjSize = PETSC_DETERMINE, a;

637:     DMPlexGetAdjacency(dm, local[l], &adjSize, &adj);
638:     for (a = 0; a < adjSize; ++a) {DMLabelSetValue(ovAdjByRank, adj[a], remote[l].rank);}
639:   }
640:   ISGetIndices(rootrank, &rrank);
641:   ISGetIndices(leafrank, &nrank);
642:   /* Handle roots */
643:   for (p = pStart; p < pEnd; ++p) {
644:     PetscInt adjSize = PETSC_DETERMINE, neighbors = 0, noff, n, a;

646:     if ((p >= sStart) && (p < sEnd)) {
647:       /* Some leaves share a root with other leaves on different processes */
648:       PetscSectionGetDof(leafSection, p, &neighbors);
649:       if (neighbors) {
650:         PetscSectionGetOffset(leafSection, p, &noff);
651:         DMPlexGetAdjacency(dm, p, &adjSize, &adj);
652:         for (n = 0; n < neighbors; ++n) {
653:           const PetscInt remoteRank = nrank[noff+n];

655:           if (remoteRank == rank) continue;
656:           for (a = 0; a < adjSize; ++a) {DMLabelSetValue(ovAdjByRank, adj[a], remoteRank);}
657:         }
658:       }
659:     }
660:     /* Roots are shared with leaves */
661:     PetscSectionGetDof(rootSection, p, &neighbors);
662:     if (!neighbors) continue;
663:     PetscSectionGetOffset(rootSection, p, &noff);
664:     DMPlexGetAdjacency(dm, p, &adjSize, &adj);
665:     for (n = 0; n < neighbors; ++n) {
666:       const PetscInt remoteRank = rrank[noff+n];

668:       if (remoteRank == rank) continue;
669:       for (a = 0; a < adjSize; ++a) {DMLabelSetValue(ovAdjByRank, adj[a], remoteRank);}
670:     }
671:   }
672:   PetscFree(adj);
673:   ISRestoreIndices(rootrank, &rrank);
674:   ISRestoreIndices(leafrank, &nrank);
675:   /* Add additional overlap levels */
676:   for (l = 1; l < levels; l++) {
677:     /* Propagate point donations over SF to capture remote connections */
678:     DMPlexPartitionLabelPropagate(dm, ovAdjByRank);
679:     /* Add next level of point donations to the label */
680:     DMPlexPartitionLabelAdjacency(dm, ovAdjByRank);
681:   }
682:   /* We require the closure in the overlap */
683:   DMPlexGetAdjacencyUseCone(dm, &useCone);
684:   DMPlexGetAdjacencyUseClosure(dm, &useClosure);
685:   if (useCone || !useClosure) {
686:     DMPlexPartitionLabelClosure(dm, ovAdjByRank);
687:   }
688:   PetscOptionsHasName(((PetscObject) dm)->options,((PetscObject) dm)->prefix, "-overlap_view", &flg);
689:   if (flg) {
690:     DMLabelView(ovAdjByRank, PETSC_VIEWER_STDOUT_WORLD);
691:   }
692:   /* Make global process SF and invert sender to receiver label */
693:   {
694:     /* Build a global process SF */
695:     PetscSFNode *remoteProc;
696:     PetscMalloc1(size, &remoteProc);
697:     for (p = 0; p < size; ++p) {
698:       remoteProc[p].rank  = p;
699:       remoteProc[p].index = rank;
700:     }
701:     PetscSFCreate(comm, &sfProc);
702:     PetscObjectSetName((PetscObject) sfProc, "Process SF");
703:     PetscSFSetGraph(sfProc, size, size, NULL, PETSC_OWN_POINTER, remoteProc, PETSC_OWN_POINTER);
704:   }
705:   DMLabelCreate("Overlap label", ovLabel);
706:   DMPlexPartitionLabelInvert(dm, ovAdjByRank, sfProc, *ovLabel);
707:   /* Add owned points, except for shared local points */
708:   for (p = pStart; p < pEnd; ++p) {DMLabelSetValue(*ovLabel, p, rank);}
709:   for (l = 0; l < nleaves; ++l) {
710:     DMLabelClearValue(*ovLabel, local[l], rank);
711:     DMLabelSetValue(*ovLabel, remote[l].index, remote[l].rank);
712:   }
713:   /* Clean up */
714:   DMLabelDestroy(&ovAdjByRank);
715:   PetscSFDestroy(&sfProc);
716:   return(0);
717: }

719: /*@C
720:   DMPlexCreateOverlapMigrationSF - Create an SF describing the new mesh distribution to make the overlap described by the input SF

722:   Collective on DM

724:   Input Parameters:
725: + dm          - The DM
726: - overlapSF   - The SF mapping ghost points in overlap to owner points on other processes

728:   Output Parameters:
729: + migrationSF - An SF that maps original points in old locations to points in new locations

731:   Level: developer

733: .seealso: DMPlexCreateOverlap(), DMPlexDistribute()
734: @*/
735: PetscErrorCode DMPlexCreateOverlapMigrationSF(DM dm, PetscSF overlapSF, PetscSF *migrationSF)
736: {
737:   MPI_Comm           comm;
738:   PetscMPIInt        rank, size;
739:   PetscInt           d, dim, p, pStart, pEnd, nroots, nleaves, newLeaves, point, numSharedPoints;
740:   PetscInt          *pointDepths, *remoteDepths, *ilocal;
741:   PetscInt          *depthRecv, *depthShift, *depthIdx;
742:   PetscSFNode       *iremote;
743:   PetscSF            pointSF;
744:   const PetscInt    *sharedLocal;
745:   const PetscSFNode *overlapRemote, *sharedRemote;
746:   PetscErrorCode     ierr;

750:   PetscObjectGetComm((PetscObject)dm, &comm);
751:   MPI_Comm_rank(comm, &rank);
752:   MPI_Comm_size(comm, &size);
753:   DMGetDimension(dm, &dim);

755:   /* Before building the migration SF we need to know the new stratum offsets */
756:   PetscSFGetGraph(overlapSF, &nroots, &nleaves, NULL, &overlapRemote);
757:   PetscMalloc2(nroots, &pointDepths, nleaves, &remoteDepths);
758:   for (d=0; d<dim+1; d++) {
759:     DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
760:     for (p=pStart; p<pEnd; p++) pointDepths[p] = d;
761:   }
762:   for (p=0; p<nleaves; p++) remoteDepths[p] = -1;
763:   PetscSFBcastBegin(overlapSF, MPIU_INT, pointDepths, remoteDepths);
764:   PetscSFBcastEnd(overlapSF, MPIU_INT, pointDepths, remoteDepths);

766:   /* Count recevied points in each stratum and compute the internal strata shift */
767:   PetscMalloc3(dim+1, &depthRecv, dim+1, &depthShift, dim+1, &depthIdx);
768:   for (d=0; d<dim+1; d++) depthRecv[d]=0;
769:   for (p=0; p<nleaves; p++) depthRecv[remoteDepths[p]]++;
770:   depthShift[dim] = 0;
771:   for (d=0; d<dim; d++) depthShift[d] = depthRecv[dim];
772:   for (d=1; d<dim; d++) depthShift[d] += depthRecv[0];
773:   for (d=dim-2; d>0; d--) depthShift[d] += depthRecv[d+1];
774:   for (d=0; d<dim+1; d++) {
775:     DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
776:     depthIdx[d] = pStart + depthShift[d];
777:   }

779:   /* Form the overlap SF build an SF that describes the full overlap migration SF */
780:   DMPlexGetChart(dm, &pStart, &pEnd);
781:   newLeaves = pEnd - pStart + nleaves;
782:   PetscMalloc1(newLeaves, &ilocal);
783:   PetscMalloc1(newLeaves, &iremote);
784:   /* First map local points to themselves */
785:   for (d=0; d<dim+1; d++) {
786:     DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
787:     for (p=pStart; p<pEnd; p++) {
788:       point = p + depthShift[d];
789:       ilocal[point] = point;
790:       iremote[point].index = p;
791:       iremote[point].rank = rank;
792:       depthIdx[d]++;
793:     }
794:   }

796:   /* Add in the remote roots for currently shared points */
797:   DMGetPointSF(dm, &pointSF);
798:   PetscSFGetGraph(pointSF, NULL, &numSharedPoints, &sharedLocal, &sharedRemote);
799:   for (d=0; d<dim+1; d++) {
800:     DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
801:     for (p=0; p<numSharedPoints; p++) {
802:       if (pStart <= sharedLocal[p] && sharedLocal[p] < pEnd) {
803:         point = sharedLocal[p] + depthShift[d];
804:         iremote[point].index = sharedRemote[p].index;
805:         iremote[point].rank = sharedRemote[p].rank;
806:       }
807:     }
808:   }

810:   /* Now add the incoming overlap points */
811:   for (p=0; p<nleaves; p++) {
812:     point = depthIdx[remoteDepths[p]];
813:     ilocal[point] = point;
814:     iremote[point].index = overlapRemote[p].index;
815:     iremote[point].rank = overlapRemote[p].rank;
816:     depthIdx[remoteDepths[p]]++;
817:   }
818:   PetscFree2(pointDepths,remoteDepths);

820:   PetscSFCreate(comm, migrationSF);
821:   PetscObjectSetName((PetscObject) *migrationSF, "Overlap Migration SF");
822:   PetscSFSetFromOptions(*migrationSF);
823:   DMPlexGetChart(dm, &pStart, &pEnd);
824:   PetscSFSetGraph(*migrationSF, pEnd-pStart, newLeaves, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER);

826:   PetscFree3(depthRecv, depthShift, depthIdx);
827:   return(0);
828: }

830: /*@
831:   DMPlexStratifyMigrationSF - Rearrange the leaves of a migration sf for stratification.

833:   Input Parameter:
834: + dm          - The DM
835: - sf          - A star forest with non-ordered leaves, usually defining a DM point migration

837:   Output Parameter:
838: . migrationSF - A star forest with added leaf indirection that ensures the resulting DM is stratified

840:   Level: developer

842: .seealso: DMPlexPartitionLabelCreateSF(), DMPlexDistribute(), DMPlexDistributeOverlap()
843: @*/
844: PetscErrorCode DMPlexStratifyMigrationSF(DM dm, PetscSF sf, PetscSF *migrationSF)
845: {
846:   MPI_Comm           comm;
847:   PetscMPIInt        rank, size;
848:   PetscInt           d, ldepth, depth, p, pStart, pEnd, nroots, nleaves;
849:   PetscInt          *pointDepths, *remoteDepths, *ilocal;
850:   PetscInt          *depthRecv, *depthShift, *depthIdx;
851:   PetscInt           hybEnd[4];
852:   const PetscSFNode *iremote;
853:   PetscErrorCode     ierr;

857:   PetscObjectGetComm((PetscObject) dm, &comm);
858:   MPI_Comm_rank(comm, &rank);
859:   MPI_Comm_size(comm, &size);
860:   DMPlexGetDepth(dm, &ldepth);
861:   MPIU_Allreduce(&ldepth, &depth, 1, MPIU_INT, MPI_MAX, comm);
862:   if ((ldepth >= 0) && (depth != ldepth)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Inconsistent Plex depth %d != %d", ldepth, depth);

864:   /* Before building the migration SF we need to know the new stratum offsets */
865:   PetscSFGetGraph(sf, &nroots, &nleaves, NULL, &iremote);
866:   PetscMalloc2(nroots, &pointDepths, nleaves, &remoteDepths);
867:   DMPlexGetHybridBounds(dm,&hybEnd[depth],&hybEnd[depth-1],&hybEnd[1],&hybEnd[0]);
868:   for (d = 0; d < depth+1; ++d) {
869:     DMPlexGetDepthStratum(dm, d, &pStart, &pEnd);
870:     for (p = pStart; p < pEnd; ++p) {
871:       if (hybEnd[d] >= 0 && p >= hybEnd[d]) { /* put in a separate value for hybrid points */
872:         pointDepths[p] = 2 * d;
873:       } else {
874:         pointDepths[p] = 2 * d + 1;
875:       }
876:     }
877:   }
878:   for (p = 0; p < nleaves; ++p) remoteDepths[p] = -1;
879:   PetscSFBcastBegin(sf, MPIU_INT, pointDepths, remoteDepths);
880:   PetscSFBcastEnd(sf, MPIU_INT, pointDepths, remoteDepths);
881:   /* Count recevied points in each stratum and compute the internal strata shift */
882:   PetscMalloc3(2*(depth+1), &depthRecv, 2*(depth+1), &depthShift, 2*(depth+1), &depthIdx);
883:   for (d = 0; d < 2*(depth+1); ++d) depthRecv[d] = 0;
884:   for (p = 0; p < nleaves; ++p) depthRecv[remoteDepths[p]]++;
885:   depthShift[2*depth+1] = 0;
886:   for (d = 0; d < 2*depth+1; ++d) depthShift[d] = depthRecv[2 * depth + 1];
887:   for (d = 0; d < 2*depth; ++d) depthShift[d] += depthRecv[2 * depth];
888:   depthShift[0] += depthRecv[1];
889:   for (d = 2; d < 2*depth; ++d) depthShift[d] += depthRecv[1];
890:   for (d = 2; d < 2*depth; ++d) depthShift[d] += depthRecv[0];
891:   for (d = 2 * depth-1; d > 2; --d) {
892:     PetscInt e;

894:     for (e = d -1; e > 1; --e) depthShift[e] += depthRecv[d];
895:   }
896:   for (d = 0; d < 2*(depth+1); ++d) {depthIdx[d] = 0;}
897:   /* Derive a new local permutation based on stratified indices */
898:   PetscMalloc1(nleaves, &ilocal);
899:   for (p = 0; p < nleaves; ++p) {
900:     const PetscInt dep = remoteDepths[p];

902:     ilocal[p] = depthShift[dep] + depthIdx[dep];
903:     depthIdx[dep]++;
904:   }
905:   PetscSFCreate(comm, migrationSF);
906:   PetscObjectSetName((PetscObject) *migrationSF, "Migration SF");
907:   PetscSFSetGraph(*migrationSF, nroots, nleaves, ilocal, PETSC_OWN_POINTER, iremote, PETSC_COPY_VALUES);
908:   PetscFree2(pointDepths,remoteDepths);
909:   PetscFree3(depthRecv, depthShift, depthIdx);
910:   return(0);
911: }

913: /*@
914:   DMPlexDistributeField - Distribute field data to match a given PetscSF, usually the SF from mesh distribution

916:   Collective on DM

918:   Input Parameters:
919: + dm - The DMPlex object
920: . pointSF - The PetscSF describing the communication pattern
921: . originalSection - The PetscSection for existing data layout
922: - originalVec - The existing data

924:   Output Parameters:
925: + newSection - The PetscSF describing the new data layout
926: - newVec - The new data

928:   Level: developer

930: .seealso: DMPlexDistribute(), DMPlexDistributeFieldIS(), DMPlexDistributeData()
931: @*/
932: PetscErrorCode DMPlexDistributeField(DM dm, PetscSF pointSF, PetscSection originalSection, Vec originalVec, PetscSection newSection, Vec newVec)
933: {
934:   PetscSF        fieldSF;
935:   PetscInt      *remoteOffsets, fieldSize;
936:   PetscScalar   *originalValues, *newValues;

940:   PetscLogEventBegin(DMPLEX_DistributeField,dm,0,0,0);
941:   PetscSFDistributeSection(pointSF, originalSection, &remoteOffsets, newSection);

943:   PetscSectionGetStorageSize(newSection, &fieldSize);
944:   VecSetSizes(newVec, fieldSize, PETSC_DETERMINE);
945:   VecSetType(newVec,dm->vectype);

947:   VecGetArray(originalVec, &originalValues);
948:   VecGetArray(newVec, &newValues);
949:   PetscSFCreateSectionSF(pointSF, originalSection, remoteOffsets, newSection, &fieldSF);
950:   PetscFree(remoteOffsets);
951:   PetscSFBcastBegin(fieldSF, MPIU_SCALAR, originalValues, newValues);
952:   PetscSFBcastEnd(fieldSF, MPIU_SCALAR, originalValues, newValues);
953:   PetscSFDestroy(&fieldSF);
954:   VecRestoreArray(newVec, &newValues);
955:   VecRestoreArray(originalVec, &originalValues);
956:   PetscLogEventEnd(DMPLEX_DistributeField,dm,0,0,0);
957:   return(0);
958: }

960: /*@
961:   DMPlexDistributeFieldIS - Distribute field data to match a given PetscSF, usually the SF from mesh distribution

963:   Collective on DM

965:   Input Parameters:
966: + dm - The DMPlex object
967: . pointSF - The PetscSF describing the communication pattern
968: . originalSection - The PetscSection for existing data layout
969: - originalIS - The existing data

971:   Output Parameters:
972: + newSection - The PetscSF describing the new data layout
973: - newIS - The new data

975:   Level: developer

977: .seealso: DMPlexDistribute(), DMPlexDistributeField(), DMPlexDistributeData()
978: @*/
979: PetscErrorCode DMPlexDistributeFieldIS(DM dm, PetscSF pointSF, PetscSection originalSection, IS originalIS, PetscSection newSection, IS *newIS)
980: {
981:   PetscSF         fieldSF;
982:   PetscInt       *newValues, *remoteOffsets, fieldSize;
983:   const PetscInt *originalValues;
984:   PetscErrorCode  ierr;

987:   PetscLogEventBegin(DMPLEX_DistributeField,dm,0,0,0);
988:   PetscSFDistributeSection(pointSF, originalSection, &remoteOffsets, newSection);

990:   PetscSectionGetStorageSize(newSection, &fieldSize);
991:   PetscMalloc1(fieldSize, &newValues);

993:   ISGetIndices(originalIS, &originalValues);
994:   PetscSFCreateSectionSF(pointSF, originalSection, remoteOffsets, newSection, &fieldSF);
995:   PetscFree(remoteOffsets);
996:   PetscSFBcastBegin(fieldSF, MPIU_INT, (PetscInt *) originalValues, newValues);
997:   PetscSFBcastEnd(fieldSF, MPIU_INT, (PetscInt *) originalValues, newValues);
998:   PetscSFDestroy(&fieldSF);
999:   ISRestoreIndices(originalIS, &originalValues);
1000:   ISCreateGeneral(PetscObjectComm((PetscObject) pointSF), fieldSize, newValues, PETSC_OWN_POINTER, newIS);
1001:   PetscLogEventEnd(DMPLEX_DistributeField,dm,0,0,0);
1002:   return(0);
1003: }

1005: /*@
1006:   DMPlexDistributeData - Distribute field data to match a given PetscSF, usually the SF from mesh distribution

1008:   Collective on DM

1010:   Input Parameters:
1011: + dm - The DMPlex object
1012: . pointSF - The PetscSF describing the communication pattern
1013: . originalSection - The PetscSection for existing data layout
1014: . datatype - The type of data
1015: - originalData - The existing data

1017:   Output Parameters:
1018: + newSection - The PetscSection describing the new data layout
1019: - newData - The new data

1021:   Level: developer

1023: .seealso: DMPlexDistribute(), DMPlexDistributeField()
1024: @*/
1025: PetscErrorCode DMPlexDistributeData(DM dm, PetscSF pointSF, PetscSection originalSection, MPI_Datatype datatype, void *originalData, PetscSection newSection, void **newData)
1026: {
1027:   PetscSF        fieldSF;
1028:   PetscInt      *remoteOffsets, fieldSize;
1029:   PetscMPIInt    dataSize;

1033:   PetscLogEventBegin(DMPLEX_DistributeData,dm,0,0,0);
1034:   PetscSFDistributeSection(pointSF, originalSection, &remoteOffsets, newSection);

1036:   PetscSectionGetStorageSize(newSection, &fieldSize);
1037:   MPI_Type_size(datatype, &dataSize);
1038:   PetscMalloc(fieldSize * dataSize, newData);

1040:   PetscSFCreateSectionSF(pointSF, originalSection, remoteOffsets, newSection, &fieldSF);
1041:   PetscFree(remoteOffsets);
1042:   PetscSFBcastBegin(fieldSF, datatype, originalData, *newData);
1043:   PetscSFBcastEnd(fieldSF, datatype, originalData, *newData);
1044:   PetscSFDestroy(&fieldSF);
1045:   PetscLogEventEnd(DMPLEX_DistributeData,dm,0,0,0);
1046:   return(0);
1047: }

1049: static PetscErrorCode DMPlexDistributeCones(DM dm, PetscSF migrationSF, ISLocalToGlobalMapping original, ISLocalToGlobalMapping renumbering, DM dmParallel)
1050: {
1051:   DM_Plex               *pmesh = (DM_Plex*) (dmParallel)->data;
1052:   MPI_Comm               comm;
1053:   PetscSF                coneSF;
1054:   PetscSection           originalConeSection, newConeSection;
1055:   PetscInt              *remoteOffsets, *cones, *globCones, *newCones, newConesSize;
1056:   PetscBool              flg;
1057:   PetscErrorCode         ierr;

1062:   PetscLogEventBegin(DMPLEX_DistributeCones,dm,0,0,0);

1064:   /* Distribute cone section */
1065:   PetscObjectGetComm((PetscObject)dm, &comm);
1066:   DMPlexGetConeSection(dm, &originalConeSection);
1067:   DMPlexGetConeSection(dmParallel, &newConeSection);
1068:   PetscSFDistributeSection(migrationSF, originalConeSection, &remoteOffsets, newConeSection);
1069:   DMSetUp(dmParallel);
1070:   {
1071:     PetscInt pStart, pEnd, p;

1073:     PetscSectionGetChart(newConeSection, &pStart, &pEnd);
1074:     for (p = pStart; p < pEnd; ++p) {
1075:       PetscInt coneSize;
1076:       PetscSectionGetDof(newConeSection, p, &coneSize);
1077:       pmesh->maxConeSize = PetscMax(pmesh->maxConeSize, coneSize);
1078:     }
1079:   }
1080:   /* Communicate and renumber cones */
1081:   PetscSFCreateSectionSF(migrationSF, originalConeSection, remoteOffsets, newConeSection, &coneSF);
1082:   PetscFree(remoteOffsets);
1083:   DMPlexGetCones(dm, &cones);
1084:   if (original) {
1085:     PetscInt numCones;

1087:     PetscSectionGetStorageSize(originalConeSection,&numCones); PetscMalloc1(numCones,&globCones);
1088:     ISLocalToGlobalMappingApplyBlock(original, numCones, cones, globCones);
1089:   }
1090:   else {
1091:     globCones = cones;
1092:   }
1093:   DMPlexGetCones(dmParallel, &newCones);
1094:   PetscSFBcastBegin(coneSF, MPIU_INT, globCones, newCones);
1095:   PetscSFBcastEnd(coneSF, MPIU_INT, globCones, newCones);
1096:   if (original) {
1097:     PetscFree(globCones);
1098:   }
1099:   PetscSectionGetStorageSize(newConeSection, &newConesSize);
1100:   ISGlobalToLocalMappingApplyBlock(renumbering, IS_GTOLM_MASK, newConesSize, newCones, NULL, newCones);
1101: #if PETSC_USE_DEBUG
1102:   {
1103:     PetscInt  p;
1104:     PetscBool valid = PETSC_TRUE;
1105:     for (p = 0; p < newConesSize; ++p) {
1106:       if (newCones[p] < 0) {valid = PETSC_FALSE; PetscPrintf(PETSC_COMM_SELF, "Point %d not in overlap SF\n", p);}
1107:     }
1108:     if (!valid) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid global to local map");
1109:   }
1110: #endif
1111:   PetscOptionsHasName(((PetscObject) dm)->options,((PetscObject) dm)->prefix, "-cones_view", &flg);
1112:   if (flg) {
1113:     PetscPrintf(comm, "Serial Cone Section:\n");
1114:     PetscSectionView(originalConeSection, PETSC_VIEWER_STDOUT_WORLD);
1115:     PetscPrintf(comm, "Parallel Cone Section:\n");
1116:     PetscSectionView(newConeSection, PETSC_VIEWER_STDOUT_WORLD);
1117:     PetscSFView(coneSF, NULL);
1118:   }
1119:   DMPlexGetConeOrientations(dm, &cones);
1120:   DMPlexGetConeOrientations(dmParallel, &newCones);
1121:   PetscSFBcastBegin(coneSF, MPIU_INT, cones, newCones);
1122:   PetscSFBcastEnd(coneSF, MPIU_INT, cones, newCones);
1123:   PetscSFDestroy(&coneSF);
1124:   PetscLogEventEnd(DMPLEX_DistributeCones,dm,0,0,0);
1125:   /* Create supports and stratify DMPlex */
1126:   {
1127:     PetscInt pStart, pEnd;

1129:     PetscSectionGetChart(pmesh->coneSection, &pStart, &pEnd);
1130:     PetscSectionSetChart(pmesh->supportSection, pStart, pEnd);
1131:   }
1132:   DMPlexSymmetrize(dmParallel);
1133:   DMPlexStratify(dmParallel);
1134:   {
1135:     PetscBool useCone, useClosure, useAnchors;

1137:     DMPlexGetAdjacencyUseCone(dm, &useCone);
1138:     DMPlexGetAdjacencyUseClosure(dm, &useClosure);
1139:     DMPlexGetAdjacencyUseAnchors(dm, &useAnchors);
1140:     DMPlexSetAdjacencyUseCone(dmParallel, useCone);
1141:     DMPlexSetAdjacencyUseClosure(dmParallel, useClosure);
1142:     DMPlexSetAdjacencyUseAnchors(dmParallel, useAnchors);
1143:   }
1144:   return(0);
1145: }

1147: static PetscErrorCode DMPlexDistributeCoordinates(DM dm, PetscSF migrationSF, DM dmParallel)
1148: {
1149:   MPI_Comm         comm;
1150:   PetscSection     originalCoordSection, newCoordSection;
1151:   Vec              originalCoordinates, newCoordinates;
1152:   PetscInt         bs;
1153:   PetscBool        isper;
1154:   const char      *name;
1155:   const PetscReal *maxCell, *L;
1156:   const DMBoundaryType *bd;
1157:   PetscErrorCode   ierr;


1163:   PetscObjectGetComm((PetscObject)dm, &comm);
1164:   DMGetCoordinateSection(dm, &originalCoordSection);
1165:   DMGetCoordinateSection(dmParallel, &newCoordSection);
1166:   DMGetCoordinatesLocal(dm, &originalCoordinates);
1167:   if (originalCoordinates) {
1168:     VecCreate(PETSC_COMM_SELF, &newCoordinates);
1169:     PetscObjectGetName((PetscObject) originalCoordinates, &name);
1170:     PetscObjectSetName((PetscObject) newCoordinates, name);

1172:     DMPlexDistributeField(dm, migrationSF, originalCoordSection, originalCoordinates, newCoordSection, newCoordinates);
1173:     DMSetCoordinatesLocal(dmParallel, newCoordinates);
1174:     VecGetBlockSize(originalCoordinates, &bs);
1175:     VecSetBlockSize(newCoordinates, bs);
1176:     VecDestroy(&newCoordinates);
1177:   }
1178:   DMGetPeriodicity(dm, &isper, &maxCell, &L, &bd);
1179:   DMSetPeriodicity(dmParallel, isper, maxCell, L, bd);
1180:   return(0);
1181: }

1183: /* Here we are assuming that process 0 always has everything */
1184: static PetscErrorCode DMPlexDistributeLabels(DM dm, PetscSF migrationSF, DM dmParallel)
1185: {
1186:   DM_Plex         *mesh = (DM_Plex*) dm->data;
1187:   MPI_Comm         comm;
1188:   DMLabel          depthLabel;
1189:   PetscMPIInt      rank;
1190:   PetscInt         depth, d, numLabels, numLocalLabels, l;
1191:   PetscBool        hasLabels = PETSC_FALSE, lsendDepth, sendDepth;
1192:   PetscObjectState depthState = -1;
1193:   PetscErrorCode   ierr;

1198:   PetscLogEventBegin(DMPLEX_DistributeLabels,dm,0,0,0);
1199:   PetscObjectGetComm((PetscObject)dm, &comm);
1200:   MPI_Comm_rank(comm, &rank);

1202:   /* If the user has changed the depth label, communicate it instead */
1203:   DMPlexGetDepth(dm, &depth);
1204:   DMPlexGetDepthLabel(dm, &depthLabel);
1205:   if (depthLabel) {DMLabelGetState(depthLabel, &depthState);}
1206:   lsendDepth = mesh->depthState != depthState ? PETSC_TRUE : PETSC_FALSE;
1207:   MPIU_Allreduce(&lsendDepth, &sendDepth, 1, MPIU_BOOL, MPI_LOR, comm);
1208:   if (sendDepth) {
1209:     DMRemoveLabel(dmParallel, "depth", &depthLabel);
1210:     DMLabelDestroy(&depthLabel);
1211:   }
1212:   /* Everyone must have either the same number of labels, or none */
1213:   DMGetNumLabels(dm, &numLocalLabels);
1214:   numLabels = numLocalLabels;
1215:   MPI_Bcast(&numLabels, 1, MPIU_INT, 0, comm);
1216:   if (numLabels == numLocalLabels) hasLabels = PETSC_TRUE;
1217:   for (l = numLabels-1; l >= 0; --l) {
1218:     DMLabel     label = NULL, labelNew = NULL;
1219:     PetscBool   isDepth, lisOutput = PETSC_TRUE, isOutput;

1221:     if (hasLabels) {DMGetLabelByNum(dm, l, &label);}
1222:     /* Skip "depth" because it is recreated */
1223:     if (hasLabels) {PetscStrcmp(label->name, "depth", &isDepth);}
1224:     MPI_Bcast(&isDepth, 1, MPIU_BOOL, 0, comm);
1225:     if (isDepth && !sendDepth) continue;
1226:     DMLabelDistribute(label, migrationSF, &labelNew);
1227:     if (isDepth) {
1228:       /* Put in any missing strata which can occur if users are managing the depth label themselves */
1229:       PetscInt gdepth;

1231:       MPIU_Allreduce(&depth, &gdepth, 1, MPIU_INT, MPI_MAX, comm);
1232:       if ((depth >= 0) && (gdepth != depth)) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Inconsistent Plex depth %d != %d", depth, gdepth);
1233:       for (d = 0; d <= gdepth; ++d) {
1234:         PetscBool has;

1236:         DMLabelHasStratum(labelNew, d, &has);
1237:         if (!has) {DMLabelAddStratum(labelNew, d);}
1238:       }
1239:     }
1240:     DMAddLabel(dmParallel, labelNew);
1241:     /* Put the output flag in the new label */
1242:     if (hasLabels) {DMGetLabelOutput(dm, label->name, &lisOutput);}
1243:     MPIU_Allreduce(&lisOutput, &isOutput, 1, MPIU_BOOL, MPI_LAND, comm);
1244:     DMSetLabelOutput(dmParallel, labelNew->name, isOutput);
1245:   }
1246:   PetscLogEventEnd(DMPLEX_DistributeLabels,dm,0,0,0);
1247:   return(0);
1248: }

1250: static PetscErrorCode DMPlexDistributeSetupHybrid(DM dm, PetscSF migrationSF, ISLocalToGlobalMapping renumbering, DM dmParallel)
1251: {
1252:   DM_Plex        *mesh  = (DM_Plex*) dm->data;
1253:   DM_Plex        *pmesh = (DM_Plex*) (dmParallel)->data;
1254:   PetscBool      *isHybrid, *isHybridParallel;
1255:   PetscInt        dim, depth, d;
1256:   PetscInt        pStart, pEnd, pStartP, pEndP;
1257:   PetscErrorCode  ierr;


1263:   DMGetDimension(dm, &dim);
1264:   DMPlexGetDepth(dm, &depth);
1265:   DMPlexGetChart(dm,&pStart,&pEnd);
1266:   DMPlexGetChart(dmParallel,&pStartP,&pEndP);
1267:   PetscCalloc2(pEnd-pStart,&isHybrid,pEndP-pStartP,&isHybridParallel);
1268:   for (d = 0; d <= depth; d++) {
1269:     PetscInt hybridMax = (depth == 1 && d == 1) ? mesh->hybridPointMax[dim] : mesh->hybridPointMax[d];

1271:     if (hybridMax >= 0) {
1272:       PetscInt sStart, sEnd, p;

1274:       DMPlexGetDepthStratum(dm,d,&sStart,&sEnd);
1275:       for (p = hybridMax; p < sEnd; p++) isHybrid[p-pStart] = PETSC_TRUE;
1276:     }
1277:   }
1278:   PetscSFBcastBegin(migrationSF,MPIU_BOOL,isHybrid,isHybridParallel);
1279:   PetscSFBcastEnd(migrationSF,MPIU_BOOL,isHybrid,isHybridParallel);
1280:   for (d = 0; d <= dim; d++) pmesh->hybridPointMax[d] = -1;
1281:   for (d = 0; d <= depth; d++) {
1282:     PetscInt sStart, sEnd, p, dd;

1284:     DMPlexGetDepthStratum(dmParallel,d,&sStart,&sEnd);
1285:     dd = (depth == 1 && d == 1) ? dim : d;
1286:     for (p = sStart; p < sEnd; p++) {
1287:       if (isHybridParallel[p-pStartP]) {
1288:         pmesh->hybridPointMax[dd] = p;
1289:         break;
1290:       }
1291:     }
1292:   }
1293:   PetscFree2(isHybrid,isHybridParallel);
1294:   return(0);
1295: }

1297: static PetscErrorCode DMPlexDistributeSetupTree(DM dm, PetscSF migrationSF, ISLocalToGlobalMapping original, ISLocalToGlobalMapping renumbering, DM dmParallel)
1298: {
1299:   DM_Plex        *mesh  = (DM_Plex*) dm->data;
1300:   DM_Plex        *pmesh = (DM_Plex*) (dmParallel)->data;
1301:   MPI_Comm        comm;
1302:   DM              refTree;
1303:   PetscSection    origParentSection, newParentSection;
1304:   PetscInt        *origParents, *origChildIDs;
1305:   PetscBool       flg;
1306:   PetscErrorCode  ierr;

1311:   PetscObjectGetComm((PetscObject)dm, &comm);

1313:   /* Set up tree */
1314:   DMPlexGetReferenceTree(dm,&refTree);
1315:   DMPlexSetReferenceTree(dmParallel,refTree);
1316:   DMPlexGetTree(dm,&origParentSection,&origParents,&origChildIDs,NULL,NULL);
1317:   if (origParentSection) {
1318:     PetscInt        pStart, pEnd;
1319:     PetscInt        *newParents, *newChildIDs, *globParents;
1320:     PetscInt        *remoteOffsetsParents, newParentSize;
1321:     PetscSF         parentSF;

1323:     DMPlexGetChart(dmParallel, &pStart, &pEnd);
1324:     PetscSectionCreate(PetscObjectComm((PetscObject)dmParallel),&newParentSection);
1325:     PetscSectionSetChart(newParentSection,pStart,pEnd);
1326:     PetscSFDistributeSection(migrationSF, origParentSection, &remoteOffsetsParents, newParentSection);
1327:     PetscSFCreateSectionSF(migrationSF, origParentSection, remoteOffsetsParents, newParentSection, &parentSF);
1328:     PetscFree(remoteOffsetsParents);
1329:     PetscSectionGetStorageSize(newParentSection,&newParentSize);
1330:     PetscMalloc2(newParentSize,&newParents,newParentSize,&newChildIDs);
1331:     if (original) {
1332:       PetscInt numParents;

1334:       PetscSectionGetStorageSize(origParentSection,&numParents);
1335:       PetscMalloc1(numParents,&globParents);
1336:       ISLocalToGlobalMappingApplyBlock(original, numParents, origParents, globParents);
1337:     }
1338:     else {
1339:       globParents = origParents;
1340:     }
1341:     PetscSFBcastBegin(parentSF, MPIU_INT, globParents, newParents);
1342:     PetscSFBcastEnd(parentSF, MPIU_INT, globParents, newParents);
1343:     if (original) {
1344:       PetscFree(globParents);
1345:     }
1346:     PetscSFBcastBegin(parentSF, MPIU_INT, origChildIDs, newChildIDs);
1347:     PetscSFBcastEnd(parentSF, MPIU_INT, origChildIDs, newChildIDs);
1348:     ISGlobalToLocalMappingApplyBlock(renumbering,IS_GTOLM_MASK, newParentSize, newParents, NULL, newParents);
1349: #if PETSC_USE_DEBUG
1350:     {
1351:       PetscInt  p;
1352:       PetscBool valid = PETSC_TRUE;
1353:       for (p = 0; p < newParentSize; ++p) {
1354:         if (newParents[p] < 0) {valid = PETSC_FALSE; PetscPrintf(PETSC_COMM_SELF, "Point %d not in overlap SF\n", p);}
1355:       }
1356:       if (!valid) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Invalid global to local map");
1357:     }
1358: #endif
1359:     PetscOptionsHasName(((PetscObject) dm)->options,((PetscObject) dm)->prefix, "-parents_view", &flg);
1360:     if (flg) {
1361:       PetscPrintf(comm, "Serial Parent Section: \n");
1362:       PetscSectionView(origParentSection, PETSC_VIEWER_STDOUT_WORLD);
1363:       PetscPrintf(comm, "Parallel Parent Section: \n");
1364:       PetscSectionView(newParentSection, PETSC_VIEWER_STDOUT_WORLD);
1365:       PetscSFView(parentSF, NULL);
1366:     }
1367:     DMPlexSetTree(dmParallel,newParentSection,newParents,newChildIDs);
1368:     PetscSectionDestroy(&newParentSection);
1369:     PetscFree2(newParents,newChildIDs);
1370:     PetscSFDestroy(&parentSF);
1371:   }
1372:   pmesh->useAnchors = mesh->useAnchors;
1373:   return(0);
1374: }

1376: PETSC_UNUSED static PetscErrorCode DMPlexDistributeSF(DM dm, PetscSF migrationSF, DM dmParallel)
1377: {
1378:   PetscMPIInt            rank, size;
1379:   MPI_Comm               comm;
1380:   PetscErrorCode         ierr;


1386:   /* Create point SF for parallel mesh */
1387:   PetscLogEventBegin(DMPLEX_DistributeSF,dm,0,0,0);
1388:   PetscObjectGetComm((PetscObject)dm, &comm);
1389:   MPI_Comm_rank(comm, &rank);
1390:   MPI_Comm_size(comm, &size);
1391:   {
1392:     const PetscInt *leaves;
1393:     PetscSFNode    *remotePoints, *rowners, *lowners;
1394:     PetscInt        numRoots, numLeaves, numGhostPoints = 0, p, gp, *ghostPoints;
1395:     PetscInt        pStart, pEnd;

1397:     DMPlexGetChart(dmParallel, &pStart, &pEnd);
1398:     PetscSFGetGraph(migrationSF, &numRoots, &numLeaves, &leaves, NULL);
1399:     PetscMalloc2(numRoots,&rowners,numLeaves,&lowners);
1400:     for (p=0; p<numRoots; p++) {
1401:       rowners[p].rank  = -1;
1402:       rowners[p].index = -1;
1403:     }
1404:     PetscSFBcastBegin(migrationSF, MPIU_2INT, rowners, lowners);
1405:     PetscSFBcastEnd(migrationSF, MPIU_2INT, rowners, lowners);
1406:     for (p = 0; p < numLeaves; ++p) {
1407:       if (lowners[p].rank < 0 || lowners[p].rank == rank) { /* Either put in a bid or we know we own it */
1408:         lowners[p].rank  = rank;
1409:         lowners[p].index = leaves ? leaves[p] : p;
1410:       } else if (lowners[p].rank >= 0) { /* Point already claimed so flag so that MAXLOC does not listen to us */
1411:         lowners[p].rank  = -2;
1412:         lowners[p].index = -2;
1413:       }
1414:     }
1415:     for (p=0; p<numRoots; p++) { /* Root must not participate in the rediction, flag so that MAXLOC does not use */
1416:       rowners[p].rank  = -3;
1417:       rowners[p].index = -3;
1418:     }
1419:     PetscSFReduceBegin(migrationSF, MPIU_2INT, lowners, rowners, MPI_MAXLOC);
1420:     PetscSFReduceEnd(migrationSF, MPIU_2INT, lowners, rowners, MPI_MAXLOC);
1421:     PetscSFBcastBegin(migrationSF, MPIU_2INT, rowners, lowners);
1422:     PetscSFBcastEnd(migrationSF, MPIU_2INT, rowners, lowners);
1423:     for (p = 0; p < numLeaves; ++p) {
1424:       if (lowners[p].rank < 0 || lowners[p].index < 0) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Cell partition corrupt: point not claimed");
1425:       if (lowners[p].rank != rank) ++numGhostPoints;
1426:     }
1427:     PetscMalloc1(numGhostPoints, &ghostPoints);
1428:     PetscMalloc1(numGhostPoints, &remotePoints);
1429:     for (p = 0, gp = 0; p < numLeaves; ++p) {
1430:       if (lowners[p].rank != rank) {
1431:         ghostPoints[gp]        = leaves ? leaves[p] : p;
1432:         remotePoints[gp].rank  = lowners[p].rank;
1433:         remotePoints[gp].index = lowners[p].index;
1434:         ++gp;
1435:       }
1436:     }
1437:     PetscFree2(rowners,lowners);
1438:     PetscSFSetGraph((dmParallel)->sf, pEnd - pStart, numGhostPoints, ghostPoints, PETSC_OWN_POINTER, remotePoints, PETSC_OWN_POINTER);
1439:     PetscSFSetFromOptions((dmParallel)->sf);
1440:   }
1441:   {
1442:     PetscBool useCone, useClosure, useAnchors;

1444:     DMPlexGetAdjacencyUseCone(dm, &useCone);
1445:     DMPlexGetAdjacencyUseClosure(dm, &useClosure);
1446:     DMPlexGetAdjacencyUseAnchors(dm, &useAnchors);
1447:     DMPlexSetAdjacencyUseCone(dmParallel, useCone);
1448:     DMPlexSetAdjacencyUseClosure(dmParallel, useClosure);
1449:     DMPlexSetAdjacencyUseAnchors(dmParallel, useAnchors);
1450:   }
1451:   PetscLogEventEnd(DMPLEX_DistributeSF,dm,0,0,0);
1452:   return(0);
1453: }

1455: /*@C
1456:   DMPlexDerivePointSF - Build a point SF from an SF describing a point migration

1458:   Input Parameter:
1459: + dm          - The source DMPlex object
1460: . migrationSF - The star forest that describes the parallel point remapping
1461: . ownership   - Flag causing a vote to determine point ownership

1463:   Output Parameter:
1464: - pointSF     - The star forest describing the point overlap in the remapped DM

1466:   Level: developer

1468: .seealso: DMPlexDistribute(), DMPlexDistributeOverlap()
1469: @*/
1470: PetscErrorCode DMPlexCreatePointSF(DM dm, PetscSF migrationSF, PetscBool ownership, PetscSF *pointSF)
1471: {
1472:   PetscMPIInt        rank;
1473:   PetscInt           p, nroots, nleaves, idx, npointLeaves;
1474:   PetscInt          *pointLocal;
1475:   const PetscInt    *leaves;
1476:   const PetscSFNode *roots;
1477:   PetscSFNode       *rootNodes, *leafNodes, *pointRemote;
1478:   PetscErrorCode     ierr;

1482:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);

1484:   PetscSFGetGraph(migrationSF, &nroots, &nleaves, &leaves, &roots);
1485:   PetscMalloc2(nroots, &rootNodes, nleaves, &leafNodes);
1486:   if (ownership) {
1487:     /* Point ownership vote: Process with highest rank ownes shared points */
1488:     for (p = 0; p < nleaves; ++p) {
1489:       /* Either put in a bid or we know we own it */
1490:       leafNodes[p].rank  = rank;
1491:       leafNodes[p].index = p;
1492:     }
1493:     for (p = 0; p < nroots; p++) {
1494:       /* Root must not participate in the reduction, flag so that MAXLOC does not use */
1495:       rootNodes[p].rank  = -3;
1496:       rootNodes[p].index = -3;
1497:     }
1498:     PetscSFReduceBegin(migrationSF, MPIU_2INT, leafNodes, rootNodes, MPI_MAXLOC);
1499:     PetscSFReduceEnd(migrationSF, MPIU_2INT, leafNodes, rootNodes, MPI_MAXLOC);
1500:   } else {
1501:     for (p = 0; p < nroots; p++) {
1502:       rootNodes[p].index = -1;
1503:       rootNodes[p].rank = rank;
1504:     };
1505:     for (p = 0; p < nleaves; p++) {
1506:       /* Write new local id into old location */
1507:       if (roots[p].rank == rank) {
1508:         rootNodes[roots[p].index].index = leaves ? leaves[p] : p;
1509:       }
1510:     }
1511:   }
1512:   PetscSFBcastBegin(migrationSF, MPIU_2INT, rootNodes, leafNodes);
1513:   PetscSFBcastEnd(migrationSF, MPIU_2INT, rootNodes, leafNodes);

1515:   for (npointLeaves = 0, p = 0; p < nleaves; p++) {if (leafNodes[p].rank != rank) npointLeaves++;}
1516:   PetscMalloc1(npointLeaves, &pointLocal);
1517:   PetscMalloc1(npointLeaves, &pointRemote);
1518:   for (idx = 0, p = 0; p < nleaves; p++) {
1519:     if (leafNodes[p].rank != rank) {
1520:       pointLocal[idx] = p;
1521:       pointRemote[idx] = leafNodes[p];
1522:       idx++;
1523:     }
1524:   }
1525:   PetscSFCreate(PetscObjectComm((PetscObject) dm), pointSF);
1526:   PetscSFSetFromOptions(*pointSF);
1527:   PetscSFSetGraph(*pointSF, nleaves, npointLeaves, pointLocal, PETSC_OWN_POINTER, pointRemote, PETSC_OWN_POINTER);
1528:   PetscFree2(rootNodes, leafNodes);
1529:   return(0);
1530: }

1532: /*@C
1533:   DMPlexMigrate  - Migrates internal DM data over the supplied star forest

1535:   Input Parameter:
1536: + dm       - The source DMPlex object
1537: . sf       - The star forest communication context describing the migration pattern

1539:   Output Parameter:
1540: - targetDM - The target DMPlex object

1542:   Level: intermediate

1544: .seealso: DMPlexDistribute(), DMPlexDistributeOverlap()
1545: @*/
1546: PetscErrorCode DMPlexMigrate(DM dm, PetscSF sf, DM targetDM)
1547: {
1548:   MPI_Comm               comm;
1549:   PetscInt               dim, nroots;
1550:   PetscSF                sfPoint;
1551:   ISLocalToGlobalMapping ltogMigration;
1552:   ISLocalToGlobalMapping ltogOriginal = NULL;
1553:   PetscBool              flg;
1554:   PetscErrorCode         ierr;

1558:   PetscLogEventBegin(DMPLEX_Migrate, dm, 0, 0, 0);
1559:   PetscObjectGetComm((PetscObject) dm, &comm);
1560:   DMGetDimension(dm, &dim);
1561:   DMSetDimension(targetDM, dim);

1563:   /* Check for a one-to-all distribution pattern */
1564:   DMGetPointSF(dm, &sfPoint);
1565:   PetscSFGetGraph(sfPoint, &nroots, NULL, NULL, NULL);
1566:   if (nroots >= 0) {
1567:     IS                     isOriginal;
1568:     PetscInt               n, size, nleaves;
1569:     PetscInt              *numbering_orig, *numbering_new;
1570:     /* Get the original point numbering */
1571:     DMPlexCreatePointNumbering(dm, &isOriginal);
1572:     ISLocalToGlobalMappingCreateIS(isOriginal, &ltogOriginal);
1573:     ISLocalToGlobalMappingGetSize(ltogOriginal, &size);
1574:     ISLocalToGlobalMappingGetBlockIndices(ltogOriginal, (const PetscInt**)&numbering_orig);
1575:     /* Convert to positive global numbers */
1576:     for (n=0; n<size; n++) {if (numbering_orig[n] < 0) numbering_orig[n] = -(numbering_orig[n]+1);}
1577:     /* Derive the new local-to-global mapping from the old one */
1578:     PetscSFGetGraph(sf, NULL, &nleaves, NULL, NULL);
1579:     PetscMalloc1(nleaves, &numbering_new);
1580:     PetscSFBcastBegin(sf, MPIU_INT, (PetscInt *) numbering_orig, numbering_new);
1581:     PetscSFBcastEnd(sf, MPIU_INT, (PetscInt *) numbering_orig, numbering_new);
1582:     ISLocalToGlobalMappingCreate(comm, 1, nleaves, (const PetscInt*) numbering_new, PETSC_OWN_POINTER, &ltogMigration);
1583:     ISLocalToGlobalMappingRestoreIndices(ltogOriginal, (const PetscInt**)&numbering_orig);
1584:     ISDestroy(&isOriginal);
1585:   } else {
1586:     /* One-to-all distribution pattern: We can derive LToG from SF */
1587:     ISLocalToGlobalMappingCreateSF(sf, 0, &ltogMigration);
1588:   }
1589:   PetscOptionsHasName(((PetscObject) dm)->options,((PetscObject) dm)->prefix, "-partition_view", &flg);
1590:   if (flg) {
1591:     PetscPrintf(comm, "Point renumbering for DM migration:\n");
1592:     ISLocalToGlobalMappingView(ltogMigration, NULL);
1593:   }
1594:   /* Migrate DM data to target DM */
1595:   DMPlexDistributeCones(dm, sf, ltogOriginal, ltogMigration, targetDM);
1596:   DMPlexDistributeLabels(dm, sf, targetDM);
1597:   DMPlexDistributeCoordinates(dm, sf, targetDM);
1598:   DMPlexDistributeSetupHybrid(dm, sf, ltogMigration, targetDM);
1599:   DMPlexDistributeSetupTree(dm, sf, ltogOriginal, ltogMigration, targetDM);
1600:   ISLocalToGlobalMappingDestroy(&ltogOriginal);
1601:   ISLocalToGlobalMappingDestroy(&ltogMigration);
1602:   PetscLogEventEnd(DMPLEX_Migrate, dm, 0, 0, 0);
1603:   return(0);
1604: }

1606: /*@C
1607:   DMPlexDistribute - Distributes the mesh and any associated sections.

1609:   Not Collective

1611:   Input Parameter:
1612: + dm  - The original DMPlex object
1613: - overlap - The overlap of partitions, 0 is the default

1615:   Output Parameter:
1616: + sf - The PetscSF used for point distribution
1617: - parallelMesh - The distributed DMPlex object, or NULL

1619:   Note: If the mesh was not distributed, the return value is NULL.

1621:   The user can control the definition of adjacency for the mesh using DMPlexSetAdjacencyUseCone() and
1622:   DMPlexSetAdjacencyUseClosure(). They should choose the combination appropriate for the function
1623:   representation on the mesh.

1625:   Level: intermediate

1627: .keywords: mesh, elements
1628: .seealso: DMPlexCreate(), DMPlexDistributeByFace(), DMPlexSetAdjacencyUseCone(), DMPlexSetAdjacencyUseClosure()
1629: @*/
1630: PetscErrorCode DMPlexDistribute(DM dm, PetscInt overlap, PetscSF *sf, DM *dmParallel)
1631: {
1632:   MPI_Comm               comm;
1633:   PetscPartitioner       partitioner;
1634:   IS                     cellPart;
1635:   PetscSection           cellPartSection;
1636:   DM                     dmCoord;
1637:   DMLabel                lblPartition, lblMigration;
1638:   PetscSF                sfProcess, sfMigration, sfStratified, sfPoint;
1639:   PetscBool              flg;
1640:   PetscMPIInt            rank, size, p;
1641:   PetscErrorCode         ierr;


1648:   PetscLogEventBegin(DMPLEX_Distribute,dm,0,0,0);
1649:   PetscObjectGetComm((PetscObject)dm,&comm);
1650:   MPI_Comm_rank(comm, &rank);
1651:   MPI_Comm_size(comm, &size);

1653:   if (sf) *sf = NULL;
1654:   *dmParallel = NULL;
1655:   if (size == 1) {
1656:     PetscLogEventEnd(DMPLEX_Distribute,dm,0,0,0);
1657:     return(0);
1658:   }

1660:   /* Create cell partition */
1661:   PetscLogEventBegin(PETSCPARTITIONER_Partition,dm,0,0,0);
1662:   PetscSectionCreate(comm, &cellPartSection);
1663:   DMPlexGetPartitioner(dm, &partitioner);
1664:   PetscPartitionerPartition(partitioner, dm, cellPartSection, &cellPart);
1665:   {
1666:     /* Convert partition to DMLabel */
1667:     PetscInt proc, pStart, pEnd, npoints, poffset;
1668:     const PetscInt *points;
1669:     DMLabelCreate("Point Partition", &lblPartition);
1670:     ISGetIndices(cellPart, &points);
1671:     PetscSectionGetChart(cellPartSection, &pStart, &pEnd);
1672:     for (proc = pStart; proc < pEnd; proc++) {
1673:       PetscSectionGetDof(cellPartSection, proc, &npoints);
1674:       PetscSectionGetOffset(cellPartSection, proc, &poffset);
1675:       for (p = poffset; p < poffset+npoints; p++) {
1676:         DMLabelSetValue(lblPartition, points[p], proc);
1677:       }
1678:     }
1679:     ISRestoreIndices(cellPart, &points);
1680:   }
1681:   DMPlexPartitionLabelClosure(dm, lblPartition);
1682:   {
1683:     /* Build a global process SF */
1684:     PetscSFNode *remoteProc;
1685:     PetscMalloc1(size, &remoteProc);
1686:     for (p = 0; p < size; ++p) {
1687:       remoteProc[p].rank  = p;
1688:       remoteProc[p].index = rank;
1689:     }
1690:     PetscSFCreate(comm, &sfProcess);
1691:     PetscObjectSetName((PetscObject) sfProcess, "Process SF");
1692:     PetscSFSetGraph(sfProcess, size, size, NULL, PETSC_OWN_POINTER, remoteProc, PETSC_OWN_POINTER);
1693:   }
1694:   DMLabelCreate("Point migration", &lblMigration);
1695:   DMPlexPartitionLabelInvert(dm, lblPartition, sfProcess, lblMigration);
1696:   DMPlexPartitionLabelCreateSF(dm, lblMigration, &sfMigration);
1697:   /* Stratify the SF in case we are migrating an already parallel plex */
1698:   DMPlexStratifyMigrationSF(dm, sfMigration, &sfStratified);
1699:   PetscSFDestroy(&sfMigration);
1700:   sfMigration = sfStratified;
1701:   PetscLogEventEnd(PETSCPARTITIONER_Partition,dm,0,0,0);
1702:   PetscOptionsHasName(((PetscObject) dm)->options,((PetscObject) dm)->prefix, "-partition_view", &flg);
1703:   if (flg) {
1704:     DMLabelView(lblPartition, PETSC_VIEWER_STDOUT_WORLD);
1705:     PetscSFView(sfMigration, PETSC_VIEWER_STDOUT_WORLD);
1706:   }

1708:   /* Create non-overlapping parallel DM and migrate internal data */
1709:   DMPlexCreate(comm, dmParallel);
1710:   PetscObjectSetName((PetscObject) *dmParallel, "Parallel Mesh");
1711:   DMPlexMigrate(dm, sfMigration, *dmParallel);

1713:   /* Build the point SF without overlap */
1714:   DMPlexCreatePointSF(*dmParallel, sfMigration, PETSC_TRUE, &sfPoint);
1715:   DMSetPointSF(*dmParallel, sfPoint);
1716:   DMGetCoordinateDM(*dmParallel, &dmCoord);
1717:   if (dmCoord) {DMSetPointSF(dmCoord, sfPoint);}
1718:   if (flg) {PetscSFView(sfPoint, PETSC_VIEWER_STDOUT_WORLD);}

1720:   if (overlap > 0) {
1721:     DM                 dmOverlap;
1722:     PetscInt           nroots, nleaves;
1723:     PetscSFNode       *newRemote;
1724:     const PetscSFNode *oldRemote;
1725:     PetscSF            sfOverlap, sfOverlapPoint;
1726:     /* Add the partition overlap to the distributed DM */
1727:     DMPlexDistributeOverlap(*dmParallel, overlap, &sfOverlap, &dmOverlap);
1728:     DMDestroy(dmParallel);
1729:     *dmParallel = dmOverlap;
1730:     if (flg) {
1731:       PetscPrintf(comm, "Overlap Migration SF:\n");
1732:       PetscSFView(sfOverlap, NULL);
1733:     }

1735:     /* Re-map the migration SF to establish the full migration pattern */
1736:     PetscSFGetGraph(sfMigration, &nroots, NULL, NULL, &oldRemote);
1737:     PetscSFGetGraph(sfOverlap, NULL, &nleaves, NULL, NULL);
1738:     PetscMalloc1(nleaves, &newRemote);
1739:     PetscSFBcastBegin(sfOverlap, MPIU_2INT, oldRemote, newRemote);
1740:     PetscSFBcastEnd(sfOverlap, MPIU_2INT, oldRemote, newRemote);
1741:     PetscSFCreate(comm, &sfOverlapPoint);
1742:     PetscSFSetGraph(sfOverlapPoint, nroots, nleaves, NULL, PETSC_OWN_POINTER, newRemote, PETSC_OWN_POINTER);
1743:     PetscSFDestroy(&sfOverlap);
1744:     PetscSFDestroy(&sfMigration);
1745:     sfMigration = sfOverlapPoint;
1746:   }
1747:   /* Cleanup Partition */
1748:   PetscSFDestroy(&sfProcess);
1749:   DMLabelDestroy(&lblPartition);
1750:   DMLabelDestroy(&lblMigration);
1751:   PetscSectionDestroy(&cellPartSection);
1752:   ISDestroy(&cellPart);
1753:   /* Copy BC */
1754:   DMCopyBoundary(dm, *dmParallel);
1755:   /* Create sfNatural */
1756:   if (dm->useNatural) {
1757:     PetscSection section;

1759:     DMGetDefaultSection(dm, &section);
1760:     DMPlexCreateGlobalToNaturalSF(*dmParallel, section, sfMigration, &(*dmParallel)->sfNatural);
1761:     DMSetUseNatural(*dmParallel, PETSC_TRUE);
1762:   }
1763:   /* Cleanup */
1764:   if (sf) {*sf = sfMigration;}
1765:   else    {PetscSFDestroy(&sfMigration);}
1766:   PetscSFDestroy(&sfPoint);
1767:   PetscLogEventEnd(DMPLEX_Distribute,dm,0,0,0);
1768:   return(0);
1769: }

1771: /*@C
1772:   DMPlexDistributeOverlap - Add partition overlap to a distributed non-overlapping DM.

1774:   Not Collective

1776:   Input Parameter:
1777: + dm  - The non-overlapping distrbuted DMPlex object
1778: - overlap - The overlap of partitions, 0 is the default

1780:   Output Parameter:
1781: + sf - The PetscSF used for point distribution
1782: - dmOverlap - The overlapping distributed DMPlex object, or NULL

1784:   Note: If the mesh was not distributed, the return value is NULL.

1786:   The user can control the definition of adjacency for the mesh using DMPlexGetAdjacencyUseCone() and
1787:   DMPlexSetAdjacencyUseClosure(). They should choose the combination appropriate for the function
1788:   representation on the mesh.

1790:   Level: intermediate

1792: .keywords: mesh, elements
1793: .seealso: DMPlexCreate(), DMPlexDistributeByFace(), DMPlexSetAdjacencyUseCone(), DMPlexSetAdjacencyUseClosure()
1794: @*/
1795: PetscErrorCode DMPlexDistributeOverlap(DM dm, PetscInt overlap, PetscSF *sf, DM *dmOverlap)
1796: {
1797:   MPI_Comm               comm;
1798:   PetscMPIInt            size, rank;
1799:   PetscSection           rootSection, leafSection;
1800:   IS                     rootrank, leafrank;
1801:   DM                     dmCoord;
1802:   DMLabel                lblOverlap;
1803:   PetscSF                sfOverlap, sfStratified, sfPoint;
1804:   PetscErrorCode         ierr;


1811:   PetscObjectGetComm((PetscObject)dm,&comm);
1812:   MPI_Comm_size(comm, &size);
1813:   MPI_Comm_rank(comm, &rank);
1814:   if (size == 1) {*dmOverlap = NULL; return(0);}
1815:   PetscLogEventBegin(DMPLEX_DistributeOverlap, dm, 0, 0, 0);

1817:   /* Compute point overlap with neighbouring processes on the distributed DM */
1818:   PetscLogEventBegin(PETSCPARTITIONER_Partition,dm,0,0,0);
1819:   PetscSectionCreate(comm, &rootSection);
1820:   PetscSectionCreate(comm, &leafSection);
1821:   DMPlexDistributeOwnership(dm, rootSection, &rootrank, leafSection, &leafrank);
1822:   DMPlexCreateOverlap(dm, overlap, rootSection, rootrank, leafSection, leafrank, &lblOverlap);
1823:   /* Convert overlap label to stratified migration SF */
1824:   DMPlexPartitionLabelCreateSF(dm, lblOverlap, &sfOverlap);
1825:   DMPlexStratifyMigrationSF(dm, sfOverlap, &sfStratified);
1826:   PetscSFDestroy(&sfOverlap);
1827:   sfOverlap = sfStratified;
1828:   PetscObjectSetName((PetscObject) sfOverlap, "Overlap SF");
1829:   PetscSFSetFromOptions(sfOverlap);

1831:   PetscSectionDestroy(&rootSection);
1832:   PetscSectionDestroy(&leafSection);
1833:   ISDestroy(&rootrank);
1834:   ISDestroy(&leafrank);
1835:   PetscLogEventEnd(PETSCPARTITIONER_Partition,dm,0,0,0);

1837:   /* Build the overlapping DM */
1838:   DMPlexCreate(comm, dmOverlap);
1839:   PetscObjectSetName((PetscObject) *dmOverlap, "Parallel Mesh");
1840:   DMPlexMigrate(dm, sfOverlap, *dmOverlap);
1841:   /* Build the new point SF */
1842:   DMPlexCreatePointSF(*dmOverlap, sfOverlap, PETSC_FALSE, &sfPoint);
1843:   DMSetPointSF(*dmOverlap, sfPoint);
1844:   DMGetCoordinateDM(*dmOverlap, &dmCoord);
1845:   if (dmCoord) {DMSetPointSF(dmCoord, sfPoint);}
1846:   PetscSFDestroy(&sfPoint);
1847:   /* Cleanup overlap partition */
1848:   DMLabelDestroy(&lblOverlap);
1849:   if (sf) *sf = sfOverlap;
1850:   else    {PetscSFDestroy(&sfOverlap);}
1851:   PetscLogEventEnd(DMPLEX_DistributeOverlap, dm, 0, 0, 0);
1852:   return(0);
1853: }

1855: /*@C
1856:   DMPlexGetGatherDM - Get a copy of the DMPlex that gathers all points on the
1857:   root process of the original's communicator.

1859:   Input Parameters:
1860: . dm - the original DMPlex object

1862:   Output Parameters:
1863: . gatherMesh - the gathered DM object, or NULL

1865:   Level: intermediate

1867: .keywords: mesh
1868: .seealso: DMPlexDistribute(), DMPlexGetRedundantDM()
1869: @*/
1870: PetscErrorCode DMPlexGetGatherDM(DM dm, DM * gatherMesh)
1871: {
1872:   MPI_Comm       comm;
1873:   PetscMPIInt    size;
1874:   PetscPartitioner oldPart, gatherPart;

1879:   comm = PetscObjectComm((PetscObject)dm);
1880:   MPI_Comm_size(comm,&size);
1881:   *gatherMesh = NULL;
1882:   if (size == 1) return(0);
1883:   DMPlexGetPartitioner(dm,&oldPart);
1884:   PetscObjectReference((PetscObject)oldPart);
1885:   PetscPartitionerCreate(comm,&gatherPart);
1886:   PetscPartitionerSetType(gatherPart,PETSCPARTITIONERGATHER);
1887:   DMPlexSetPartitioner(dm,gatherPart);
1888:   DMPlexDistribute(dm,0,NULL,gatherMesh);
1889:   DMPlexSetPartitioner(dm,oldPart);
1890:   PetscPartitionerDestroy(&gatherPart);
1891:   PetscPartitionerDestroy(&oldPart);
1892:   return(0);
1893: }

1895: /*@C
1896:   DMPlexGetRedundantDM - Get a copy of the DMPlex that is completely copied on each process.

1898:   Input Parameters:
1899: . dm - the original DMPlex object

1901:   Output Parameters:
1902: . redundantMesh - the redundant DM object, or NULL

1904:   Level: intermediate

1906: .keywords: mesh
1907: .seealso: DMPlexDistribute(), DMPlexGetGatherDM()
1908: @*/
1909: PetscErrorCode DMPlexGetRedundantDM(DM dm, DM * redundantMesh)
1910: {
1911:   MPI_Comm       comm;
1912:   PetscMPIInt    size, rank;
1913:   PetscInt       pStart, pEnd, p;
1914:   PetscInt       numPoints = -1;
1915:   PetscSF        migrationSF, sfPoint;
1916:   DM             gatherDM, dmCoord;
1917:   PetscSFNode    *points;

1922:   comm = PetscObjectComm((PetscObject)dm);
1923:   MPI_Comm_size(comm,&size);
1924:   *redundantMesh = NULL;
1925:   if (size == 1) {
1926:     PetscObjectReference((PetscObject) dm);
1927:     *redundantMesh = dm;
1928:     return(0);
1929:   }
1930:   DMPlexGetGatherDM(dm,&gatherDM);
1931:   if (!gatherDM) return(0);
1932:   MPI_Comm_rank(comm,&rank);
1933:   DMPlexGetChart(gatherDM,&pStart,&pEnd);
1934:   numPoints = pEnd - pStart;
1935:   MPI_Bcast(&numPoints,1,MPIU_INT,0,comm);
1936:   PetscMalloc1(numPoints,&points);
1937:   PetscSFCreate(comm,&migrationSF);
1938:   for (p = 0; p < numPoints; p++) {
1939:     points[p].index = p;
1940:     points[p].rank  = 0;
1941:   }
1942:   PetscSFSetGraph(migrationSF,pEnd-pStart,numPoints,NULL,PETSC_OWN_POINTER,points,PETSC_OWN_POINTER);
1943:   DMPlexCreate(comm, redundantMesh);
1944:   PetscObjectSetName((PetscObject) *redundantMesh, "Redundant Mesh");
1945:   DMPlexMigrate(gatherDM, migrationSF, *redundantMesh);
1946:   DMPlexCreatePointSF(*redundantMesh, migrationSF, PETSC_FALSE, &sfPoint);
1947:   DMSetPointSF(*redundantMesh, sfPoint);
1948:   DMGetCoordinateDM(*redundantMesh, &dmCoord);
1949:   if (dmCoord) {DMSetPointSF(dmCoord, sfPoint);}
1950:   PetscSFDestroy(&sfPoint);
1951:   PetscSFDestroy(&migrationSF);
1952:   DMDestroy(&gatherDM);
1953:   return(0);
1954: }