Actual source code: dm.c

petsc-master 2017-03-22
Report Typos and Errors
  1:  #include <petsc/private/dmimpl.h>
  2:  #include <petsc/private/dmlabelimpl.h>
  3:  #include <petsc/private/petscdsimpl.h>
  4:  #include <petscdmplex.h>
  5:  #include <petscsf.h>
  6:  #include <petscds.h>

  8: PetscClassId  DM_CLASSID;
  9: PetscLogEvent DM_Convert, DM_GlobalToLocal, DM_LocalToGlobal, DM_LocalToLocal, DM_LocatePoints, DM_Coarsen, DM_Refine, DM_CreateInterpolation, DM_CreateRestriction;

 11: const char *const DMBoundaryTypes[] = {"NONE","GHOSTED","MIRROR","PERIODIC","TWIST","DM_BOUNDARY_",0};

 13: /*@
 14:   DMCreate - Creates an empty DM object. The type can then be set with DMSetType().

 16:    If you never  call DMSetType()  it will generate an
 17:    error when you try to use the vector.

 19:   Collective on MPI_Comm

 21:   Input Parameter:
 22: . comm - The communicator for the DM object

 24:   Output Parameter:
 25: . dm - The DM object

 27:   Level: beginner

 29: .seealso: DMSetType(), DMDA, DMSLICED, DMCOMPOSITE, DMPLEX, DMMOAB, DMNETWORK
 30: @*/
 31: PetscErrorCode  DMCreate(MPI_Comm comm,DM *dm)
 32: {
 33:   DM             v;

 38:   *dm = NULL;
 39:   PetscSysInitializePackage();
 40:   VecInitializePackage();
 41:   MatInitializePackage();
 42:   DMInitializePackage();

 44:   PetscHeaderCreate(v, DM_CLASSID, "DM", "Distribution Manager", "DM", comm, DMDestroy, DMView);

 46:   v->ltogmap                  = NULL;
 47:   v->bs                       = 1;
 48:   v->coloringtype             = IS_COLORING_GLOBAL;
 49:   PetscSFCreate(comm, &v->sf);
 50:   PetscSFCreate(comm, &v->defaultSF);
 51:   v->labels                   = NULL;
 52:   v->depthLabel               = NULL;
 53:   v->defaultSection           = NULL;
 54:   v->defaultGlobalSection     = NULL;
 55:   v->defaultConstraintSection = NULL;
 56:   v->defaultConstraintMat     = NULL;
 57:   v->L                        = NULL;
 58:   v->maxCell                  = NULL;
 59:   v->bdtype                   = NULL;
 60:   v->dimEmbed                 = PETSC_DEFAULT;
 61:   {
 62:     PetscInt i;
 63:     for (i = 0; i < 10; ++i) {
 64:       v->nullspaceConstructors[i] = NULL;
 65:     }
 66:   }
 67:   PetscDSCreate(comm, &v->prob);
 68:   v->dmBC = NULL;
 69:   v->coarseMesh = NULL;
 70:   v->outputSequenceNum = -1;
 71:   v->outputSequenceVal = 0.0;
 72:   DMSetVecType(v,VECSTANDARD);
 73:   DMSetMatType(v,MATAIJ);
 74:   PetscNew(&(v->labels));
 75:   v->labels->refct = 1;
 76:   *dm = v;
 77:   return(0);
 78: }

 80: /*@
 81:   DMClone - Creates a DM object with the same topology as the original.

 83:   Collective on MPI_Comm

 85:   Input Parameter:
 86: . dm - The original DM object

 88:   Output Parameter:
 89: . newdm  - The new DM object

 91:   Level: beginner

 93: .keywords: DM, topology, create
 94: @*/
 95: PetscErrorCode DMClone(DM dm, DM *newdm)
 96: {
 97:   PetscSF        sf;
 98:   Vec            coords;
 99:   void          *ctx;
100:   PetscInt       dim;

106:   DMCreate(PetscObjectComm((PetscObject) dm), newdm);
107:   PetscFree((*newdm)->labels);
108:   dm->labels->refct++;
109:   (*newdm)->labels = dm->labels;
110:   (*newdm)->depthLabel = dm->depthLabel;
111:   DMGetDimension(dm, &dim);
112:   DMSetDimension(*newdm, dim);
113:   if (dm->ops->clone) {
114:     (*dm->ops->clone)(dm, newdm);
115:   }
116:   (*newdm)->setupcalled = dm->setupcalled;
117:   DMGetPointSF(dm, &sf);
118:   DMSetPointSF(*newdm, sf);
119:   DMGetApplicationContext(dm, &ctx);
120:   DMSetApplicationContext(*newdm, ctx);
121:   if (dm->coordinateDM) {
122:     DM           ncdm;
123:     PetscSection cs;
124:     PetscInt     pEnd = -1, pEndMax = -1;

126:     DMGetDefaultSection(dm->coordinateDM, &cs);
127:     if (cs) {PetscSectionGetChart(cs, NULL, &pEnd);}
128:     MPI_Allreduce(&pEnd,&pEndMax,1,MPIU_INT,MPI_MAX,PetscObjectComm((PetscObject)dm));
129:     if (pEndMax >= 0) {
130:       DMClone(dm->coordinateDM, &ncdm);
131:       DMSetDefaultSection(ncdm, cs);
132:       DMSetCoordinateDM(*newdm, ncdm);
133:       DMDestroy(&ncdm);
134:     }
135:   }
136:   DMGetCoordinatesLocal(dm, &coords);
137:   if (coords) {
138:     DMSetCoordinatesLocal(*newdm, coords);
139:   } else {
140:     DMGetCoordinates(dm, &coords);
141:     if (coords) {DMSetCoordinates(*newdm, coords);}
142:   }
143:   if (dm->maxCell) {
144:     const PetscReal *maxCell, *L;
145:     const DMBoundaryType *bd;
146:     DMGetPeriodicity(dm,     &maxCell, &L, &bd);
147:     DMSetPeriodicity(*newdm,  maxCell,  L,  bd);
148:   }
149:   return(0);
150: }

152: /*@C
153:        DMSetVecType - Sets the type of vector created with DMCreateLocalVector() and DMCreateGlobalVector()

155:    Logically Collective on DM

157:    Input Parameter:
158: +  da - initial distributed array
159: .  ctype - the vector type, currently either VECSTANDARD or VECCUSP

161:    Options Database:
162: .   -dm_vec_type ctype

164:    Level: intermediate

166: .seealso: DMCreate(), DMDestroy(), DM, DMDAInterpolationType, VecType, DMGetVecType()
167: @*/
168: PetscErrorCode  DMSetVecType(DM da,VecType ctype)
169: {

174:   PetscFree(da->vectype);
175:   PetscStrallocpy(ctype,(char**)&da->vectype);
176:   return(0);
177: }

179: /*@C
180:        DMGetVecType - Gets the type of vector created with DMCreateLocalVector() and DMCreateGlobalVector()

182:    Logically Collective on DM

184:    Input Parameter:
185: .  da - initial distributed array

187:    Output Parameter:
188: .  ctype - the vector type

190:    Level: intermediate

192: .seealso: DMCreate(), DMDestroy(), DM, DMDAInterpolationType, VecType
193: @*/
194: PetscErrorCode  DMGetVecType(DM da,VecType *ctype)
195: {
198:   *ctype = da->vectype;
199:   return(0);
200: }

202: /*@
203:   VecGetDM - Gets the DM defining the data layout of the vector

205:   Not collective

207:   Input Parameter:
208: . v - The Vec

210:   Output Parameter:
211: . dm - The DM

213:   Level: intermediate

215: .seealso: VecSetDM(), DMGetLocalVector(), DMGetGlobalVector(), DMSetVecType()
216: @*/
217: PetscErrorCode VecGetDM(Vec v, DM *dm)
218: {

224:   PetscObjectQuery((PetscObject) v, "__PETSc_dm", (PetscObject*) dm);
225:   return(0);
226: }

228: /*@
229:   VecSetDM - Sets the DM defining the data layout of the vector.

231:   Not collective

233:   Input Parameters:
234: + v - The Vec
235: - dm - The DM

237:   Note: This is NOT the same as DMCreateGlobalVector() since it does not change the view methods or perform other customization, but merely sets the DM member.

239:   Level: intermediate

241: .seealso: VecGetDM(), DMGetLocalVector(), DMGetGlobalVector(), DMSetVecType()
242: @*/
243: PetscErrorCode VecSetDM(Vec v, DM dm)
244: {

250:   PetscObjectCompose((PetscObject) v, "__PETSc_dm", (PetscObject) dm);
251:   return(0);
252: }

254: /*@C
255:        DMSetMatType - Sets the type of matrix created with DMCreateMatrix()

257:    Logically Collective on DM

259:    Input Parameter:
260: +  dm - the DM context
261: -  ctype - the matrix type

263:    Options Database:
264: .   -dm_mat_type ctype

266:    Level: intermediate

268: .seealso: DMDACreate1d(), DMDACreate2d(), DMDACreate3d(), DMCreateMatrix(), DMSetMatrixPreallocateOnly(), MatType, DMGetMatType()
269: @*/
270: PetscErrorCode  DMSetMatType(DM dm,MatType ctype)
271: {

276:   PetscFree(dm->mattype);
277:   PetscStrallocpy(ctype,(char**)&dm->mattype);
278:   return(0);
279: }

281: /*@C
282:        DMGetMatType - Gets the type of matrix created with DMCreateMatrix()

284:    Logically Collective on DM

286:    Input Parameter:
287: .  dm - the DM context

289:    Output Parameter:
290: .  ctype - the matrix type

292:    Options Database:
293: .   -dm_mat_type ctype

295:    Level: intermediate

297: .seealso: DMDACreate1d(), DMDACreate2d(), DMDACreate3d(), DMCreateMatrix(), DMSetMatrixPreallocateOnly(), MatType, DMSetMatType()
298: @*/
299: PetscErrorCode  DMGetMatType(DM dm,MatType *ctype)
300: {
303:   *ctype = dm->mattype;
304:   return(0);
305: }

307: /*@
308:   MatGetDM - Gets the DM defining the data layout of the matrix

310:   Not collective

312:   Input Parameter:
313: . A - The Mat

315:   Output Parameter:
316: . dm - The DM

318:   Level: intermediate

320: .seealso: MatSetDM(), DMCreateMatrix(), DMSetMatType()
321: @*/
322: PetscErrorCode MatGetDM(Mat A, DM *dm)
323: {

329:   PetscObjectQuery((PetscObject) A, "__PETSc_dm", (PetscObject*) dm);
330:   return(0);
331: }

333: /*@
334:   MatSetDM - Sets the DM defining the data layout of the matrix

336:   Not collective

338:   Input Parameters:
339: + A - The Mat
340: - dm - The DM

342:   Level: intermediate

344: .seealso: MatGetDM(), DMCreateMatrix(), DMSetMatType()
345: @*/
346: PetscErrorCode MatSetDM(Mat A, DM dm)
347: {

353:   PetscObjectCompose((PetscObject) A, "__PETSc_dm", (PetscObject) dm);
354:   return(0);
355: }

357: /*@C
358:    DMSetOptionsPrefix - Sets the prefix used for searching for all
359:    DM options in the database.

361:    Logically Collective on DM

363:    Input Parameter:
364: +  da - the DM context
365: -  prefix - the prefix to prepend to all option names

367:    Notes:
368:    A hyphen (-) must NOT be given at the beginning of the prefix name.
369:    The first character of all runtime options is AUTOMATICALLY the hyphen.

371:    Level: advanced

373: .keywords: DM, set, options, prefix, database

375: .seealso: DMSetFromOptions()
376: @*/
377: PetscErrorCode  DMSetOptionsPrefix(DM dm,const char prefix[])
378: {

383:   PetscObjectSetOptionsPrefix((PetscObject)dm,prefix);
384:   if (dm->sf) {
385:     PetscObjectSetOptionsPrefix((PetscObject)dm->sf,prefix);
386:   }
387:   if (dm->defaultSF) {
388:     PetscObjectSetOptionsPrefix((PetscObject)dm->defaultSF,prefix);
389:   }
390:   return(0);
391: }

393: /*@C
394:    DMAppendOptionsPrefix - Appends to the prefix used for searching for all
395:    DM options in the database.

397:    Logically Collective on DM

399:    Input Parameters:
400: +  dm - the DM context
401: -  prefix - the prefix string to prepend to all DM option requests

403:    Notes:
404:    A hyphen (-) must NOT be given at the beginning of the prefix name.
405:    The first character of all runtime options is AUTOMATICALLY the hyphen.

407:    Level: advanced

409: .keywords: DM, append, options, prefix, database

411: .seealso: DMSetOptionsPrefix(), DMGetOptionsPrefix()
412: @*/
413: PetscErrorCode  DMAppendOptionsPrefix(DM dm,const char prefix[])
414: {

419:   PetscObjectAppendOptionsPrefix((PetscObject)dm,prefix);
420:   return(0);
421: }

423: /*@C
424:    DMGetOptionsPrefix - Gets the prefix used for searching for all
425:    DM options in the database.

427:    Not Collective

429:    Input Parameters:
430: .  dm - the DM context

432:    Output Parameters:
433: .  prefix - pointer to the prefix string used is returned

435:    Notes: On the fortran side, the user should pass in a string 'prefix' of
436:    sufficient length to hold the prefix.

438:    Level: advanced

440: .keywords: DM, set, options, prefix, database

442: .seealso: DMSetOptionsPrefix(), DMAppendOptionsPrefix()
443: @*/
444: PetscErrorCode  DMGetOptionsPrefix(DM dm,const char *prefix[])
445: {

450:   PetscObjectGetOptionsPrefix((PetscObject)dm,prefix);
451:   return(0);
452: }

454: static PetscErrorCode DMCountNonCyclicReferences(DM dm, PetscBool recurseCoarse, PetscBool recurseFine, PetscInt *ncrefct)
455: {
456:   PetscInt i, refct = ((PetscObject) dm)->refct;
457:   DMNamedVecLink nlink;

461:   /* count all the circular references of DM and its contained Vecs */
462:   for (i=0; i<DM_MAX_WORK_VECTORS; i++) {
463:     if (dm->localin[i])  refct--;
464:     if (dm->globalin[i]) refct--;
465:   }
466:   for (nlink=dm->namedglobal; nlink; nlink=nlink->next) refct--;
467:   for (nlink=dm->namedlocal; nlink; nlink=nlink->next) refct--;
468:   if (dm->x) {
469:     DM obj;
470:     VecGetDM(dm->x, &obj);
471:     if (obj == dm) refct--;
472:   }
473:   if (dm->coarseMesh && dm->coarseMesh->fineMesh == dm) {
474:     refct--;
475:     if (recurseCoarse) {
476:       PetscInt coarseCount;

478:       DMCountNonCyclicReferences(dm->coarseMesh, PETSC_TRUE, PETSC_FALSE,&coarseCount);
479:       refct += coarseCount;
480:     }
481:   }
482:   if (dm->fineMesh && dm->fineMesh->coarseMesh == dm) {
483:     refct--;
484:     if (recurseFine) {
485:       PetscInt fineCount;

487:       DMCountNonCyclicReferences(dm->fineMesh, PETSC_FALSE, PETSC_TRUE,&fineCount);
488:       refct += fineCount;
489:     }
490:   }
491:   *ncrefct = refct;
492:   return(0);
493: }

495: PetscErrorCode DMDestroyLabelLinkList(DM dm)
496: {

500:   if (!--(dm->labels->refct)) {
501:     DMLabelLink next = dm->labels->next;

503:     /* destroy the labels */
504:     while (next) {
505:       DMLabelLink tmp = next->next;

507:       DMLabelDestroy(&next->label);
508:       PetscFree(next);
509:       next = tmp;
510:     }
511:     PetscFree(dm->labels);
512:   }
513:   return(0);
514: }

516: /*@
517:     DMDestroy - Destroys a vector packer or DM.

519:     Collective on DM

521:     Input Parameter:
522: .   dm - the DM object to destroy

524:     Level: developer

526: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix()

528: @*/
529: PetscErrorCode  DMDestroy(DM *dm)
530: {
531:   PetscInt       i, cnt;
532:   DMNamedVecLink nlink,nnext;

536:   if (!*dm) return(0);

539:   /* count all non-cyclic references in the doubly-linked list of coarse<->fine meshes */
540:   DMCountNonCyclicReferences(*dm,PETSC_TRUE,PETSC_TRUE,&cnt);
541:   --((PetscObject)(*dm))->refct;
542:   if (--cnt > 0) {*dm = 0; return(0);}
543:   /*
544:      Need this test because the dm references the vectors that
545:      reference the dm, so destroying the dm calls destroy on the
546:      vectors that cause another destroy on the dm
547:   */
548:   if (((PetscObject)(*dm))->refct < 0) return(0);
549:   ((PetscObject) (*dm))->refct = 0;
550:   for (i=0; i<DM_MAX_WORK_VECTORS; i++) {
551:     if ((*dm)->localout[i]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Destroying a DM that has a local vector obtained with DMGetLocalVector()");
552:     VecDestroy(&(*dm)->localin[i]);
553:   }
554:   nnext=(*dm)->namedglobal;
555:   (*dm)->namedglobal = NULL;
556:   for (nlink=nnext; nlink; nlink=nnext) { /* Destroy the named vectors */
557:     nnext = nlink->next;
558:     if (nlink->status != DMVEC_STATUS_IN) SETERRQ1(((PetscObject)*dm)->comm,PETSC_ERR_ARG_WRONGSTATE,"DM still has Vec named '%s' checked out",nlink->name);
559:     PetscFree(nlink->name);
560:     VecDestroy(&nlink->X);
561:     PetscFree(nlink);
562:   }
563:   nnext=(*dm)->namedlocal;
564:   (*dm)->namedlocal = NULL;
565:   for (nlink=nnext; nlink; nlink=nnext) { /* Destroy the named local vectors */
566:     nnext = nlink->next;
567:     if (nlink->status != DMVEC_STATUS_IN) SETERRQ1(((PetscObject)*dm)->comm,PETSC_ERR_ARG_WRONGSTATE,"DM still has Vec named '%s' checked out",nlink->name);
568:     PetscFree(nlink->name);
569:     VecDestroy(&nlink->X);
570:     PetscFree(nlink);
571:   }

573:   /* Destroy the list of hooks */
574:   {
575:     DMCoarsenHookLink link,next;
576:     for (link=(*dm)->coarsenhook; link; link=next) {
577:       next = link->next;
578:       PetscFree(link);
579:     }
580:     (*dm)->coarsenhook = NULL;
581:   }
582:   {
583:     DMRefineHookLink link,next;
584:     for (link=(*dm)->refinehook; link; link=next) {
585:       next = link->next;
586:       PetscFree(link);
587:     }
588:     (*dm)->refinehook = NULL;
589:   }
590:   {
591:     DMSubDomainHookLink link,next;
592:     for (link=(*dm)->subdomainhook; link; link=next) {
593:       next = link->next;
594:       PetscFree(link);
595:     }
596:     (*dm)->subdomainhook = NULL;
597:   }
598:   {
599:     DMGlobalToLocalHookLink link,next;
600:     for (link=(*dm)->gtolhook; link; link=next) {
601:       next = link->next;
602:       PetscFree(link);
603:     }
604:     (*dm)->gtolhook = NULL;
605:   }
606:   {
607:     DMLocalToGlobalHookLink link,next;
608:     for (link=(*dm)->ltoghook; link; link=next) {
609:       next = link->next;
610:       PetscFree(link);
611:     }
612:     (*dm)->ltoghook = NULL;
613:   }
614:   /* Destroy the work arrays */
615:   {
616:     DMWorkLink link,next;
617:     if ((*dm)->workout) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Work array still checked out");
618:     for (link=(*dm)->workin; link; link=next) {
619:       next = link->next;
620:       PetscFree(link->mem);
621:       PetscFree(link);
622:     }
623:     (*dm)->workin = NULL;
624:   }
625:   if (!--((*dm)->labels->refct)) {
626:     DMLabelLink next = (*dm)->labels->next;

628:     /* destroy the labels */
629:     while (next) {
630:       DMLabelLink tmp = next->next;

632:       DMLabelDestroy(&next->label);
633:       PetscFree(next);
634:       next = tmp;
635:     }
636:     PetscFree((*dm)->labels);
637:   }
638:   {
639:     DMBoundary next = (*dm)->boundary;
640:     while (next) {
641:       DMBoundary b = next;

643:       next = b->next;
644:       PetscFree(b);
645:     }
646:   }

648:   PetscObjectDestroy(&(*dm)->dmksp);
649:   PetscObjectDestroy(&(*dm)->dmsnes);
650:   PetscObjectDestroy(&(*dm)->dmts);

652:   if ((*dm)->ctx && (*dm)->ctxdestroy) {
653:     (*(*dm)->ctxdestroy)(&(*dm)->ctx);
654:   }
655:   VecDestroy(&(*dm)->x);
656:   MatFDColoringDestroy(&(*dm)->fd);
657:   DMClearGlobalVectors(*dm);
658:   ISLocalToGlobalMappingDestroy(&(*dm)->ltogmap);
659:   PetscFree((*dm)->vectype);
660:   PetscFree((*dm)->mattype);

662:   PetscSectionDestroy(&(*dm)->defaultSection);
663:   PetscSectionDestroy(&(*dm)->defaultGlobalSection);
664:   PetscLayoutDestroy(&(*dm)->map);
665:   PetscSectionDestroy(&(*dm)->defaultConstraintSection);
666:   MatDestroy(&(*dm)->defaultConstraintMat);
667:   PetscSFDestroy(&(*dm)->sf);
668:   PetscSFDestroy(&(*dm)->defaultSF);
669:   PetscSFDestroy(&(*dm)->sfNatural);

671:   if ((*dm)->coarseMesh && (*dm)->coarseMesh->fineMesh == *dm) {
672:     DMSetFineDM((*dm)->coarseMesh,NULL);
673:   }
674:   DMDestroy(&(*dm)->coarseMesh);
675:   if ((*dm)->fineMesh && (*dm)->fineMesh->coarseMesh == *dm) {
676:     DMSetCoarseDM((*dm)->fineMesh,NULL);
677:   }
678:   DMDestroy(&(*dm)->fineMesh);
679:   DMDestroy(&(*dm)->coordinateDM);
680:   VecDestroy(&(*dm)->coordinates);
681:   VecDestroy(&(*dm)->coordinatesLocal);
682:   PetscFree3((*dm)->L,(*dm)->maxCell,(*dm)->bdtype);

684:   PetscDSDestroy(&(*dm)->prob);
685:   DMDestroy(&(*dm)->dmBC);
686:   /* if memory was published with SAWs then destroy it */
687:   PetscObjectSAWsViewOff((PetscObject)*dm);

689:   (*(*dm)->ops->destroy)(*dm);
690:   /* We do not destroy (*dm)->data here so that we can reference count backend objects */
691:   PetscHeaderDestroy(dm);
692:   return(0);
693: }

695: /*@
696:     DMSetUp - sets up the data structures inside a DM object

698:     Collective on DM

700:     Input Parameter:
701: .   dm - the DM object to setup

703:     Level: developer

705: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix()

707: @*/
708: PetscErrorCode  DMSetUp(DM dm)
709: {

714:   if (dm->setupcalled) return(0);
715:   if (dm->ops->setup) {
716:     (*dm->ops->setup)(dm);
717:   }
718:   dm->setupcalled = PETSC_TRUE;
719:   return(0);
720: }

722: /*@
723:     DMSetFromOptions - sets parameters in a DM from the options database

725:     Collective on DM

727:     Input Parameter:
728: .   dm - the DM object to set options for

730:     Options Database:
731: +   -dm_preallocate_only - Only preallocate the matrix for DMCreateMatrix(), but do not fill it with zeros
732: .   -dm_vec_type <type>  - type of vector to create inside DM
733: .   -dm_mat_type <type>  - type of matrix to create inside DM
734: -   -dm_coloring_type    - <global or ghosted>

736:     Level: developer

738: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix()

740: @*/
741: PetscErrorCode  DMSetFromOptions(DM dm)
742: {
743:   char           typeName[256];
744:   PetscBool      flg;

749:   if (dm->prob) {
750:     PetscDSSetFromOptions(dm->prob);
751:   }
752:   if (dm->sf) {
753:     PetscSFSetFromOptions(dm->sf);
754:   }
755:   if (dm->defaultSF) {
756:     PetscSFSetFromOptions(dm->defaultSF);
757:   }
758:   PetscObjectOptionsBegin((PetscObject)dm);
759:   PetscOptionsBool("-dm_preallocate_only","only preallocate matrix, but do not set column indices","DMSetMatrixPreallocateOnly",dm->prealloc_only,&dm->prealloc_only,NULL);
760:   PetscOptionsFList("-dm_vec_type","Vector type used for created vectors","DMSetVecType",VecList,dm->vectype,typeName,256,&flg);
761:   if (flg) {
762:     DMSetVecType(dm,typeName);
763:   }
764:   PetscOptionsFList("-dm_mat_type","Matrix type used for created matrices","DMSetMatType",MatList,dm->mattype ? dm->mattype : typeName,typeName,sizeof(typeName),&flg);
765:   if (flg) {
766:     DMSetMatType(dm,typeName);
767:   }
768:   PetscOptionsEnum("-dm_is_coloring_type","Global or local coloring of Jacobian","ISColoringType",ISColoringTypes,(PetscEnum)dm->coloringtype,(PetscEnum*)&dm->coloringtype,NULL);
769:   if (dm->ops->setfromoptions) {
770:     (*dm->ops->setfromoptions)(PetscOptionsObject,dm);
771:   }
772:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
773:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject) dm);
774:   PetscOptionsEnd();
775:   return(0);
776: }

778: /*@C
779:     DMView - Views a DM

781:     Collective on DM

783:     Input Parameter:
784: +   dm - the DM object to view
785: -   v - the viewer

787:     Level: beginner

789: .seealso DMDestroy(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix()

791: @*/
792: PetscErrorCode  DMView(DM dm,PetscViewer v)
793: {
795:   PetscBool      isbinary;

799:   if (!v) {
800:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)dm),&v);
801:   }
802:   PetscObjectPrintClassNamePrefixType((PetscObject)dm,v);
803:   PetscObjectTypeCompare((PetscObject)v,PETSCVIEWERBINARY,&isbinary);
804:   if (isbinary) {
805:     PetscInt classid = DM_FILE_CLASSID;
806:     char     type[256];

808:     PetscViewerBinaryWrite(v,&classid,1,PETSC_INT,PETSC_FALSE);
809:     PetscStrncpy(type,((PetscObject)dm)->type_name,256);
810:     PetscViewerBinaryWrite(v,type,256,PETSC_CHAR,PETSC_FALSE);
811:   }
812:   if (dm->ops->view) {
813:     (*dm->ops->view)(dm,v);
814:   }
815:   return(0);
816: }

818: /*@
819:     DMCreateGlobalVector - Creates a global vector from a DM object

821:     Collective on DM

823:     Input Parameter:
824: .   dm - the DM object

826:     Output Parameter:
827: .   vec - the global vector

829:     Level: beginner

831: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix()

833: @*/
834: PetscErrorCode  DMCreateGlobalVector(DM dm,Vec *vec)
835: {

840:   (*dm->ops->createglobalvector)(dm,vec);
841:   return(0);
842: }

844: /*@
845:     DMCreateLocalVector - Creates a local vector from a DM object

847:     Not Collective

849:     Input Parameter:
850: .   dm - the DM object

852:     Output Parameter:
853: .   vec - the local vector

855:     Level: beginner

857: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix()

859: @*/
860: PetscErrorCode  DMCreateLocalVector(DM dm,Vec *vec)
861: {

866:   (*dm->ops->createlocalvector)(dm,vec);
867:   return(0);
868: }

870: /*@
871:    DMGetLocalToGlobalMapping - Accesses the local-to-global mapping in a DM.

873:    Collective on DM

875:    Input Parameter:
876: .  dm - the DM that provides the mapping

878:    Output Parameter:
879: .  ltog - the mapping

881:    Level: intermediate

883:    Notes:
884:    This mapping can then be used by VecSetLocalToGlobalMapping() or
885:    MatSetLocalToGlobalMapping().

887: .seealso: DMCreateLocalVector()
888: @*/
889: PetscErrorCode DMGetLocalToGlobalMapping(DM dm,ISLocalToGlobalMapping *ltog)
890: {
891:   PetscInt       bs = -1, bsLocal, bsMin, bsMax;

897:   if (!dm->ltogmap) {
898:     PetscSection section, sectionGlobal;

900:     DMGetDefaultSection(dm, &section);
901:     if (section) {
902:       const PetscInt *cdofs;
903:       PetscInt       *ltog;
904:       PetscInt        pStart, pEnd, size, p, l;

906:       DMGetDefaultGlobalSection(dm, &sectionGlobal);
907:       PetscSectionGetChart(section, &pStart, &pEnd);
908:       PetscSectionGetStorageSize(section, &size);
909:       PetscMalloc1(size, &ltog); /* We want the local+overlap size */
910:       for (p = pStart, l = 0; p < pEnd; ++p) {
911:         PetscInt bdof, cdof, dof, off, c, cind = 0;

913:         /* Should probably use constrained dofs */
914:         PetscSectionGetDof(section, p, &dof);
915:         PetscSectionGetConstraintDof(section, p, &cdof);
916:         PetscSectionGetConstraintIndices(section, p, &cdofs);
917:         PetscSectionGetOffset(sectionGlobal, p, &off);
918:         /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
919:         bdof = cdof && (dof-cdof) ? 1 : dof;
920:         if (dof) {
921:           if (bs < 0)          {bs = bdof;}
922:           else if (bs != bdof) {bs = 1;}
923:         }
924:         for (c = 0; c < dof; ++c, ++l) {
925:           if ((cind < cdof) && (c == cdofs[cind])) ltog[l] = off < 0 ? off-c : off+c;
926:           else                                     ltog[l] = (off < 0 ? -(off+1) : off) + c;
927:         }
928:       }
929:       /* Must have same blocksize on all procs (some might have no points) */
930:       bsLocal = bs;
931:       MPIU_Allreduce(&bsLocal, &bsMax, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm));
932:       bsLocal = bs < 0 ? bsMax : bs;
933:       MPIU_Allreduce(&bsLocal, &bsMin, 1, MPIU_INT, MPI_MIN, PetscObjectComm((PetscObject)dm));
934:       if (bsMin != bsMax) {bs = 1;}
935:       else                {bs = bsMax;}
936:       bs   = bs < 0 ? 1 : bs;
937:       /* Must reduce indices by blocksize */
938:       if (bs > 1) for (l = 0; l < size; ++l) ltog[l] /= bs;
939:       ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs, size, ltog, PETSC_OWN_POINTER, &dm->ltogmap);
940:       PetscLogObjectParent((PetscObject)dm, (PetscObject)dm->ltogmap);
941:     } else {
942:       if (!dm->ops->getlocaltoglobalmapping) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM can not create LocalToGlobalMapping");
943:       (*dm->ops->getlocaltoglobalmapping)(dm);
944:     }
945:   }
946:   *ltog = dm->ltogmap;
947:   return(0);
948: }

950: /*@
951:    DMGetBlockSize - Gets the inherent block size associated with a DM

953:    Not Collective

955:    Input Parameter:
956: .  dm - the DM with block structure

958:    Output Parameter:
959: .  bs - the block size, 1 implies no exploitable block structure

961:    Level: intermediate

963: .seealso: ISCreateBlock(), VecSetBlockSize(), MatSetBlockSize(), DMGetLocalToGlobalMapping()
964: @*/
965: PetscErrorCode  DMGetBlockSize(DM dm,PetscInt *bs)
966: {
970:   if (dm->bs < 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"DM does not have enough information to provide a block size yet");
971:   *bs = dm->bs;
972:   return(0);
973: }

975: /*@
976:     DMCreateInterpolation - Gets interpolation matrix between two DM objects

978:     Collective on DM

980:     Input Parameter:
981: +   dm1 - the DM object
982: -   dm2 - the second, finer DM object

984:     Output Parameter:
985: +  mat - the interpolation
986: -  vec - the scaling (optional)

988:     Level: developer

990:     Notes:  For DMDA objects this only works for "uniform refinement", that is the refined mesh was obtained DMRefine() or the coarse mesh was obtained by
991:         DMCoarsen(). The coordinates set into the DMDA are completely ignored in computing the interpolation.

993:         For DMDA objects you can use this interpolation (more precisely the interpolation from the DMGetCoordinateDM()) to interpolate the mesh coordinate vectors
994:         EXCEPT in the periodic case where it does not make sense since the coordinate vectors are not periodic.


997: .seealso DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateColoring(), DMCreateMatrix(), DMRefine(), DMCoarsen(), DMCreateRestriction()

999: @*/
1000: PetscErrorCode  DMCreateInterpolation(DM dm1,DM dm2,Mat *mat,Vec *vec)
1001: {

1007:   PetscLogEventBegin(DM_CreateInterpolation,dm1,dm2,0,0);
1008:   (*dm1->ops->createinterpolation)(dm1,dm2,mat,vec);
1009:   PetscLogEventEnd(DM_CreateInterpolation,dm1,dm2,0,0);
1010:   return(0);
1011: }

1013: /*@
1014:     DMCreateRestriction - Gets restriction matrix between two DM objects

1016:     Collective on DM

1018:     Input Parameter:
1019: +   dm1 - the DM object
1020: -   dm2 - the second, finer DM object

1022:     Output Parameter:
1023: .  mat - the restriction


1026:     Level: developer

1028:     Notes:  For DMDA objects this only works for "uniform refinement", that is the refined mesh was obtained DMRefine() or the coarse mesh was obtained by
1029:         DMCoarsen(). The coordinates set into the DMDA are completely ignored in computing the interpolation.

1031:  
1032: .seealso DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateColoring(), DMCreateMatrix(), DMRefine(), DMCoarsen(), DMCreateInterpolation()

1034: @*/
1035: PetscErrorCode  DMCreateRestriction(DM dm1,DM dm2,Mat *mat)
1036: {

1042:   PetscLogEventBegin(DM_CreateRestriction,dm1,dm2,0,0);
1043:   if (!dm1->ops->createrestriction) SETERRQ(PetscObjectComm((PetscObject)dm1),PETSC_ERR_SUP,"DMCreateRestriction not implemented for this type");
1044:   (*dm1->ops->createrestriction)(dm1,dm2,mat);
1045:   PetscLogEventEnd(DM_CreateRestriction,dm1,dm2,0,0);
1046:   return(0);
1047: }

1049: /*@
1050:     DMCreateInjection - Gets injection matrix between two DM objects

1052:     Collective on DM

1054:     Input Parameter:
1055: +   dm1 - the DM object
1056: -   dm2 - the second, finer DM object

1058:     Output Parameter:
1059: .   mat - the injection

1061:     Level: developer

1063:    Notes:  For DMDA objects this only works for "uniform refinement", that is the refined mesh was obtained DMRefine() or the coarse mesh was obtained by
1064:         DMCoarsen(). The coordinates set into the DMDA are completely ignored in computing the injection.

1066: .seealso DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateColoring(), DMCreateMatrix(), DMCreateInterpolation()

1068: @*/
1069: PetscErrorCode  DMCreateInjection(DM dm1,DM dm2,Mat *mat)
1070: {

1076:   if (!dm1->ops->getinjection) SETERRQ(PetscObjectComm((PetscObject)dm1),PETSC_ERR_SUP,"DMCreateInjection not implemented for this type");
1077:   (*dm1->ops->getinjection)(dm1,dm2,mat);
1078:   return(0);
1079: }

1081: /*@
1082:     DMCreateColoring - Gets coloring for a DM

1084:     Collective on DM

1086:     Input Parameter:
1087: +   dm - the DM object
1088: -   ctype - IS_COLORING_LOCAL or IS_COLORING_GLOBAL

1090:     Output Parameter:
1091: .   coloring - the coloring

1093:     Level: developer

1095: .seealso DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateMatrix(), DMSetMatType()

1097: @*/
1098: PetscErrorCode  DMCreateColoring(DM dm,ISColoringType ctype,ISColoring *coloring)
1099: {

1104:   if (!dm->ops->getcoloring) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"No coloring for this type of DM yet");
1105:   (*dm->ops->getcoloring)(dm,ctype,coloring);
1106:   return(0);
1107: }

1109: /*@
1110:     DMCreateMatrix - Gets empty Jacobian for a DM

1112:     Collective on DM

1114:     Input Parameter:
1115: .   dm - the DM object

1117:     Output Parameter:
1118: .   mat - the empty Jacobian

1120:     Level: beginner

1122:     Notes: This properly preallocates the number of nonzeros in the sparse matrix so you
1123:        do not need to do it yourself.

1125:        By default it also sets the nonzero structure and puts in the zero entries. To prevent setting
1126:        the nonzero pattern call DMSetMatrixPreallocateOnly()

1128:        For structured grid problems, when you call MatView() on this matrix it is displayed using the global natural ordering, NOT in the ordering used
1129:        internally by PETSc.

1131:        For structured grid problems, in general it is easiest to use MatSetValuesStencil() or MatSetValuesLocal() to put values into the matrix because MatSetValues() requires
1132:        the indices for the global numbering for DMDAs which is complicated.

1134: .seealso DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMSetMatType()

1136: @*/
1137: PetscErrorCode  DMCreateMatrix(DM dm,Mat *mat)
1138: {

1143:   MatInitializePackage();
1146:   (*dm->ops->creatematrix)(dm,mat);
1147:   return(0);
1148: }

1150: /*@
1151:   DMSetMatrixPreallocateOnly - When DMCreateMatrix() is called the matrix will be properly
1152:     preallocated but the nonzero structure and zero values will not be set.

1154:   Logically Collective on DM

1156:   Input Parameter:
1157: + dm - the DM
1158: - only - PETSC_TRUE if only want preallocation

1160:   Level: developer
1161: .seealso DMCreateMatrix()
1162: @*/
1163: PetscErrorCode DMSetMatrixPreallocateOnly(DM dm, PetscBool only)
1164: {
1167:   dm->prealloc_only = only;
1168:   return(0);
1169: }

1171: /*@C
1172:   DMGetWorkArray - Gets a work array guaranteed to be at least the input size, restore with DMRestoreWorkArray()

1174:   Not Collective

1176:   Input Parameters:
1177: + dm - the DM object
1178: . count - The minium size
1179: - dtype - data type (PETSC_REAL, PETSC_SCALAR, PETSC_INT)

1181:   Output Parameter:
1182: . array - the work array

1184:   Level: developer

1186: .seealso DMDestroy(), DMCreate()
1187: @*/
1188: PetscErrorCode DMGetWorkArray(DM dm,PetscInt count,PetscDataType dtype,void *mem)
1189: {
1191:   DMWorkLink     link;
1192:   size_t         dsize;

1197:   if (dm->workin) {
1198:     link       = dm->workin;
1199:     dm->workin = dm->workin->next;
1200:   } else {
1201:     PetscNewLog(dm,&link);
1202:   }
1203:   PetscDataTypeGetSize(dtype,&dsize);
1204:   if (dsize*count > link->bytes) {
1205:     PetscFree(link->mem);
1206:     PetscMalloc(dsize*count,&link->mem);
1207:     link->bytes = dsize*count;
1208:   }
1209:   link->next   = dm->workout;
1210:   dm->workout  = link;
1211:   *(void**)mem = link->mem;
1212:   return(0);
1213: }

1215: /*@C
1216:   DMRestoreWorkArray - Restores a work array guaranteed to be at least the input size, restore with DMRestoreWorkArray()

1218:   Not Collective

1220:   Input Parameters:
1221: + dm - the DM object
1222: . count - The minium size
1223: - dtype - data type (PETSC_REAL, PETSC_SCALAR, PETSC_INT)

1225:   Output Parameter:
1226: . array - the work array

1228:   Level: developer

1230: .seealso DMDestroy(), DMCreate()
1231: @*/
1232: PetscErrorCode DMRestoreWorkArray(DM dm,PetscInt count,PetscDataType dtype,void *mem)
1233: {
1234:   DMWorkLink *p,link;

1239:   for (p=&dm->workout; (link=*p); p=&link->next) {
1240:     if (link->mem == *(void**)mem) {
1241:       *p           = link->next;
1242:       link->next   = dm->workin;
1243:       dm->workin   = link;
1244:       *(void**)mem = NULL;
1245:       return(0);
1246:     }
1247:   }
1248:   SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Array was not checked out");
1249: }

1251: PetscErrorCode DMSetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt field, MatNullSpace *nullSpace))
1252: {
1255:   if (field >= 10) SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %d >= 10 fields", field);
1256:   dm->nullspaceConstructors[field] = nullsp;
1257:   return(0);
1258: }

1260: /*@C
1261:   DMCreateFieldIS - Creates a set of IS objects with the global indices of dofs for each field

1263:   Not collective

1265:   Input Parameter:
1266: . dm - the DM object

1268:   Output Parameters:
1269: + numFields  - The number of fields (or NULL if not requested)
1270: . fieldNames - The name for each field (or NULL if not requested)
1271: - fields     - The global indices for each field (or NULL if not requested)

1273:   Level: intermediate

1275:   Notes:
1276:   The user is responsible for freeing all requested arrays. In particular, every entry of names should be freed with
1277:   PetscFree(), every entry of fields should be destroyed with ISDestroy(), and both arrays should be freed with
1278:   PetscFree().

1280: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix()
1281: @*/
1282: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS **fields)
1283: {
1284:   PetscSection   section, sectionGlobal;

1289:   if (numFields) {
1291:     *numFields = 0;
1292:   }
1293:   if (fieldNames) {
1295:     *fieldNames = NULL;
1296:   }
1297:   if (fields) {
1299:     *fields = NULL;
1300:   }
1301:   DMGetDefaultSection(dm, &section);
1302:   if (section) {
1303:     PetscInt *fieldSizes, **fieldIndices;
1304:     PetscInt nF, f, pStart, pEnd, p;

1306:     DMGetDefaultGlobalSection(dm, &sectionGlobal);
1307:     PetscSectionGetNumFields(section, &nF);
1308:     PetscMalloc2(nF,&fieldSizes,nF,&fieldIndices);
1309:     PetscSectionGetChart(sectionGlobal, &pStart, &pEnd);
1310:     for (f = 0; f < nF; ++f) {
1311:       fieldSizes[f] = 0;
1312:     }
1313:     for (p = pStart; p < pEnd; ++p) {
1314:       PetscInt gdof;

1316:       PetscSectionGetDof(sectionGlobal, p, &gdof);
1317:       if (gdof > 0) {
1318:         for (f = 0; f < nF; ++f) {
1319:           PetscInt fdof, fcdof;

1321:           PetscSectionGetFieldDof(section, p, f, &fdof);
1322:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
1323:           fieldSizes[f] += fdof-fcdof;
1324:         }
1325:       }
1326:     }
1327:     for (f = 0; f < nF; ++f) {
1328:       PetscMalloc1(fieldSizes[f], &fieldIndices[f]);
1329:       fieldSizes[f] = 0;
1330:     }
1331:     for (p = pStart; p < pEnd; ++p) {
1332:       PetscInt gdof, goff;

1334:       PetscSectionGetDof(sectionGlobal, p, &gdof);
1335:       if (gdof > 0) {
1336:         PetscSectionGetOffset(sectionGlobal, p, &goff);
1337:         for (f = 0; f < nF; ++f) {
1338:           PetscInt fdof, fcdof, fc;

1340:           PetscSectionGetFieldDof(section, p, f, &fdof);
1341:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
1342:           for (fc = 0; fc < fdof-fcdof; ++fc, ++fieldSizes[f]) {
1343:             fieldIndices[f][fieldSizes[f]] = goff++;
1344:           }
1345:         }
1346:       }
1347:     }
1348:     if (numFields) *numFields = nF;
1349:     if (fieldNames) {
1350:       PetscMalloc1(nF, fieldNames);
1351:       for (f = 0; f < nF; ++f) {
1352:         const char *fieldName;

1354:         PetscSectionGetFieldName(section, f, &fieldName);
1355:         PetscStrallocpy(fieldName, (char**) &(*fieldNames)[f]);
1356:       }
1357:     }
1358:     if (fields) {
1359:       PetscMalloc1(nF, fields);
1360:       for (f = 0; f < nF; ++f) {
1361:         ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]);
1362:       }
1363:     }
1364:     PetscFree2(fieldSizes,fieldIndices);
1365:   } else if (dm->ops->createfieldis) {
1366:     (*dm->ops->createfieldis)(dm, numFields, fieldNames, fields);
1367:   }
1368:   return(0);
1369: }


1372: /*@C
1373:   DMCreateFieldDecomposition - Returns a list of IS objects defining a decomposition of a problem into subproblems
1374:                           corresponding to different fields: each IS contains the global indices of the dofs of the
1375:                           corresponding field. The optional list of DMs define the DM for each subproblem.
1376:                           Generalizes DMCreateFieldIS().

1378:   Not collective

1380:   Input Parameter:
1381: . dm - the DM object

1383:   Output Parameters:
1384: + len       - The number of subproblems in the field decomposition (or NULL if not requested)
1385: . namelist  - The name for each field (or NULL if not requested)
1386: . islist    - The global indices for each field (or NULL if not requested)
1387: - dmlist    - The DMs for each field subproblem (or NULL, if not requested; if NULL is returned, no DMs are defined)

1389:   Level: intermediate

1391:   Notes:
1392:   The user is responsible for freeing all requested arrays. In particular, every entry of names should be freed with
1393:   PetscFree(), every entry of is should be destroyed with ISDestroy(), every entry of dm should be destroyed with DMDestroy(),
1394:   and all of the arrays should be freed with PetscFree().

1396: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMCreateFieldIS()
1397: @*/
1398: PetscErrorCode DMCreateFieldDecomposition(DM dm, PetscInt *len, char ***namelist, IS **islist, DM **dmlist)
1399: {

1404:   if (len) {
1406:     *len = 0;
1407:   }
1408:   if (namelist) {
1410:     *namelist = 0;
1411:   }
1412:   if (islist) {
1414:     *islist = 0;
1415:   }
1416:   if (dmlist) {
1418:     *dmlist = 0;
1419:   }
1420:   /*
1421:    Is it a good idea to apply the following check across all impls?
1422:    Perhaps some impls can have a well-defined decomposition before DMSetUp?
1423:    This, however, follows the general principle that accessors are not well-behaved until the object is set up.
1424:    */
1425:   if (!dm->setupcalled) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
1426:   if (!dm->ops->createfielddecomposition) {
1427:     PetscSection section;
1428:     PetscInt     numFields, f;

1430:     DMGetDefaultSection(dm, &section);
1431:     if (section) {PetscSectionGetNumFields(section, &numFields);}
1432:     if (section && numFields && dm->ops->createsubdm) {
1433:       if (len) *len = numFields;
1434:       if (namelist) {PetscMalloc1(numFields,namelist);}
1435:       if (islist)   {PetscMalloc1(numFields,islist);}
1436:       if (dmlist)   {PetscMalloc1(numFields,dmlist);}
1437:       for (f = 0; f < numFields; ++f) {
1438:         const char *fieldName;

1440:         DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL);
1441:         if (namelist) {
1442:           PetscSectionGetFieldName(section, f, &fieldName);
1443:           PetscStrallocpy(fieldName, (char**) &(*namelist)[f]);
1444:         }
1445:       }
1446:     } else {
1447:       DMCreateFieldIS(dm, len, namelist, islist);
1448:       /* By default there are no DMs associated with subproblems. */
1449:       if (dmlist) *dmlist = NULL;
1450:     }
1451:   } else {
1452:     (*dm->ops->createfielddecomposition)(dm,len,namelist,islist,dmlist);
1453:   }
1454:   return(0);
1455: }

1457: /*@
1458:   DMCreateSubDM - Returns an IS and DM encapsulating a subproblem defined by the fields passed in.
1459:                   The fields are defined by DMCreateFieldIS().

1461:   Not collective

1463:   Input Parameters:
1464: + dm - the DM object
1465: . numFields - number of fields in this subproblem
1466: - len       - The number of subproblems in the decomposition (or NULL if not requested)

1468:   Output Parameters:
1469: . is - The global indices for the subproblem
1470: - dm - The DM for the subproblem

1472:   Level: intermediate

1474: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMCreateFieldIS()
1475: @*/
1476: PetscErrorCode DMCreateSubDM(DM dm, PetscInt numFields, PetscInt fields[], IS *is, DM *subdm)
1477: {

1485:   if (dm->ops->createsubdm) {
1486:     (*dm->ops->createsubdm)(dm, numFields, fields, is, subdm);
1487:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "This type has no DMCreateSubDM implementation defined");
1488:   return(0);
1489: }


1492: /*@C
1493:   DMCreateDomainDecomposition - Returns lists of IS objects defining a decomposition of a problem into subproblems
1494:                           corresponding to restrictions to pairs nested subdomains: each IS contains the global
1495:                           indices of the dofs of the corresponding subdomains.  The inner subdomains conceptually
1496:                           define a nonoverlapping covering, while outer subdomains can overlap.
1497:                           The optional list of DMs define the DM for each subproblem.

1499:   Not collective

1501:   Input Parameter:
1502: . dm - the DM object

1504:   Output Parameters:
1505: + len         - The number of subproblems in the domain decomposition (or NULL if not requested)
1506: . namelist    - The name for each subdomain (or NULL if not requested)
1507: . innerislist - The global indices for each inner subdomain (or NULL, if not requested)
1508: . outerislist - The global indices for each outer subdomain (or NULL, if not requested)
1509: - dmlist      - The DMs for each subdomain subproblem (or NULL, if not requested; if NULL is returned, no DMs are defined)

1511:   Level: intermediate

1513:   Notes:
1514:   The user is responsible for freeing all requested arrays. In particular, every entry of names should be freed with
1515:   PetscFree(), every entry of is should be destroyed with ISDestroy(), every entry of dm should be destroyed with DMDestroy(),
1516:   and all of the arrays should be freed with PetscFree().

1518: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMCreateDomainDecompositionDM(), DMCreateFieldDecomposition()
1519: @*/
1520: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *len, char ***namelist, IS **innerislist, IS **outerislist, DM **dmlist)
1521: {
1522:   PetscErrorCode      ierr;
1523:   DMSubDomainHookLink link;
1524:   PetscInt            i,l;

1533:   /*
1534:    Is it a good idea to apply the following check across all impls?
1535:    Perhaps some impls can have a well-defined decomposition before DMSetUp?
1536:    This, however, follows the general principle that accessors are not well-behaved until the object is set up.
1537:    */
1538:   if (!dm->setupcalled) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
1539:   if (dm->ops->createdomaindecomposition) {
1540:     (*dm->ops->createdomaindecomposition)(dm,&l,namelist,innerislist,outerislist,dmlist);
1541:     /* copy subdomain hooks and context over to the subdomain DMs */
1542:     if (dmlist && *dmlist) {
1543:       for (i = 0; i < l; i++) {
1544:         for (link=dm->subdomainhook; link; link=link->next) {
1545:           if (link->ddhook) {(*link->ddhook)(dm,(*dmlist)[i],link->ctx);}
1546:         }
1547:         if (dm->ctx) (*dmlist)[i]->ctx = dm->ctx;
1548:       }
1549:     }
1550:     if (len) *len = l;
1551:   }
1552:   return(0);
1553: }


1556: /*@C
1557:   DMCreateDomainDecompositionScatters - Returns scatters to the subdomain vectors from the global vector

1559:   Not collective

1561:   Input Parameters:
1562: + dm - the DM object
1563: . n  - the number of subdomain scatters
1564: - subdms - the local subdomains

1566:   Output Parameters:
1567: + n     - the number of scatters returned
1568: . iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
1569: . oscat - scatter from global vector to overlapping global vector entries on subdomain
1570: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)

1572:   Notes: This is an alternative to the iis and ois arguments in DMCreateDomainDecomposition that allow for the solution
1573:   of general nonlinear problems with overlapping subdomain methods.  While merely having index sets that enable subsets
1574:   of the residual equations to be created is fine for linear problems, nonlinear problems require local assembly of
1575:   solution and residual data.

1577:   Level: developer

1579: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMCreateFieldIS()
1580: @*/
1581: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm,PetscInt n,DM *subdms,VecScatter **iscat,VecScatter **oscat,VecScatter **gscat)
1582: {

1588:   if (dm->ops->createddscatters) {
1589:     (*dm->ops->createddscatters)(dm,n,subdms,iscat,oscat,gscat);
1590:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "This type has no DMCreateDomainDecompositionScatter implementation defined");
1591:   return(0);
1592: }

1594: /*@
1595:   DMRefine - Refines a DM object

1597:   Collective on DM

1599:   Input Parameter:
1600: + dm   - the DM object
1601: - comm - the communicator to contain the new DM object (or MPI_COMM_NULL)

1603:   Output Parameter:
1604: . dmf - the refined DM, or NULL

1606:   Note: If no refinement was done, the return value is NULL

1608:   Level: developer

1610: .seealso DMCoarsen(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation()
1611: @*/
1612: PetscErrorCode  DMRefine(DM dm,MPI_Comm comm,DM *dmf)
1613: {
1614:   PetscErrorCode   ierr;
1615:   DMRefineHookLink link;

1619:   PetscLogEventBegin(DM_Refine,dm,0,0,0);
1620:   if (!dm->ops->refine) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"This DM cannot refine");
1621:   (*dm->ops->refine)(dm,comm,dmf);
1622:   if (*dmf) {
1623:     (*dmf)->ops->creatematrix = dm->ops->creatematrix;

1625:     PetscObjectCopyFortranFunctionPointers((PetscObject)dm,(PetscObject)*dmf);

1627:     (*dmf)->ctx       = dm->ctx;
1628:     (*dmf)->leveldown = dm->leveldown;
1629:     (*dmf)->levelup   = dm->levelup + 1;

1631:     DMSetMatType(*dmf,dm->mattype);
1632:     for (link=dm->refinehook; link; link=link->next) {
1633:       if (link->refinehook) {
1634:         (*link->refinehook)(dm,*dmf,link->ctx);
1635:       }
1636:     }
1637:   }
1638:   PetscLogEventEnd(DM_Refine,dm,0,0,0);
1639:   return(0);
1640: }

1642: /*@C
1643:    DMRefineHookAdd - adds a callback to be run when interpolating a nonlinear problem to a finer grid

1645:    Logically Collective

1647:    Input Arguments:
1648: +  coarse - nonlinear solver context on which to run a hook when restricting to a coarser level
1649: .  refinehook - function to run when setting up a coarser level
1650: .  interphook - function to run to update data on finer levels (once per SNESSolve())
1651: -  ctx - [optional] user-defined context for provide data for the hooks (may be NULL)

1653:    Calling sequence of refinehook:
1654: $    refinehook(DM coarse,DM fine,void *ctx);

1656: +  coarse - coarse level DM
1657: .  fine - fine level DM to interpolate problem to
1658: -  ctx - optional user-defined function context

1660:    Calling sequence for interphook:
1661: $    interphook(DM coarse,Mat interp,DM fine,void *ctx)

1663: +  coarse - coarse level DM
1664: .  interp - matrix interpolating a coarse-level solution to the finer grid
1665: .  fine - fine level DM to update
1666: -  ctx - optional user-defined function context

1668:    Level: advanced

1670:    Notes:
1671:    This function is only needed if auxiliary data needs to be passed to fine grids while grid sequencing

1673:    If this function is called multiple times, the hooks will be run in the order they are added.

1675:    This function is currently not available from Fortran.

1677: .seealso: DMCoarsenHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
1678: @*/
1679: PetscErrorCode DMRefineHookAdd(DM coarse,PetscErrorCode (*refinehook)(DM,DM,void*),PetscErrorCode (*interphook)(DM,Mat,DM,void*),void *ctx)
1680: {
1681:   PetscErrorCode   ierr;
1682:   DMRefineHookLink link,*p;

1686:   for (p=&coarse->refinehook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
1687:   PetscNew(&link);
1688:   link->refinehook = refinehook;
1689:   link->interphook = interphook;
1690:   link->ctx        = ctx;
1691:   link->next       = NULL;
1692:   *p               = link;
1693:   return(0);
1694: }

1696: /*@
1697:    DMInterpolate - interpolates user-defined problem data to a finer DM by running hooks registered by DMRefineHookAdd()

1699:    Collective if any hooks are

1701:    Input Arguments:
1702: +  coarse - coarser DM to use as a base
1703: .  restrct - interpolation matrix, apply using MatInterpolate()
1704: -  fine - finer DM to update

1706:    Level: developer

1708: .seealso: DMRefineHookAdd(), MatInterpolate()
1709: @*/
1710: PetscErrorCode DMInterpolate(DM coarse,Mat interp,DM fine)
1711: {
1712:   PetscErrorCode   ierr;
1713:   DMRefineHookLink link;

1716:   for (link=fine->refinehook; link; link=link->next) {
1717:     if (link->interphook) {
1718:       (*link->interphook)(coarse,interp,fine,link->ctx);
1719:     }
1720:   }
1721:   return(0);
1722: }

1724: /*@
1725:     DMGetRefineLevel - Get's the number of refinements that have generated this DM.

1727:     Not Collective

1729:     Input Parameter:
1730: .   dm - the DM object

1732:     Output Parameter:
1733: .   level - number of refinements

1735:     Level: developer

1737: .seealso DMCoarsen(), DMGetCoarsenLevel(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation()

1739: @*/
1740: PetscErrorCode  DMGetRefineLevel(DM dm,PetscInt *level)
1741: {
1744:   *level = dm->levelup;
1745:   return(0);
1746: }

1748: /*@
1749:     DMSetRefineLevel - Set's the number of refinements that have generated this DM.

1751:     Not Collective

1753:     Input Parameter:
1754: +   dm - the DM object
1755: -   level - number of refinements

1757:     Level: advanced

1759:     Notes: This value is used by PCMG to determine how many multigrid levels to use

1761: .seealso DMCoarsen(), DMGetCoarsenLevel(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation()

1763: @*/
1764: PetscErrorCode  DMSetRefineLevel(DM dm,PetscInt level)
1765: {
1768:   dm->levelup = level;
1769:   return(0);
1770: }

1772: /*@C
1773:    DMGlobalToLocalHookAdd - adds a callback to be run when global to local is called

1775:    Logically Collective

1777:    Input Arguments:
1778: +  dm - the DM
1779: .  beginhook - function to run at the beginning of DMGlobalToLocalBegin()
1780: .  endhook - function to run after DMGlobalToLocalEnd() has completed
1781: -  ctx - [optional] user-defined context for provide data for the hooks (may be NULL)

1783:    Calling sequence for beginhook:
1784: $    beginhook(DM fine,VecScatter out,VecScatter in,DM coarse,void *ctx)

1786: +  dm - global DM
1787: .  g - global vector
1788: .  mode - mode
1789: .  l - local vector
1790: -  ctx - optional user-defined function context


1793:    Calling sequence for endhook:
1794: $    endhook(DM fine,VecScatter out,VecScatter in,DM coarse,void *ctx)

1796: +  global - global DM
1797: -  ctx - optional user-defined function context

1799:    Level: advanced

1801: .seealso: DMRefineHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
1802: @*/
1803: PetscErrorCode DMGlobalToLocalHookAdd(DM dm,PetscErrorCode (*beginhook)(DM,Vec,InsertMode,Vec,void*),PetscErrorCode (*endhook)(DM,Vec,InsertMode,Vec,void*),void *ctx)
1804: {
1805:   PetscErrorCode          ierr;
1806:   DMGlobalToLocalHookLink link,*p;

1810:   for (p=&dm->gtolhook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
1811:   PetscNew(&link);
1812:   link->beginhook = beginhook;
1813:   link->endhook   = endhook;
1814:   link->ctx       = ctx;
1815:   link->next      = NULL;
1816:   *p              = link;
1817:   return(0);
1818: }

1820: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, void *ctx)
1821: {
1822:   Mat cMat;
1823:   Vec cVec;
1824:   PetscSection section, cSec;
1825:   PetscInt pStart, pEnd, p, dof;

1830:   DMGetDefaultConstraints(dm,&cSec,&cMat);
1831:   if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
1832:     PetscInt nRows;

1834:     MatGetSize(cMat,&nRows,NULL);
1835:     if (nRows <= 0) return(0);
1836:     DMGetDefaultSection(dm,&section);
1837:     MatCreateVecs(cMat,NULL,&cVec);
1838:     MatMult(cMat,l,cVec);
1839:     PetscSectionGetChart(cSec,&pStart,&pEnd);
1840:     for (p = pStart; p < pEnd; p++) {
1841:       PetscSectionGetDof(cSec,p,&dof);
1842:       if (dof) {
1843:         PetscScalar *vals;
1844:         VecGetValuesSection(cVec,cSec,p,&vals);
1845:         VecSetValuesSection(l,section,p,vals,INSERT_ALL_VALUES);
1846:       }
1847:     }
1848:     VecDestroy(&cVec);
1849:   }
1850:   return(0);
1851: }

1853: /*@
1854:     DMGlobalToLocalBegin - Begins updating local vectors from global vector

1856:     Neighbor-wise Collective on DM

1858:     Input Parameters:
1859: +   dm - the DM object
1860: .   g - the global vector
1861: .   mode - INSERT_VALUES or ADD_VALUES
1862: -   l - the local vector


1865:     Level: beginner

1867: .seealso DMCoarsen(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMGlobalToLocalEnd(), DMLocalToGlobalBegin()

1869: @*/
1870: PetscErrorCode  DMGlobalToLocalBegin(DM dm,Vec g,InsertMode mode,Vec l)
1871: {
1872:   PetscSF                 sf;
1873:   PetscErrorCode          ierr;
1874:   DMGlobalToLocalHookLink link;

1878:   for (link=dm->gtolhook; link; link=link->next) {
1879:     if (link->beginhook) {
1880:       (*link->beginhook)(dm,g,mode,l,link->ctx);
1881:     }
1882:   }
1883:   DMGetDefaultSF(dm, &sf);
1884:   if (sf) {
1885:     const PetscScalar *gArray;
1886:     PetscScalar       *lArray;

1888:     if (mode == ADD_VALUES) SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %D", mode);
1889:     VecGetArray(l, &lArray);
1890:     VecGetArrayRead(g, &gArray);
1891:     PetscSFBcastBegin(sf, MPIU_SCALAR, gArray, lArray);
1892:     VecRestoreArray(l, &lArray);
1893:     VecRestoreArrayRead(g, &gArray);
1894:   } else {
1895:     (*dm->ops->globaltolocalbegin)(dm,g,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),l);
1896:   }
1897:   return(0);
1898: }

1900: /*@
1901:     DMGlobalToLocalEnd - Ends updating local vectors from global vector

1903:     Neighbor-wise Collective on DM

1905:     Input Parameters:
1906: +   dm - the DM object
1907: .   g - the global vector
1908: .   mode - INSERT_VALUES or ADD_VALUES
1909: -   l - the local vector


1912:     Level: beginner

1914: .seealso DMCoarsen(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMGlobalToLocalEnd(), DMLocalToGlobalBegin()

1916: @*/
1917: PetscErrorCode  DMGlobalToLocalEnd(DM dm,Vec g,InsertMode mode,Vec l)
1918: {
1919:   PetscSF                 sf;
1920:   PetscErrorCode          ierr;
1921:   const PetscScalar      *gArray;
1922:   PetscScalar            *lArray;
1923:   DMGlobalToLocalHookLink link;

1927:   DMGetDefaultSF(dm, &sf);
1928:   if (sf) {
1929:     if (mode == ADD_VALUES) SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %D", mode);

1931:     VecGetArray(l, &lArray);
1932:     VecGetArrayRead(g, &gArray);
1933:     PetscSFBcastEnd(sf, MPIU_SCALAR, gArray, lArray);
1934:     VecRestoreArray(l, &lArray);
1935:     VecRestoreArrayRead(g, &gArray);
1936:   } else {
1937:     (*dm->ops->globaltolocalend)(dm,g,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),l);
1938:   }
1939:   DMGlobalToLocalHook_Constraints(dm,g,mode,l,NULL);
1940:   for (link=dm->gtolhook; link; link=link->next) {
1941:     if (link->endhook) {(*link->endhook)(dm,g,mode,l,link->ctx);}
1942:   }
1943:   return(0);
1944: }

1946: /*@C
1947:    DMLocalToGlobalHookAdd - adds a callback to be run when a local to global is called

1949:    Logically Collective

1951:    Input Arguments:
1952: +  dm - the DM
1953: .  beginhook - function to run at the beginning of DMLocalToGlobalBegin()
1954: .  endhook - function to run after DMLocalToGlobalEnd() has completed
1955: -  ctx - [optional] user-defined context for provide data for the hooks (may be NULL)

1957:    Calling sequence for beginhook:
1958: $    beginhook(DM fine,Vec l,InsertMode mode,Vec g,void *ctx)

1960: +  dm - global DM
1961: .  l - local vector
1962: .  mode - mode
1963: .  g - global vector
1964: -  ctx - optional user-defined function context


1967:    Calling sequence for endhook:
1968: $    endhook(DM fine,Vec l,InsertMode mode,Vec g,void *ctx)

1970: +  global - global DM
1971: .  l - local vector
1972: .  mode - mode
1973: .  g - global vector
1974: -  ctx - optional user-defined function context

1976:    Level: advanced

1978: .seealso: DMRefineHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
1979: @*/
1980: PetscErrorCode DMLocalToGlobalHookAdd(DM dm,PetscErrorCode (*beginhook)(DM,Vec,InsertMode,Vec,void*),PetscErrorCode (*endhook)(DM,Vec,InsertMode,Vec,void*),void *ctx)
1981: {
1982:   PetscErrorCode          ierr;
1983:   DMLocalToGlobalHookLink link,*p;

1987:   for (p=&dm->ltoghook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
1988:   PetscNew(&link);
1989:   link->beginhook = beginhook;
1990:   link->endhook   = endhook;
1991:   link->ctx       = ctx;
1992:   link->next      = NULL;
1993:   *p              = link;
1994:   return(0);
1995: }

1997: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, void *ctx)
1998: {
1999:   Mat cMat;
2000:   Vec cVec;
2001:   PetscSection section, cSec;
2002:   PetscInt pStart, pEnd, p, dof;

2007:   DMGetDefaultConstraints(dm,&cSec,&cMat);
2008:   if (cMat && (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES)) {
2009:     PetscInt nRows;

2011:     MatGetSize(cMat,&nRows,NULL);
2012:     if (nRows <= 0) return(0);
2013:     DMGetDefaultSection(dm,&section);
2014:     MatCreateVecs(cMat,NULL,&cVec);
2015:     PetscSectionGetChart(cSec,&pStart,&pEnd);
2016:     for (p = pStart; p < pEnd; p++) {
2017:       PetscSectionGetDof(cSec,p,&dof);
2018:       if (dof) {
2019:         PetscInt d;
2020:         PetscScalar *vals;
2021:         VecGetValuesSection(l,section,p,&vals);
2022:         VecSetValuesSection(cVec,cSec,p,vals,mode);
2023:         /* for this to be the true transpose, we have to zero the values that
2024:          * we just extracted */
2025:         for (d = 0; d < dof; d++) {
2026:           vals[d] = 0.;
2027:         }
2028:       }
2029:     }
2030:     MatMultTransposeAdd(cMat,cVec,l,l);
2031:     VecDestroy(&cVec);
2032:   }
2033:   return(0);
2034: }

2036: /*@
2037:     DMLocalToGlobalBegin - updates global vectors from local vectors

2039:     Neighbor-wise Collective on DM

2041:     Input Parameters:
2042: +   dm - the DM object
2043: .   l - the local vector
2044: .   mode - if INSERT_VALUES then no parallel communication is used, if ADD_VALUES then all ghost points from the same base point accumulate into that base point.
2045: -   g - the global vector

2047:     Notes: In the ADD_VALUES case you normally would zero the receiving vector before beginning this operation.
2048:            INSERT_VALUES is not supported for DMDA, in that case simply compute the values directly into a global vector instead of a local one.

2050:     Level: beginner

2052: .seealso DMCoarsen(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMGlobalToLocalEnd(), DMGlobalToLocalBegin()

2054: @*/
2055: PetscErrorCode  DMLocalToGlobalBegin(DM dm,Vec l,InsertMode mode,Vec g)
2056: {
2057:   PetscSF                 sf;
2058:   PetscSection            s, gs;
2059:   DMLocalToGlobalHookLink link;
2060:   const PetscScalar      *lArray;
2061:   PetscScalar            *gArray;
2062:   PetscBool               isInsert;
2063:   PetscErrorCode          ierr;

2067:   for (link=dm->ltoghook; link; link=link->next) {
2068:     if (link->beginhook) {
2069:       (*link->beginhook)(dm,l,mode,g,link->ctx);
2070:     }
2071:   }
2072:   DMLocalToGlobalHook_Constraints(dm,l,mode,g,NULL);
2073:   DMGetDefaultSF(dm, &sf);
2074:   DMGetDefaultSection(dm, &s);
2075:   switch (mode) {
2076:   case INSERT_VALUES:
2077:   case INSERT_ALL_VALUES:
2078:   case INSERT_BC_VALUES:
2079:     isInsert = PETSC_TRUE; break;
2080:   case ADD_VALUES:
2081:   case ADD_ALL_VALUES:
2082:   case ADD_BC_VALUES:
2083:     isInsert = PETSC_FALSE; break;
2084:   default:
2085:     SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %D", mode);
2086:   }
2087:   if (sf && !isInsert) {
2088:     VecGetArrayRead(l, &lArray);
2089:     VecGetArray(g, &gArray);
2090:     PetscSFReduceBegin(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM);
2091:     VecRestoreArrayRead(l, &lArray);
2092:     VecRestoreArray(g, &gArray);
2093:   } else if (s && isInsert) {
2094:     PetscInt gStart, pStart, pEnd, p;

2096:     DMGetDefaultGlobalSection(dm, &gs);
2097:     PetscSectionGetChart(s, &pStart, &pEnd);
2098:     VecGetOwnershipRange(g, &gStart, NULL);
2099:     VecGetArrayRead(l, &lArray);
2100:     VecGetArray(g, &gArray);
2101:     for (p = pStart; p < pEnd; ++p) {
2102:       PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;

2104:       PetscSectionGetDof(s, p, &dof);
2105:       PetscSectionGetDof(gs, p, &gdof);
2106:       PetscSectionGetConstraintDof(s, p, &cdof);
2107:       PetscSectionGetConstraintDof(gs, p, &gcdof);
2108:       PetscSectionGetOffset(s, p, &off);
2109:       PetscSectionGetOffset(gs, p, &goff);
2110:       /* Ignore off-process data and points with no global data */
2111:       if (!gdof || goff < 0) continue;
2112:       if (dof != gdof) SETERRQ5(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Inconsistent sizes, p: %d dof: %d gdof: %d cdof: %d gcdof: %d", p, dof, gdof, cdof, gcdof);
2113:       /* If no constraints are enforced in the global vector */
2114:       if (!gcdof) {
2115:         for (d = 0; d < dof; ++d) gArray[goff-gStart+d] = lArray[off+d];
2116:       /* If constraints are enforced in the global vector */
2117:       } else if (cdof == gcdof) {
2118:         const PetscInt *cdofs;
2119:         PetscInt        cind = 0;

2121:         PetscSectionGetConstraintIndices(s, p, &cdofs);
2122:         for (d = 0, e = 0; d < dof; ++d) {
2123:           if ((cind < cdof) && (d == cdofs[cind])) {++cind; continue;}
2124:           gArray[goff-gStart+e++] = lArray[off+d];
2125:         }
2126:       } else SETERRQ5(PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Inconsistent sizes, p: %d dof: %d gdof: %d cdof: %d gcdof: %d", p, dof, gdof, cdof, gcdof);
2127:     }
2128:     VecRestoreArrayRead(l, &lArray);
2129:     VecRestoreArray(g, &gArray);
2130:   } else {
2131:     (*dm->ops->localtoglobalbegin)(dm,l,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),g);
2132:   }
2133:   return(0);
2134: }

2136: /*@
2137:     DMLocalToGlobalEnd - updates global vectors from local vectors

2139:     Neighbor-wise Collective on DM

2141:     Input Parameters:
2142: +   dm - the DM object
2143: .   l - the local vector
2144: .   mode - INSERT_VALUES or ADD_VALUES
2145: -   g - the global vector


2148:     Level: beginner

2150: .seealso DMCoarsen(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMGlobalToLocalEnd(), DMGlobalToLocalEnd()

2152: @*/
2153: PetscErrorCode  DMLocalToGlobalEnd(DM dm,Vec l,InsertMode mode,Vec g)
2154: {
2155:   PetscSF                 sf;
2156:   PetscSection            s;
2157:   DMLocalToGlobalHookLink link;
2158:   PetscBool               isInsert;
2159:   PetscErrorCode          ierr;

2163:   DMGetDefaultSF(dm, &sf);
2164:   DMGetDefaultSection(dm, &s);
2165:   switch (mode) {
2166:   case INSERT_VALUES:
2167:   case INSERT_ALL_VALUES:
2168:     isInsert = PETSC_TRUE; break;
2169:   case ADD_VALUES:
2170:   case ADD_ALL_VALUES:
2171:     isInsert = PETSC_FALSE; break;
2172:   default:
2173:     SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %D", mode);
2174:   }
2175:   if (sf && !isInsert) {
2176:     const PetscScalar *lArray;
2177:     PetscScalar       *gArray;

2179:     VecGetArrayRead(l, &lArray);
2180:     VecGetArray(g, &gArray);
2181:     PetscSFReduceEnd(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM);
2182:     VecRestoreArrayRead(l, &lArray);
2183:     VecRestoreArray(g, &gArray);
2184:   } else if (s && isInsert) {
2185:   } else {
2186:     (*dm->ops->localtoglobalend)(dm,l,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),g);
2187:   }
2188:   for (link=dm->ltoghook; link; link=link->next) {
2189:     if (link->endhook) {(*link->endhook)(dm,g,mode,l,link->ctx);}
2190:   }
2191:   return(0);
2192: }

2194: /*@
2195:    DMLocalToLocalBegin - Maps from a local vector (including ghost points
2196:    that contain irrelevant values) to another local vector where the ghost
2197:    points in the second are set correctly. Must be followed by DMLocalToLocalEnd().

2199:    Neighbor-wise Collective on DM and Vec

2201:    Input Parameters:
2202: +  dm - the DM object
2203: .  g - the original local vector
2204: -  mode - one of INSERT_VALUES or ADD_VALUES

2206:    Output Parameter:
2207: .  l  - the local vector with correct ghost values

2209:    Level: intermediate

2211:    Notes:
2212:    The local vectors used here need not be the same as those
2213:    obtained from DMCreateLocalVector(), BUT they
2214:    must have the same parallel data layout; they could, for example, be
2215:    obtained with VecDuplicate() from the DM originating vectors.

2217: .keywords: DM, local-to-local, begin
2218: .seealso DMCoarsen(), DMDestroy(), DMView(), DMCreateLocalVector(), DMCreateGlobalVector(), DMCreateInterpolation(), DMLocalToLocalEnd(), DMGlobalToLocalEnd(), DMLocalToGlobalBegin()

2220: @*/
2221: PetscErrorCode  DMLocalToLocalBegin(DM dm,Vec g,InsertMode mode,Vec l)
2222: {
2223:   PetscErrorCode          ierr;

2227:   (*dm->ops->localtolocalbegin)(dm,g,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),l);
2228:   return(0);
2229: }

2231: /*@
2232:    DMLocalToLocalEnd - Maps from a local vector (including ghost points
2233:    that contain irrelevant values) to another local vector where the ghost
2234:    points in the second are set correctly. Must be preceded by DMLocalToLocalBegin().

2236:    Neighbor-wise Collective on DM and Vec

2238:    Input Parameters:
2239: +  da - the DM object
2240: .  g - the original local vector
2241: -  mode - one of INSERT_VALUES or ADD_VALUES

2243:    Output Parameter:
2244: .  l  - the local vector with correct ghost values

2246:    Level: intermediate

2248:    Notes:
2249:    The local vectors used here need not be the same as those
2250:    obtained from DMCreateLocalVector(), BUT they
2251:    must have the same parallel data layout; they could, for example, be
2252:    obtained with VecDuplicate() from the DM originating vectors.

2254: .keywords: DM, local-to-local, end
2255: .seealso DMCoarsen(), DMDestroy(), DMView(), DMCreateLocalVector(), DMCreateGlobalVector(), DMCreateInterpolation(), DMLocalToLocalBegin(), DMGlobalToLocalEnd(), DMLocalToGlobalBegin()

2257: @*/
2258: PetscErrorCode  DMLocalToLocalEnd(DM dm,Vec g,InsertMode mode,Vec l)
2259: {
2260:   PetscErrorCode          ierr;

2264:   (*dm->ops->localtolocalend)(dm,g,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),l);
2265:   return(0);
2266: }


2269: /*@
2270:     DMCoarsen - Coarsens a DM object

2272:     Collective on DM

2274:     Input Parameter:
2275: +   dm - the DM object
2276: -   comm - the communicator to contain the new DM object (or MPI_COMM_NULL)

2278:     Output Parameter:
2279: .   dmc - the coarsened DM

2281:     Level: developer

2283: .seealso DMRefine(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation()

2285: @*/
2286: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
2287: {
2288:   PetscErrorCode    ierr;
2289:   DMCoarsenHookLink link;

2293:   if (!dm->ops->coarsen) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"This DM cannot coarsen");
2294:   PetscLogEventBegin(DM_Coarsen,dm,0,0,0);
2295:   (*dm->ops->coarsen)(dm, comm, dmc);
2296:   if (!(*dmc)) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "NULL coarse mesh produced");
2297:   DMSetCoarseDM(dm,*dmc);
2298:   (*dmc)->ops->creatematrix = dm->ops->creatematrix;
2299:   PetscObjectCopyFortranFunctionPointers((PetscObject)dm,(PetscObject)*dmc);
2300:   (*dmc)->ctx               = dm->ctx;
2301:   (*dmc)->levelup           = dm->levelup;
2302:   (*dmc)->leveldown         = dm->leveldown + 1;
2303:   DMSetMatType(*dmc,dm->mattype);
2304:   for (link=dm->coarsenhook; link; link=link->next) {
2305:     if (link->coarsenhook) {(*link->coarsenhook)(dm,*dmc,link->ctx);}
2306:   }
2307:   PetscLogEventEnd(DM_Coarsen,dm,0,0,0);
2308:   return(0);
2309: }

2311: /*@C
2312:    DMCoarsenHookAdd - adds a callback to be run when restricting a nonlinear problem to the coarse grid

2314:    Logically Collective

2316:    Input Arguments:
2317: +  fine - nonlinear solver context on which to run a hook when restricting to a coarser level
2318: .  coarsenhook - function to run when setting up a coarser level
2319: .  restricthook - function to run to update data on coarser levels (once per SNESSolve())
2320: -  ctx - [optional] user-defined context for provide data for the hooks (may be NULL)

2322:    Calling sequence of coarsenhook:
2323: $    coarsenhook(DM fine,DM coarse,void *ctx);

2325: +  fine - fine level DM
2326: .  coarse - coarse level DM to restrict problem to
2327: -  ctx - optional user-defined function context

2329:    Calling sequence for restricthook:
2330: $    restricthook(DM fine,Mat mrestrict,Vec rscale,Mat inject,DM coarse,void *ctx)

2332: +  fine - fine level DM
2333: .  mrestrict - matrix restricting a fine-level solution to the coarse grid
2334: .  rscale - scaling vector for restriction
2335: .  inject - matrix restricting by injection
2336: .  coarse - coarse level DM to update
2337: -  ctx - optional user-defined function context

2339:    Level: advanced

2341:    Notes:
2342:    This function is only needed if auxiliary data needs to be set up on coarse grids.

2344:    If this function is called multiple times, the hooks will be run in the order they are added.

2346:    In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
2347:    extract the finest level information from its context (instead of from the SNES).

2349:    This function is currently not available from Fortran.

2351: .seealso: DMRefineHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
2352: @*/
2353: PetscErrorCode DMCoarsenHookAdd(DM fine,PetscErrorCode (*coarsenhook)(DM,DM,void*),PetscErrorCode (*restricthook)(DM,Mat,Vec,Mat,DM,void*),void *ctx)
2354: {
2355:   PetscErrorCode    ierr;
2356:   DMCoarsenHookLink link,*p;

2360:   for (p=&fine->coarsenhook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
2361:   PetscNew(&link);
2362:   link->coarsenhook  = coarsenhook;
2363:   link->restricthook = restricthook;
2364:   link->ctx          = ctx;
2365:   link->next         = NULL;
2366:   *p                 = link;
2367:   return(0);
2368: }

2370: /*@
2371:    DMRestrict - restricts user-defined problem data to a coarser DM by running hooks registered by DMCoarsenHookAdd()

2373:    Collective if any hooks are

2375:    Input Arguments:
2376: +  fine - finer DM to use as a base
2377: .  restrct - restriction matrix, apply using MatRestrict()
2378: .  inject - injection matrix, also use MatRestrict()
2379: -  coarse - coarer DM to update

2381:    Level: developer

2383: .seealso: DMCoarsenHookAdd(), MatRestrict()
2384: @*/
2385: PetscErrorCode DMRestrict(DM fine,Mat restrct,Vec rscale,Mat inject,DM coarse)
2386: {
2387:   PetscErrorCode    ierr;
2388:   DMCoarsenHookLink link;

2391:   for (link=fine->coarsenhook; link; link=link->next) {
2392:     if (link->restricthook) {
2393:       (*link->restricthook)(fine,restrct,rscale,inject,coarse,link->ctx);
2394:     }
2395:   }
2396:   return(0);
2397: }

2399: /*@C
2400:    DMSubDomainHookAdd - adds a callback to be run when restricting a problem to the coarse grid

2402:    Logically Collective

2404:    Input Arguments:
2405: +  global - global DM
2406: .  ddhook - function to run to pass data to the decomposition DM upon its creation
2407: .  restricthook - function to run to update data on block solve (at the beginning of the block solve)
2408: -  ctx - [optional] user-defined context for provide data for the hooks (may be NULL)


2411:    Calling sequence for ddhook:
2412: $    ddhook(DM global,DM block,void *ctx)

2414: +  global - global DM
2415: .  block  - block DM
2416: -  ctx - optional user-defined function context

2418:    Calling sequence for restricthook:
2419: $    restricthook(DM global,VecScatter out,VecScatter in,DM block,void *ctx)

2421: +  global - global DM
2422: .  out    - scatter to the outer (with ghost and overlap points) block vector
2423: .  in     - scatter to block vector values only owned locally
2424: .  block  - block DM
2425: -  ctx - optional user-defined function context

2427:    Level: advanced

2429:    Notes:
2430:    This function is only needed if auxiliary data needs to be set up on subdomain DMs.

2432:    If this function is called multiple times, the hooks will be run in the order they are added.

2434:    In order to compose with nonlinear preconditioning without duplicating storage, the hook should be implemented to
2435:    extract the global information from its context (instead of from the SNES).

2437:    This function is currently not available from Fortran.

2439: .seealso: DMRefineHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
2440: @*/
2441: PetscErrorCode DMSubDomainHookAdd(DM global,PetscErrorCode (*ddhook)(DM,DM,void*),PetscErrorCode (*restricthook)(DM,VecScatter,VecScatter,DM,void*),void *ctx)
2442: {
2443:   PetscErrorCode      ierr;
2444:   DMSubDomainHookLink link,*p;

2448:   for (p=&global->subdomainhook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
2449:   PetscNew(&link);
2450:   link->restricthook = restricthook;
2451:   link->ddhook       = ddhook;
2452:   link->ctx          = ctx;
2453:   link->next         = NULL;
2454:   *p                 = link;
2455:   return(0);
2456: }

2458: /*@
2459:    DMSubDomainRestrict - restricts user-defined problem data to a block DM by running hooks registered by DMSubDomainHookAdd()

2461:    Collective if any hooks are

2463:    Input Arguments:
2464: +  fine - finer DM to use as a base
2465: .  oscatter - scatter from domain global vector filling subdomain global vector with overlap
2466: .  gscatter - scatter from domain global vector filling subdomain local vector with ghosts
2467: -  coarse - coarer DM to update

2469:    Level: developer

2471: .seealso: DMCoarsenHookAdd(), MatRestrict()
2472: @*/
2473: PetscErrorCode DMSubDomainRestrict(DM global,VecScatter oscatter,VecScatter gscatter,DM subdm)
2474: {
2475:   PetscErrorCode      ierr;
2476:   DMSubDomainHookLink link;

2479:   for (link=global->subdomainhook; link; link=link->next) {
2480:     if (link->restricthook) {
2481:       (*link->restricthook)(global,oscatter,gscatter,subdm,link->ctx);
2482:     }
2483:   }
2484:   return(0);
2485: }

2487: /*@
2488:     DMGetCoarsenLevel - Get's the number of coarsenings that have generated this DM.

2490:     Not Collective

2492:     Input Parameter:
2493: .   dm - the DM object

2495:     Output Parameter:
2496: .   level - number of coarsenings

2498:     Level: developer

2500: .seealso DMCoarsen(), DMGetRefineLevel(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation()

2502: @*/
2503: PetscErrorCode  DMGetCoarsenLevel(DM dm,PetscInt *level)
2504: {
2507:   *level = dm->leveldown;
2508:   return(0);
2509: }



2513: /*@C
2514:     DMRefineHierarchy - Refines a DM object, all levels at once

2516:     Collective on DM

2518:     Input Parameter:
2519: +   dm - the DM object
2520: -   nlevels - the number of levels of refinement

2522:     Output Parameter:
2523: .   dmf - the refined DM hierarchy

2525:     Level: developer

2527: .seealso DMCoarsenHierarchy(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation()

2529: @*/
2530: PetscErrorCode  DMRefineHierarchy(DM dm,PetscInt nlevels,DM dmf[])
2531: {

2536:   if (nlevels < 0) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_OUTOFRANGE,"nlevels cannot be negative");
2537:   if (nlevels == 0) return(0);
2538:   if (dm->ops->refinehierarchy) {
2539:     (*dm->ops->refinehierarchy)(dm,nlevels,dmf);
2540:   } else if (dm->ops->refine) {
2541:     PetscInt i;

2543:     DMRefine(dm,PetscObjectComm((PetscObject)dm),&dmf[0]);
2544:     for (i=1; i<nlevels; i++) {
2545:       DMRefine(dmf[i-1],PetscObjectComm((PetscObject)dm),&dmf[i]);
2546:     }
2547:   } else SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"No RefineHierarchy for this DM yet");
2548:   return(0);
2549: }

2551: /*@C
2552:     DMCoarsenHierarchy - Coarsens a DM object, all levels at once

2554:     Collective on DM

2556:     Input Parameter:
2557: +   dm - the DM object
2558: -   nlevels - the number of levels of coarsening

2560:     Output Parameter:
2561: .   dmc - the coarsened DM hierarchy

2563:     Level: developer

2565: .seealso DMRefineHierarchy(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation()

2567: @*/
2568: PetscErrorCode  DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
2569: {

2574:   if (nlevels < 0) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_OUTOFRANGE,"nlevels cannot be negative");
2575:   if (nlevels == 0) return(0);
2577:   if (dm->ops->coarsenhierarchy) {
2578:     (*dm->ops->coarsenhierarchy)(dm, nlevels, dmc);
2579:   } else if (dm->ops->coarsen) {
2580:     PetscInt i;

2582:     DMCoarsen(dm,PetscObjectComm((PetscObject)dm),&dmc[0]);
2583:     for (i=1; i<nlevels; i++) {
2584:       DMCoarsen(dmc[i-1],PetscObjectComm((PetscObject)dm),&dmc[i]);
2585:     }
2586:   } else SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"No CoarsenHierarchy for this DM yet");
2587:   return(0);
2588: }

2590: /*@
2591:    DMCreateAggregates - Gets the aggregates that map between
2592:    grids associated with two DMs.

2594:    Collective on DM

2596:    Input Parameters:
2597: +  dmc - the coarse grid DM
2598: -  dmf - the fine grid DM

2600:    Output Parameters:
2601: .  rest - the restriction matrix (transpose of the projection matrix)

2603:    Level: intermediate

2605: .keywords: interpolation, restriction, multigrid

2607: .seealso: DMRefine(), DMCreateInjection(), DMCreateInterpolation()
2608: @*/
2609: PetscErrorCode  DMCreateAggregates(DM dmc, DM dmf, Mat *rest)
2610: {

2616:   (*dmc->ops->getaggregates)(dmc, dmf, rest);
2617:   return(0);
2618: }

2620: /*@C
2621:     DMSetApplicationContextDestroy - Sets a user function that will be called to destroy the application context when the DM is destroyed

2623:     Not Collective

2625:     Input Parameters:
2626: +   dm - the DM object
2627: -   destroy - the destroy function

2629:     Level: intermediate

2631: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMGetApplicationContext()

2633: @*/
2634: PetscErrorCode  DMSetApplicationContextDestroy(DM dm,PetscErrorCode (*destroy)(void**))
2635: {
2638:   dm->ctxdestroy = destroy;
2639:   return(0);
2640: }

2642: /*@
2643:     DMSetApplicationContext - Set a user context into a DM object

2645:     Not Collective

2647:     Input Parameters:
2648: +   dm - the DM object
2649: -   ctx - the user context

2651:     Level: intermediate

2653: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMGetApplicationContext()

2655: @*/
2656: PetscErrorCode  DMSetApplicationContext(DM dm,void *ctx)
2657: {
2660:   dm->ctx = ctx;
2661:   return(0);
2662: }

2664: /*@
2665:     DMGetApplicationContext - Gets a user context from a DM object

2667:     Not Collective

2669:     Input Parameter:
2670: .   dm - the DM object

2672:     Output Parameter:
2673: .   ctx - the user context

2675:     Level: intermediate

2677: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMGetApplicationContext()

2679: @*/
2680: PetscErrorCode  DMGetApplicationContext(DM dm,void *ctx)
2681: {
2684:   *(void**)ctx = dm->ctx;
2685:   return(0);
2686: }

2688: /*@C
2689:     DMSetVariableBounds - sets a function to compute the lower and upper bound vectors for SNESVI.

2691:     Logically Collective on DM

2693:     Input Parameter:
2694: +   dm - the DM object
2695: -   f - the function that computes variable bounds used by SNESVI (use NULL to cancel a previous function that was set)

2697:     Level: intermediate

2699: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMGetApplicationContext(),
2700:          DMSetJacobian()

2702: @*/
2703: PetscErrorCode  DMSetVariableBounds(DM dm,PetscErrorCode (*f)(DM,Vec,Vec))
2704: {
2706:   dm->ops->computevariablebounds = f;
2707:   return(0);
2708: }

2710: /*@
2711:     DMHasVariableBounds - does the DM object have a variable bounds function?

2713:     Not Collective

2715:     Input Parameter:
2716: .   dm - the DM object to destroy

2718:     Output Parameter:
2719: .   flg - PETSC_TRUE if the variable bounds function exists

2721:     Level: developer

2723: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMGetApplicationContext()

2725: @*/
2726: PetscErrorCode  DMHasVariableBounds(DM dm,PetscBool  *flg)
2727: {
2729:   *flg =  (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
2730:   return(0);
2731: }

2733: /*@C
2734:     DMComputeVariableBounds - compute variable bounds used by SNESVI.

2736:     Logically Collective on DM

2738:     Input Parameters:
2739: .   dm - the DM object

2741:     Output parameters:
2742: +   xl - lower bound
2743: -   xu - upper bound

2745:     Level: advanced

2747:     Notes: This is generally not called by users. It calls the function provided by the user with DMSetVariableBounds()

2749: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMGetApplicationContext()

2751: @*/
2752: PetscErrorCode  DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
2753: {

2759:   if (dm->ops->computevariablebounds) {
2760:     (*dm->ops->computevariablebounds)(dm, xl,xu);
2761:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "This DM is incapable of computing variable bounds.");
2762:   return(0);
2763: }

2765: /*@
2766:     DMHasColoring - does the DM object have a method of providing a coloring?

2768:     Not Collective

2770:     Input Parameter:
2771: .   dm - the DM object

2773:     Output Parameter:
2774: .   flg - PETSC_TRUE if the DM has facilities for DMCreateColoring().

2776:     Level: developer

2778: .seealso DMHasFunction(), DMCreateColoring()

2780: @*/
2781: PetscErrorCode  DMHasColoring(DM dm,PetscBool  *flg)
2782: {
2784:   *flg =  (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
2785:   return(0);
2786: }

2788: /*@
2789:     DMHasCreateRestriction - does the DM object have a method of providing a restriction?

2791:     Not Collective

2793:     Input Parameter:
2794: .   dm - the DM object

2796:     Output Parameter:
2797: .   flg - PETSC_TRUE if the DM has facilities for DMCreateRestriction().

2799:     Level: developer

2801: .seealso DMHasFunction(), DMCreateRestriction()

2803: @*/
2804: PetscErrorCode  DMHasCreateRestriction(DM dm,PetscBool  *flg)
2805: {
2807:   *flg =  (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
2808:   return(0);
2809: }

2811: /*@C
2812:     DMSetVec - set the vector at which to compute residual, Jacobian and VI bounds, if the problem is nonlinear.

2814:     Collective on DM

2816:     Input Parameter:
2817: +   dm - the DM object
2818: -   x - location to compute residual and Jacobian, if NULL is passed to those routines; will be NULL for linear problems.

2820:     Level: developer

2822: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMGetApplicationContext()

2824: @*/
2825: PetscErrorCode  DMSetVec(DM dm,Vec x)
2826: {

2830:   if (x) {
2831:     if (!dm->x) {
2832:       DMCreateGlobalVector(dm,&dm->x);
2833:     }
2834:     VecCopy(x,dm->x);
2835:   } else if (dm->x) {
2836:     VecDestroy(&dm->x);
2837:   }
2838:   return(0);
2839: }

2841: PetscFunctionList DMList              = NULL;
2842: PetscBool         DMRegisterAllCalled = PETSC_FALSE;

2844: /*@C
2845:   DMSetType - Builds a DM, for a particular DM implementation.

2847:   Collective on DM

2849:   Input Parameters:
2850: + dm     - The DM object
2851: - method - The name of the DM type

2853:   Options Database Key:
2854: . -dm_type <type> - Sets the DM type; use -help for a list of available types

2856:   Notes:
2857:   See "petsc/include/petscdm.h" for available DM types (for instance, DM1D, DM2D, or DM3D).

2859:   Level: intermediate

2861: .keywords: DM, set, type
2862: .seealso: DMGetType(), DMCreate()
2863: @*/
2864: PetscErrorCode  DMSetType(DM dm, DMType method)
2865: {
2866:   PetscErrorCode (*r)(DM);
2867:   PetscBool      match;

2872:   PetscObjectTypeCompare((PetscObject) dm, method, &match);
2873:   if (match) return(0);

2875:   DMRegisterAll();
2876:   PetscFunctionListFind(DMList,method,&r);
2877:   if (!r) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_UNKNOWN_TYPE, "Unknown DM type: %s", method);

2879:   if (dm->ops->destroy) {
2880:     (*dm->ops->destroy)(dm);
2881:     dm->ops->destroy = NULL;
2882:   }
2883:   (*r)(dm);
2884:   PetscObjectChangeTypeName((PetscObject)dm,method);
2885:   return(0);
2886: }

2888: /*@C
2889:   DMGetType - Gets the DM type name (as a string) from the DM.

2891:   Not Collective

2893:   Input Parameter:
2894: . dm  - The DM

2896:   Output Parameter:
2897: . type - The DM type name

2899:   Level: intermediate

2901: .keywords: DM, get, type, name
2902: .seealso: DMSetType(), DMCreate()
2903: @*/
2904: PetscErrorCode  DMGetType(DM dm, DMType *type)
2905: {

2911:   DMRegisterAll();
2912:   *type = ((PetscObject)dm)->type_name;
2913:   return(0);
2914: }

2916: /*@C
2917:   DMConvert - Converts a DM to another DM, either of the same or different type.

2919:   Collective on DM

2921:   Input Parameters:
2922: + dm - the DM
2923: - newtype - new DM type (use "same" for the same type)

2925:   Output Parameter:
2926: . M - pointer to new DM

2928:   Notes:
2929:   Cannot be used to convert a sequential DM to parallel or parallel to sequential,
2930:   the MPI communicator of the generated DM is always the same as the communicator
2931:   of the input DM.

2933:   Level: intermediate

2935: .seealso: DMCreate()
2936: @*/
2937: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
2938: {
2939:   DM             B;
2940:   char           convname[256];
2941:   PetscBool      sametype/*, issame */;

2948:   PetscObjectTypeCompare((PetscObject) dm, newtype, &sametype);
2949:   /* PetscStrcmp(newtype, "same", &issame); */
2950:   if (sametype) {
2951:     *M   = dm;
2952:     PetscObjectReference((PetscObject) dm);
2953:     return(0);
2954:   } else {
2955:     PetscErrorCode (*conv)(DM, DMType, DM*) = NULL;

2957:     /*
2958:        Order of precedence:
2959:        1) See if a specialized converter is known to the current DM.
2960:        2) See if a specialized converter is known to the desired DM class.
2961:        3) See if a good general converter is registered for the desired class
2962:        4) See if a good general converter is known for the current matrix.
2963:        5) Use a really basic converter.
2964:     */

2966:     /* 1) See if a specialized converter is known to the current DM and the desired class */
2967:     PetscStrcpy(convname,"DMConvert_");
2968:     PetscStrcat(convname,((PetscObject) dm)->type_name);
2969:     PetscStrcat(convname,"_");
2970:     PetscStrcat(convname,newtype);
2971:     PetscStrcat(convname,"_C");
2972:     PetscObjectQueryFunction((PetscObject)dm,convname,&conv);
2973:     if (conv) goto foundconv;

2975:     /* 2)  See if a specialized converter is known to the desired DM class. */
2976:     DMCreate(PetscObjectComm((PetscObject)dm), &B);
2977:     DMSetType(B, newtype);
2978:     PetscStrcpy(convname,"DMConvert_");
2979:     PetscStrcat(convname,((PetscObject) dm)->type_name);
2980:     PetscStrcat(convname,"_");
2981:     PetscStrcat(convname,newtype);
2982:     PetscStrcat(convname,"_C");
2983:     PetscObjectQueryFunction((PetscObject)B,convname,&conv);
2984:     if (conv) {
2985:       DMDestroy(&B);
2986:       goto foundconv;
2987:     }

2989: #if 0
2990:     /* 3) See if a good general converter is registered for the desired class */
2991:     conv = B->ops->convertfrom;
2992:     DMDestroy(&B);
2993:     if (conv) goto foundconv;

2995:     /* 4) See if a good general converter is known for the current matrix */
2996:     if (dm->ops->convert) {
2997:       conv = dm->ops->convert;
2998:     }
2999:     if (conv) goto foundconv;
3000: #endif

3002:     /* 5) Use a really basic converter. */
3003:     SETERRQ2(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "No conversion possible between DM types %s and %s", ((PetscObject) dm)->type_name, newtype);

3005: foundconv:
3006:     PetscLogEventBegin(DM_Convert,dm,0,0,0);
3007:     (*conv)(dm,newtype,M);
3008:     /* Things that are independent of DM type: We should consult DMClone() here */
3009:     if (dm->maxCell) {
3010:       const PetscReal *maxCell, *L;
3011:       const DMBoundaryType *bd;
3012:       DMGetPeriodicity(dm, &maxCell, &L, &bd);
3013:       DMSetPeriodicity(*M,  maxCell,  L,  bd);
3014:     }
3015:     PetscLogEventEnd(DM_Convert,dm,0,0,0);
3016:   }
3017:   PetscObjectStateIncrease((PetscObject) *M);
3018:   return(0);
3019: }

3021: /*--------------------------------------------------------------------------------------------------------------------*/

3023: /*@C
3024:   DMRegister -  Adds a new DM component implementation

3026:   Not Collective

3028:   Input Parameters:
3029: + name        - The name of a new user-defined creation routine
3030: - create_func - The creation routine itself

3032:   Notes:
3033:   DMRegister() may be called multiple times to add several user-defined DMs


3036:   Sample usage:
3037: .vb
3038:     DMRegister("my_da", MyDMCreate);
3039: .ve

3041:   Then, your DM type can be chosen with the procedural interface via
3042: .vb
3043:     DMCreate(MPI_Comm, DM *);
3044:     DMSetType(DM,"my_da");
3045: .ve
3046:    or at runtime via the option
3047: .vb
3048:     -da_type my_da
3049: .ve

3051:   Level: advanced

3053: .keywords: DM, register
3054: .seealso: DMRegisterAll(), DMRegisterDestroy()

3056: @*/
3057: PetscErrorCode  DMRegister(const char sname[],PetscErrorCode (*function)(DM))
3058: {

3062:   PetscFunctionListAdd(&DMList,sname,function);
3063:   return(0);
3064: }

3066: /*@C
3067:   DMLoad - Loads a DM that has been stored in binary  with DMView().

3069:   Collective on PetscViewer

3071:   Input Parameters:
3072: + newdm - the newly loaded DM, this needs to have been created with DMCreate() or
3073:            some related function before a call to DMLoad().
3074: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen() or
3075:            HDF5 file viewer, obtained from PetscViewerHDF5Open()

3077:    Level: intermediate

3079:   Notes:
3080:    The type is determined by the data in the file, any type set into the DM before this call is ignored.

3082:   Notes for advanced users:
3083:   Most users should not need to know the details of the binary storage
3084:   format, since DMLoad() and DMView() completely hide these details.
3085:   But for anyone who's interested, the standard binary matrix storage
3086:   format is
3087: .vb
3088:      has not yet been determined
3089: .ve

3091: .seealso: PetscViewerBinaryOpen(), DMView(), MatLoad(), VecLoad()
3092: @*/
3093: PetscErrorCode  DMLoad(DM newdm, PetscViewer viewer)
3094: {
3095:   PetscBool      isbinary, ishdf5;

3101:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
3102:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERHDF5,&ishdf5);
3103:   if (isbinary) {
3104:     PetscInt classid;
3105:     char     type[256];

3107:     PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
3108:     if (classid != DM_FILE_CLASSID) SETERRQ1(PetscObjectComm((PetscObject)newdm),PETSC_ERR_ARG_WRONG,"Not DM next in file, classid found %d",(int)classid);
3109:     PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
3110:     DMSetType(newdm, type);
3111:     if (newdm->ops->load) {(*newdm->ops->load)(newdm,viewer);}
3112:   } else if (ishdf5) {
3113:     if (newdm->ops->load) {(*newdm->ops->load)(newdm,viewer);}
3114:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
3115:   return(0);
3116: }

3118: /******************************** FEM Support **********************************/

3120: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
3121: {
3122:   PetscInt       f;

3126:   PetscPrintf(PETSC_COMM_SELF, "Cell %D Element %s\n", c, name);
3127:   for (f = 0; f < len; ++f) {
3128:     PetscPrintf(PETSC_COMM_SELF, "  | %g |\n", (double)PetscRealPart(x[f]));
3129:   }
3130:   return(0);
3131: }

3133: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
3134: {
3135:   PetscInt       f, g;

3139:   PetscPrintf(PETSC_COMM_SELF, "Cell %D Element %s\n", c, name);
3140:   for (f = 0; f < rows; ++f) {
3141:     PetscPrintf(PETSC_COMM_SELF, "  |");
3142:     for (g = 0; g < cols; ++g) {
3143:       PetscPrintf(PETSC_COMM_SELF, " % 9.5g", PetscRealPart(A[f*cols+g]));
3144:     }
3145:     PetscPrintf(PETSC_COMM_SELF, " |\n");
3146:   }
3147:   return(0);
3148: }

3150: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
3151: {
3152:   PetscMPIInt    rank, size;
3153:   PetscInt       p;

3157:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
3158:   MPI_Comm_size(PetscObjectComm((PetscObject) dm), &size);
3159:   PetscPrintf(PetscObjectComm((PetscObject) dm), "%s:\n", name);
3160:   for (p = 0; p < size; ++p) {
3161:     if (p == rank) {
3162:       Vec x;

3164:       VecDuplicate(X, &x);
3165:       VecCopy(X, x);
3166:       VecChop(x, tol);
3167:       VecView(x, PETSC_VIEWER_STDOUT_SELF);
3168:       VecDestroy(&x);
3169:       PetscViewerFlush(PETSC_VIEWER_STDOUT_SELF);
3170:     }
3171:     PetscBarrier((PetscObject) dm);
3172:   }
3173:   return(0);
3174: }

3176: /*@
3177:   DMGetDefaultSection - Get the PetscSection encoding the local data layout for the DM.

3179:   Input Parameter:
3180: . dm - The DM

3182:   Output Parameter:
3183: . section - The PetscSection

3185:   Level: intermediate

3187:   Note: This gets a borrowed reference, so the user should not destroy this PetscSection.

3189: .seealso: DMSetDefaultSection(), DMGetDefaultGlobalSection()
3190: @*/
3191: PetscErrorCode DMGetDefaultSection(DM dm, PetscSection *section)
3192: {

3198:   if (!dm->defaultSection && dm->ops->createdefaultsection) {
3199:     (*dm->ops->createdefaultsection)(dm);
3200:     if (dm->defaultSection) {PetscObjectViewFromOptions((PetscObject) dm->defaultSection, NULL, "-dm_petscsection_view");}
3201:   }
3202:   *section = dm->defaultSection;
3203:   return(0);
3204: }

3206: /*@
3207:   DMSetDefaultSection - Set the PetscSection encoding the local data layout for the DM.

3209:   Input Parameters:
3210: + dm - The DM
3211: - section - The PetscSection

3213:   Level: intermediate

3215:   Note: Any existing Section will be destroyed

3217: .seealso: DMSetDefaultSection(), DMGetDefaultGlobalSection()
3218: @*/
3219: PetscErrorCode DMSetDefaultSection(DM dm, PetscSection section)
3220: {
3221:   PetscInt       numFields = 0;
3222:   PetscInt       f;

3227:   if (section) {
3229:     PetscObjectReference((PetscObject)section);
3230:   }
3231:   PetscSectionDestroy(&dm->defaultSection);
3232:   dm->defaultSection = section;
3233:   if (section) {PetscSectionGetNumFields(dm->defaultSection, &numFields);}
3234:   if (numFields) {
3235:     DMSetNumFields(dm, numFields);
3236:     for (f = 0; f < numFields; ++f) {
3237:       PetscObject disc;
3238:       const char *name;

3240:       PetscSectionGetFieldName(dm->defaultSection, f, &name);
3241:       DMGetField(dm, f, &disc);
3242:       PetscObjectSetName(disc, name);
3243:     }
3244:   }
3245:   /* The global section will be rebuilt in the next call to DMGetDefaultGlobalSection(). */
3246:   PetscSectionDestroy(&dm->defaultGlobalSection);
3247:   return(0);
3248: }

3250: /*@
3251:   DMGetDefaultConstraints - Get the PetscSection and Mat the specify the local constraint interpolation. See DMSetDefaultConstraints() for a description of the purpose of constraint interpolation.

3253:   not collective

3255:   Input Parameter:
3256: . dm - The DM

3258:   Output Parameter:
3259: + section - The PetscSection describing the range of the constraint matrix: relates rows of the constraint matrix to dofs of the default section.  Returns NULL if there are no local constraints.
3260: - mat - The Mat that interpolates local constraints: its width should be the layout size of the default section.  Returns NULL if there are no local constraints.

3262:   Level: advanced

3264:   Note: This gets borrowed references, so the user should not destroy the PetscSection or the Mat.

3266: .seealso: DMSetDefaultConstraints()
3267: @*/
3268: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat)
3269: {

3274:   if (!dm->defaultConstraintSection && !dm->defaultConstraintMat && dm->ops->createdefaultconstraints) {(*dm->ops->createdefaultconstraints)(dm);}
3275:   if (section) {*section = dm->defaultConstraintSection;}
3276:   if (mat) {*mat = dm->defaultConstraintMat;}
3277:   return(0);
3278: }

3280: /*@
3281:   DMSetDefaultConstraints - Set the PetscSection and Mat the specify the local constraint interpolation.

3283:   If a constraint matrix is specified, then it is applied during DMGlobalToLocalEnd() when mode is INSERT_VALUES, INSERT_BC_VALUES, or INSERT_ALL_VALUES.  Without a constraint matrix, the local vector l returned by DMGlobalToLocalEnd() contains values that have been scattered from a global vector without modification; with a constraint matrix A, l is modified by computing c = A * l, l[s[i]] = c[i], where the scatter s is defined by the PetscSection returned by DMGetDefaultConstraintMatrix().

3285:   If a constraint matrix is specified, then its adjoint is applied during DMLocalToGlobalBegin() when mode is ADD_VALUES, ADD_BC_VALUES, or ADD_ALL_VALUES.  Without a constraint matrix, the local vector l is accumulated into a global vector without modification; with a constraint matrix A, l is first modified by computing c[i] = l[s[i]], l[s[i]] = 0, l = l + A'*c, which is the adjoint of the operation described above.

3287:   collective on dm

3289:   Input Parameters:
3290: + dm - The DM
3291: + section - The PetscSection describing the range of the constraint matrix: relates rows of the constraint matrix to dofs of the default section.  Must have a local communicator (PETSC_COMM_SELF or derivative).
3292: - mat - The Mat that interpolates local constraints: its width should be the layout size of the default section:  NULL indicates no constraints.  Must have a local communicator (PETSC_COMM_SELF or derivative).

3294:   Level: advanced

3296:   Note: This increments the references of the PetscSection and the Mat, so they user can destroy them

3298: .seealso: DMGetDefaultConstraints()
3299: @*/
3300: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat)
3301: {
3302:   PetscMPIInt result;

3307:   if (section) {
3309:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)section),&result);
3310:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"constraint section must have local communicator");
3311:   }
3312:   if (mat) {
3314:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)mat),&result);
3315:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"constraint matrix must have local communicator");
3316:   }
3317:   PetscObjectReference((PetscObject)section);
3318:   PetscSectionDestroy(&dm->defaultConstraintSection);
3319:   dm->defaultConstraintSection = section;
3320:   PetscObjectReference((PetscObject)mat);
3321:   MatDestroy(&dm->defaultConstraintMat);
3322:   dm->defaultConstraintMat = mat;
3323:   return(0);
3324: }

3326: #ifdef PETSC_USE_DEBUG
3327: /*
3328:   DMDefaultSectionCheckConsistency - Check the consistentcy of the global and local sections.

3330:   Input Parameters:
3331: + dm - The DM
3332: . localSection - PetscSection describing the local data layout
3333: - globalSection - PetscSection describing the global data layout

3335:   Level: intermediate

3337: .seealso: DMGetDefaultSF(), DMSetDefaultSF()
3338: */
3339: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
3340: {
3341:   MPI_Comm        comm;
3342:   PetscLayout     layout;
3343:   const PetscInt *ranges;
3344:   PetscInt        pStart, pEnd, p, nroots;
3345:   PetscMPIInt     size, rank;
3346:   PetscBool       valid = PETSC_TRUE, gvalid;
3347:   PetscErrorCode  ierr;

3350:   PetscObjectGetComm((PetscObject)dm,&comm);
3352:   MPI_Comm_size(comm, &size);
3353:   MPI_Comm_rank(comm, &rank);
3354:   PetscSectionGetChart(globalSection, &pStart, &pEnd);
3355:   PetscSectionGetConstrainedStorageSize(globalSection, &nroots);
3356:   PetscLayoutCreate(comm, &layout);
3357:   PetscLayoutSetBlockSize(layout, 1);
3358:   PetscLayoutSetLocalSize(layout, nroots);
3359:   PetscLayoutSetUp(layout);
3360:   PetscLayoutGetRanges(layout, &ranges);
3361:   for (p = pStart; p < pEnd; ++p) {
3362:     PetscInt       dof, cdof, off, gdof, gcdof, goff, gsize, d;

3364:     PetscSectionGetDof(localSection, p, &dof);
3365:     PetscSectionGetOffset(localSection, p, &off);
3366:     PetscSectionGetConstraintDof(localSection, p, &cdof);
3367:     PetscSectionGetDof(globalSection, p, &gdof);
3368:     PetscSectionGetConstraintDof(globalSection, p, &gcdof);
3369:     PetscSectionGetOffset(globalSection, p, &goff);
3370:     if (!gdof) continue; /* Censored point */
3371:     if ((gdof < 0 ? -(gdof+1) : gdof) != dof) {PetscSynchronizedPrintf(comm, "[%d]Global dof %d for point %d not equal to local dof %d\n", rank, gdof, p, dof); valid = PETSC_FALSE;}
3372:     if (gcdof && (gcdof != cdof)) {PetscSynchronizedPrintf(comm, "[%d]Global constraints %d for point %d not equal to local constraints %d\n", rank, gcdof, p, cdof); valid = PETSC_FALSE;}
3373:     if (gdof < 0) {
3374:       gsize = gdof < 0 ? -(gdof+1)-gcdof : gdof-gcdof;
3375:       for (d = 0; d < gsize; ++d) {
3376:         PetscInt offset = -(goff+1) + d, r;

3378:         PetscFindInt(offset,size+1,ranges,&r);
3379:         if (r < 0) r = -(r+2);
3380:         if ((r < 0) || (r >= size)) {PetscSynchronizedPrintf(comm, "[%d]Point %d mapped to invalid process %d (%d, %d)\n", rank, p, r, gdof, goff); valid = PETSC_FALSE;break;}
3381:       }
3382:     }
3383:   }
3384:   PetscLayoutDestroy(&layout);
3385:   PetscSynchronizedFlush(comm, NULL);
3386:   MPIU_Allreduce(&valid, &gvalid, 1, MPIU_BOOL, MPI_LAND, comm);
3387:   if (!gvalid) {
3388:     DMView(dm, NULL);
3389:     SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Inconsistent local and global sections");
3390:   }
3391:   return(0);
3392: }
3393: #endif

3395: /*@
3396:   DMGetDefaultGlobalSection - Get the PetscSection encoding the global data layout for the DM.

3398:   Collective on DM

3400:   Input Parameter:
3401: . dm - The DM

3403:   Output Parameter:
3404: . section - The PetscSection

3406:   Level: intermediate

3408:   Note: This gets a borrowed reference, so the user should not destroy this PetscSection.

3410: .seealso: DMSetDefaultSection(), DMGetDefaultSection()
3411: @*/
3412: PetscErrorCode DMGetDefaultGlobalSection(DM dm, PetscSection *section)
3413: {

3419:   if (!dm->defaultGlobalSection) {
3420:     PetscSection s;

3422:     DMGetDefaultSection(dm, &s);
3423:     if (!s)  SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
3424:     if (!dm->sf) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSF in order to create a global PetscSection");
3425:     PetscSectionCreateGlobalSection(s, dm->sf, PETSC_FALSE, PETSC_FALSE, &dm->defaultGlobalSection);
3426:     PetscLayoutDestroy(&dm->map);
3427:     PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->defaultGlobalSection, &dm->map);
3428:     PetscSectionViewFromOptions(dm->defaultGlobalSection, NULL, "-global_section_view");
3429:   }
3430:   *section = dm->defaultGlobalSection;
3431:   return(0);
3432: }

3434: /*@
3435:   DMSetDefaultGlobalSection - Set the PetscSection encoding the global data layout for the DM.

3437:   Input Parameters:
3438: + dm - The DM
3439: - section - The PetscSection, or NULL

3441:   Level: intermediate

3443:   Note: Any existing Section will be destroyed

3445: .seealso: DMGetDefaultGlobalSection(), DMSetDefaultSection()
3446: @*/
3447: PetscErrorCode DMSetDefaultGlobalSection(DM dm, PetscSection section)
3448: {

3454:   PetscObjectReference((PetscObject)section);
3455:   PetscSectionDestroy(&dm->defaultGlobalSection);
3456:   dm->defaultGlobalSection = section;
3457: #ifdef PETSC_USE_DEBUG
3458:   if (section) {DMDefaultSectionCheckConsistency_Internal(dm, dm->defaultSection, section);}
3459: #endif
3460:   return(0);
3461: }

3463: /*@
3464:   DMGetDefaultSF - Get the PetscSF encoding the parallel dof overlap for the DM. If it has not been set,
3465:   it is created from the default PetscSection layouts in the DM.

3467:   Input Parameter:
3468: . dm - The DM

3470:   Output Parameter:
3471: . sf - The PetscSF

3473:   Level: intermediate

3475:   Note: This gets a borrowed reference, so the user should not destroy this PetscSF.

3477: .seealso: DMSetDefaultSF(), DMCreateDefaultSF()
3478: @*/
3479: PetscErrorCode DMGetDefaultSF(DM dm, PetscSF *sf)
3480: {
3481:   PetscInt       nroots;

3487:   PetscSFGetGraph(dm->defaultSF, &nroots, NULL, NULL, NULL);
3488:   if (nroots < 0) {
3489:     PetscSection section, gSection;

3491:     DMGetDefaultSection(dm, &section);
3492:     if (section) {
3493:       DMGetDefaultGlobalSection(dm, &gSection);
3494:       DMCreateDefaultSF(dm, section, gSection);
3495:     } else {
3496:       *sf = NULL;
3497:       return(0);
3498:     }
3499:   }
3500:   *sf = dm->defaultSF;
3501:   return(0);
3502: }

3504: /*@
3505:   DMSetDefaultSF - Set the PetscSF encoding the parallel dof overlap for the DM

3507:   Input Parameters:
3508: + dm - The DM
3509: - sf - The PetscSF

3511:   Level: intermediate

3513:   Note: Any previous SF is destroyed

3515: .seealso: DMGetDefaultSF(), DMCreateDefaultSF()
3516: @*/
3517: PetscErrorCode DMSetDefaultSF(DM dm, PetscSF sf)
3518: {

3524:   PetscSFDestroy(&dm->defaultSF);
3525:   dm->defaultSF = sf;
3526:   return(0);
3527: }

3529: /*@C
3530:   DMCreateDefaultSF - Create the PetscSF encoding the parallel dof overlap for the DM based upon the PetscSections
3531:   describing the data layout.

3533:   Input Parameters:
3534: + dm - The DM
3535: . localSection - PetscSection describing the local data layout
3536: - globalSection - PetscSection describing the global data layout

3538:   Level: intermediate

3540: .seealso: DMGetDefaultSF(), DMSetDefaultSF()
3541: @*/
3542: PetscErrorCode DMCreateDefaultSF(DM dm, PetscSection localSection, PetscSection globalSection)
3543: {
3544:   MPI_Comm       comm;
3545:   PetscLayout    layout;
3546:   const PetscInt *ranges;
3547:   PetscInt       *local;
3548:   PetscSFNode    *remote;
3549:   PetscInt       pStart, pEnd, p, nroots, nleaves = 0, l;
3550:   PetscMPIInt    size, rank;

3554:   PetscObjectGetComm((PetscObject)dm,&comm);
3556:   MPI_Comm_size(comm, &size);
3557:   MPI_Comm_rank(comm, &rank);
3558:   PetscSectionGetChart(globalSection, &pStart, &pEnd);
3559:   PetscSectionGetConstrainedStorageSize(globalSection, &nroots);
3560:   PetscLayoutCreate(comm, &layout);
3561:   PetscLayoutSetBlockSize(layout, 1);
3562:   PetscLayoutSetLocalSize(layout, nroots);
3563:   PetscLayoutSetUp(layout);
3564:   PetscLayoutGetRanges(layout, &ranges);
3565:   for (p = pStart; p < pEnd; ++p) {
3566:     PetscInt gdof, gcdof;

3568:     PetscSectionGetDof(globalSection, p, &gdof);
3569:     PetscSectionGetConstraintDof(globalSection, p, &gcdof);
3570:     if (gcdof > (gdof < 0 ? -(gdof+1) : gdof)) SETERRQ3(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Point %d has %d constraints > %d dof", p, gcdof, (gdof < 0 ? -(gdof+1) : gdof));
3571:     nleaves += gdof < 0 ? -(gdof+1)-gcdof : gdof-gcdof;
3572:   }
3573:   PetscMalloc1(nleaves, &local);
3574:   PetscMalloc1(nleaves, &remote);
3575:   for (p = pStart, l = 0; p < pEnd; ++p) {
3576:     const PetscInt *cind;
3577:     PetscInt       dof, cdof, off, gdof, gcdof, goff, gsize, d, c;

3579:     PetscSectionGetDof(localSection, p, &dof);
3580:     PetscSectionGetOffset(localSection, p, &off);
3581:     PetscSectionGetConstraintDof(localSection, p, &cdof);
3582:     PetscSectionGetConstraintIndices(localSection, p, &cind);
3583:     PetscSectionGetDof(globalSection, p, &gdof);
3584:     PetscSectionGetConstraintDof(globalSection, p, &gcdof);
3585:     PetscSectionGetOffset(globalSection, p, &goff);
3586:     if (!gdof) continue; /* Censored point */
3587:     gsize = gdof < 0 ? -(gdof+1)-gcdof : gdof-gcdof;
3588:     if (gsize != dof-cdof) {
3589:       if (gsize != dof) SETERRQ4(comm, PETSC_ERR_ARG_WRONG, "Global dof %d for point %d is neither the constrained size %d, nor the unconstrained %d", gsize, p, dof-cdof, dof);
3590:       cdof = 0; /* Ignore constraints */
3591:     }
3592:     for (d = 0, c = 0; d < dof; ++d) {
3593:       if ((c < cdof) && (cind[c] == d)) {++c; continue;}
3594:       local[l+d-c] = off+d;
3595:     }
3596:     if (gdof < 0) {
3597:       for (d = 0; d < gsize; ++d, ++l) {
3598:         PetscInt offset = -(goff+1) + d, r;

3600:         PetscFindInt(offset,size+1,ranges,&r);
3601:         if (r < 0) r = -(r+2);
3602:         if ((r < 0) || (r >= size)) SETERRQ4(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Point %d mapped to invalid process %d (%d, %d)", p, r, gdof, goff);
3603:         remote[l].rank  = r;
3604:         remote[l].index = offset - ranges[r];
3605:       }
3606:     } else {
3607:       for (d = 0; d < gsize; ++d, ++l) {
3608:         remote[l].rank  = rank;
3609:         remote[l].index = goff+d - ranges[rank];
3610:       }
3611:     }
3612:   }
3613:   if (l != nleaves) SETERRQ2(comm, PETSC_ERR_PLIB, "Iteration error, l %d != nleaves %d", l, nleaves);
3614:   PetscLayoutDestroy(&layout);
3615:   PetscSFSetGraph(dm->defaultSF, nroots, nleaves, local, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER);
3616:   return(0);
3617: }

3619: /*@
3620:   DMGetPointSF - Get the PetscSF encoding the parallel section point overlap for the DM.

3622:   Input Parameter:
3623: . dm - The DM

3625:   Output Parameter:
3626: . sf - The PetscSF

3628:   Level: intermediate

3630:   Note: This gets a borrowed reference, so the user should not destroy this PetscSF.

3632: .seealso: DMSetPointSF(), DMGetDefaultSF(), DMSetDefaultSF(), DMCreateDefaultSF()
3633: @*/
3634: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
3635: {
3639:   *sf = dm->sf;
3640:   return(0);
3641: }

3643: /*@
3644:   DMSetPointSF - Set the PetscSF encoding the parallel section point overlap for the DM.

3646:   Input Parameters:
3647: + dm - The DM
3648: - sf - The PetscSF

3650:   Level: intermediate

3652: .seealso: DMGetPointSF(), DMGetDefaultSF(), DMSetDefaultSF(), DMCreateDefaultSF()
3653: @*/
3654: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
3655: {

3661:   PetscSFDestroy(&dm->sf);
3662:   PetscObjectReference((PetscObject) sf);
3663:   dm->sf = sf;
3664:   return(0);
3665: }

3667: /*@
3668:   DMGetDS - Get the PetscDS

3670:   Input Parameter:
3671: . dm - The DM

3673:   Output Parameter:
3674: . prob - The PetscDS

3676:   Level: developer

3678: .seealso: DMSetDS()
3679: @*/
3680: PetscErrorCode DMGetDS(DM dm, PetscDS *prob)
3681: {
3685:   *prob = dm->prob;
3686:   return(0);
3687: }

3689: /*@
3690:   DMSetDS - Set the PetscDS

3692:   Input Parameters:
3693: + dm - The DM
3694: - prob - The PetscDS

3696:   Level: developer

3698: .seealso: DMGetDS()
3699: @*/
3700: PetscErrorCode DMSetDS(DM dm, PetscDS prob)
3701: {

3707:   PetscObjectReference((PetscObject) prob);
3708:   PetscDSDestroy(&dm->prob);
3709:   dm->prob = prob;
3710:   return(0);
3711: }

3713: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
3714: {

3719:   PetscDSGetNumFields(dm->prob, numFields);
3720:   return(0);
3721: }

3723: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
3724: {
3725:   PetscInt       Nf, f;

3730:   PetscDSGetNumFields(dm->prob, &Nf);
3731:   for (f = Nf; f < numFields; ++f) {
3732:     PetscContainer obj;

3734:     PetscContainerCreate(PetscObjectComm((PetscObject) dm), &obj);
3735:     PetscDSSetDiscretization(dm->prob, f, (PetscObject) obj);
3736:     PetscContainerDestroy(&obj);
3737:   }
3738:   return(0);
3739: }

3741: /*@
3742:   DMGetField - Return the discretization object for a given DM field

3744:   Not collective

3746:   Input Parameters:
3747: + dm - The DM
3748: - f  - The field number

3750:   Output Parameter:
3751: . field - The discretization object

3753:   Level: developer

3755: .seealso: DMSetField()
3756: @*/
3757: PetscErrorCode DMGetField(DM dm, PetscInt f, PetscObject *field)
3758: {

3763:   PetscDSGetDiscretization(dm->prob, f, field);
3764:   return(0);
3765: }

3767: /*@
3768:   DMSetField - Set the discretization object for a given DM field

3770:   Logically collective on DM

3772:   Input Parameters:
3773: + dm - The DM
3774: . f  - The field number
3775: - field - The discretization object

3777:   Level: developer

3779: .seealso: DMGetField()
3780: @*/
3781: PetscErrorCode DMSetField(DM dm, PetscInt f, PetscObject field)
3782: {

3787:   PetscDSSetDiscretization(dm->prob, f, field);
3788:   return(0);
3789: }

3791: PetscErrorCode DMRestrictHook_Coordinates(DM dm,DM dmc,void *ctx)
3792: {
3793:   DM dm_coord,dmc_coord;
3795:   Vec coords,ccoords;
3796:   Mat inject;
3798:   DMGetCoordinateDM(dm,&dm_coord);
3799:   DMGetCoordinateDM(dmc,&dmc_coord);
3800:   DMGetCoordinates(dm,&coords);
3801:   DMGetCoordinates(dmc,&ccoords);
3802:   if (coords && !ccoords) {
3803:     DMCreateGlobalVector(dmc_coord,&ccoords);
3804:     PetscObjectSetName((PetscObject)ccoords,"coordinates");
3805:     DMCreateInjection(dmc_coord,dm_coord,&inject);
3806:     MatRestrict(inject,coords,ccoords);
3807:     MatDestroy(&inject);
3808:     DMSetCoordinates(dmc,ccoords);
3809:     VecDestroy(&ccoords);
3810:   }
3811:   return(0);
3812: }

3814: static PetscErrorCode DMSubDomainHook_Coordinates(DM dm,DM subdm,void *ctx)
3815: {
3816:   DM dm_coord,subdm_coord;
3818:   Vec coords,ccoords,clcoords;
3819:   VecScatter *scat_i,*scat_g;
3821:   DMGetCoordinateDM(dm,&dm_coord);
3822:   DMGetCoordinateDM(subdm,&subdm_coord);
3823:   DMGetCoordinates(dm,&coords);
3824:   DMGetCoordinates(subdm,&ccoords);
3825:   if (coords && !ccoords) {
3826:     DMCreateGlobalVector(subdm_coord,&ccoords);
3827:     PetscObjectSetName((PetscObject)ccoords,"coordinates");
3828:     DMCreateLocalVector(subdm_coord,&clcoords);
3829:     PetscObjectSetName((PetscObject)clcoords,"coordinates");
3830:     DMCreateDomainDecompositionScatters(dm_coord,1,&subdm_coord,NULL,&scat_i,&scat_g);
3831:     VecScatterBegin(scat_i[0],coords,ccoords,INSERT_VALUES,SCATTER_FORWARD);
3832:     VecScatterBegin(scat_g[0],coords,clcoords,INSERT_VALUES,SCATTER_FORWARD);
3833:     VecScatterEnd(scat_i[0],coords,ccoords,INSERT_VALUES,SCATTER_FORWARD);
3834:     VecScatterEnd(scat_g[0],coords,clcoords,INSERT_VALUES,SCATTER_FORWARD);
3835:     DMSetCoordinates(subdm,ccoords);
3836:     DMSetCoordinatesLocal(subdm,clcoords);
3837:     VecScatterDestroy(&scat_i[0]);
3838:     VecScatterDestroy(&scat_g[0]);
3839:     VecDestroy(&ccoords);
3840:     VecDestroy(&clcoords);
3841:     PetscFree(scat_i);
3842:     PetscFree(scat_g);
3843:   }
3844:   return(0);
3845: }

3847: /*@
3848:   DMGetDimension - Return the topological dimension of the DM

3850:   Not collective

3852:   Input Parameter:
3853: . dm - The DM

3855:   Output Parameter:
3856: . dim - The topological dimension

3858:   Level: beginner

3860: .seealso: DMSetDimension(), DMCreate()
3861: @*/
3862: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
3863: {
3867:   *dim = dm->dim;
3868:   return(0);
3869: }

3871: /*@
3872:   DMSetDimension - Set the topological dimension of the DM

3874:   Collective on dm

3876:   Input Parameters:
3877: + dm - The DM
3878: - dim - The topological dimension

3880:   Level: beginner

3882: .seealso: DMGetDimension(), DMCreate()
3883: @*/
3884: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
3885: {
3889:   dm->dim = dim;
3890:   return(0);
3891: }

3893: /*@
3894:   DMGetDimPoints - Get the half-open interval for all points of a given dimension

3896:   Collective on DM

3898:   Input Parameters:
3899: + dm - the DM
3900: - dim - the dimension

3902:   Output Parameters:
3903: + pStart - The first point of the given dimension
3904: . pEnd - The first point following points of the given dimension

3906:   Note:
3907:   The points are vertices in the Hasse diagram encoding the topology. This is explained in
3908:   http://arxiv.org/abs/0908.4427. If not points exist of this dimension in the storage scheme,
3909:   then the interval is empty.

3911:   Level: intermediate

3913: .keywords: point, Hasse Diagram, dimension
3914: .seealso: DMPLEX, DMPlexGetDepthStratum(), DMPlexGetHeightStratum()
3915: @*/
3916: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
3917: {
3918:   PetscInt       d;

3923:   DMGetDimension(dm, &d);
3924:   if ((dim < 0) || (dim > d)) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %d 1", dim, d);
3925:   (*dm->ops->getdimpoints)(dm, dim, pStart, pEnd);
3926:   return(0);
3927: }

3929: /*@
3930:   DMSetCoordinates - Sets into the DM a global vector that holds the coordinates

3932:   Collective on DM

3934:   Input Parameters:
3935: + dm - the DM
3936: - c - coordinate vector

3938:   Note:
3939:   The coordinates do include those for ghost points, which are in the local vector

3941:   Level: intermediate

3943: .keywords: distributed array, get, corners, nodes, local indices, coordinates
3944: .seealso: DMSetCoordinatesLocal(), DMGetCoordinates(), DMGetCoordinatesLoca(), DMGetCoordinateDM()
3945: @*/
3946: PetscErrorCode DMSetCoordinates(DM dm, Vec c)
3947: {

3953:   PetscObjectReference((PetscObject) c);
3954:   VecDestroy(&dm->coordinates);
3955:   dm->coordinates = c;
3956:   VecDestroy(&dm->coordinatesLocal);
3957:   DMCoarsenHookAdd(dm,DMRestrictHook_Coordinates,NULL,NULL);
3958:   DMSubDomainHookAdd(dm,DMSubDomainHook_Coordinates,NULL,NULL);
3959:   return(0);
3960: }

3962: /*@
3963:   DMSetCoordinatesLocal - Sets into the DM a local vector that holds the coordinates

3965:   Collective on DM

3967:    Input Parameters:
3968: +  dm - the DM
3969: -  c - coordinate vector

3971:   Note:
3972:   The coordinates of ghost points can be set using DMSetCoordinates()
3973:   followed by DMGetCoordinatesLocal(). This is intended to enable the
3974:   setting of ghost coordinates outside of the domain.

3976:   Level: intermediate

3978: .keywords: distributed array, get, corners, nodes, local indices, coordinates
3979: .seealso: DMGetCoordinatesLocal(), DMSetCoordinates(), DMGetCoordinates(), DMGetCoordinateDM()
3980: @*/
3981: PetscErrorCode DMSetCoordinatesLocal(DM dm, Vec c)
3982: {

3988:   PetscObjectReference((PetscObject) c);
3989:   VecDestroy(&dm->coordinatesLocal);

3991:   dm->coordinatesLocal = c;

3993:   VecDestroy(&dm->coordinates);
3994:   return(0);
3995: }

3997: /*@
3998:   DMGetCoordinates - Gets a global vector with the coordinates associated with the DM.

4000:   Not Collective

4002:   Input Parameter:
4003: . dm - the DM

4005:   Output Parameter:
4006: . c - global coordinate vector

4008:   Note:
4009:   This is a borrowed reference, so the user should NOT destroy this vector

4011:   Each process has only the local coordinates (does NOT have the ghost coordinates).

4013:   For DMDA, in two and three dimensions coordinates are interlaced (x_0,y_0,x_1,y_1,...)
4014:   and (x_0,y_0,z_0,x_1,y_1,z_1...)

4016:   Level: intermediate

4018: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4019: .seealso: DMSetCoordinates(), DMGetCoordinatesLocal(), DMGetCoordinateDM()
4020: @*/
4021: PetscErrorCode DMGetCoordinates(DM dm, Vec *c)
4022: {

4028:   if (!dm->coordinates && dm->coordinatesLocal) {
4029:     DM cdm = NULL;

4031:     DMGetCoordinateDM(dm, &cdm);
4032:     DMCreateGlobalVector(cdm, &dm->coordinates);
4033:     PetscObjectSetName((PetscObject) dm->coordinates, "coordinates");
4034:     DMLocalToGlobalBegin(cdm, dm->coordinatesLocal, INSERT_VALUES, dm->coordinates);
4035:     DMLocalToGlobalEnd(cdm, dm->coordinatesLocal, INSERT_VALUES, dm->coordinates);
4036:   }
4037:   *c = dm->coordinates;
4038:   return(0);
4039: }

4041: /*@
4042:   DMGetCoordinatesLocal - Gets a local vector with the coordinates associated with the DM.

4044:   Collective on DM

4046:   Input Parameter:
4047: . dm - the DM

4049:   Output Parameter:
4050: . c - coordinate vector

4052:   Note:
4053:   This is a borrowed reference, so the user should NOT destroy this vector

4055:   Each process has the local and ghost coordinates

4057:   For DMDA, in two and three dimensions coordinates are interlaced (x_0,y_0,x_1,y_1,...)
4058:   and (x_0,y_0,z_0,x_1,y_1,z_1...)

4060:   Level: intermediate

4062: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4063: .seealso: DMSetCoordinatesLocal(), DMGetCoordinates(), DMSetCoordinates(), DMGetCoordinateDM()
4064: @*/
4065: PetscErrorCode DMGetCoordinatesLocal(DM dm, Vec *c)
4066: {

4072:   if (!dm->coordinatesLocal && dm->coordinates) {
4073:     DM cdm = NULL;

4075:     DMGetCoordinateDM(dm, &cdm);
4076:     DMCreateLocalVector(cdm, &dm->coordinatesLocal);
4077:     PetscObjectSetName((PetscObject) dm->coordinatesLocal, "coordinates");
4078:     DMGlobalToLocalBegin(cdm, dm->coordinates, INSERT_VALUES, dm->coordinatesLocal);
4079:     DMGlobalToLocalEnd(cdm, dm->coordinates, INSERT_VALUES, dm->coordinatesLocal);
4080:   }
4081:   *c = dm->coordinatesLocal;
4082:   return(0);
4083: }

4085: /*@
4086:   DMGetCoordinateDM - Gets the DM that prescribes coordinate layout and scatters between global and local coordinates

4088:   Collective on DM

4090:   Input Parameter:
4091: . dm - the DM

4093:   Output Parameter:
4094: . cdm - coordinate DM

4096:   Level: intermediate

4098: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4099: .seealso: DMSetCoordinateDM(), DMSetCoordinates(), DMSetCoordinatesLocal(), DMGetCoordinates(), DMGetCoordinatesLocal()
4100: @*/
4101: PetscErrorCode DMGetCoordinateDM(DM dm, DM *cdm)
4102: {

4108:   if (!dm->coordinateDM) {
4109:     if (!dm->ops->createcoordinatedm) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Unable to create coordinates for this DM");
4110:     (*dm->ops->createcoordinatedm)(dm, &dm->coordinateDM);
4111:   }
4112:   *cdm = dm->coordinateDM;
4113:   return(0);
4114: }

4116: /*@
4117:   DMSetCoordinateDM - Sets the DM that prescribes coordinate layout and scatters between global and local coordinates

4119:   Logically Collective on DM

4121:   Input Parameters:
4122: + dm - the DM
4123: - cdm - coordinate DM

4125:   Level: intermediate

4127: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4128: .seealso: DMGetCoordinateDM(), DMSetCoordinates(), DMSetCoordinatesLocal(), DMGetCoordinates(), DMGetCoordinatesLocal()
4129: @*/
4130: PetscErrorCode DMSetCoordinateDM(DM dm, DM cdm)
4131: {

4137:   PetscObjectReference((PetscObject)cdm);
4138:   DMDestroy(&dm->coordinateDM);
4139:   dm->coordinateDM = cdm;
4140:   return(0);
4141: }

4143: /*@
4144:   DMGetCoordinateDim - Retrieve the dimension of embedding space for coordinate values.

4146:   Not Collective

4148:   Input Parameter:
4149: . dm - The DM object

4151:   Output Parameter:
4152: . dim - The embedding dimension

4154:   Level: intermediate

4156: .keywords: mesh, coordinates
4157: .seealso: DMSetCoordinateDim(), DMGetCoordinateSection(), DMGetCoordinateDM(), DMGetDefaultSection(), DMSetDefaultSection()
4158: @*/
4159: PetscErrorCode DMGetCoordinateDim(DM dm, PetscInt *dim)
4160: {
4164:   if (dm->dimEmbed == PETSC_DEFAULT) {
4165:     dm->dimEmbed = dm->dim;
4166:   }
4167:   *dim = dm->dimEmbed;
4168:   return(0);
4169: }

4171: /*@
4172:   DMSetCoordinateDim - Set the dimension of the embedding space for coordinate values.

4174:   Not Collective

4176:   Input Parameters:
4177: + dm  - The DM object
4178: - dim - The embedding dimension

4180:   Level: intermediate

4182: .keywords: mesh, coordinates
4183: .seealso: DMGetCoordinateDim(), DMSetCoordinateSection(), DMGetCoordinateSection(), DMGetDefaultSection(), DMSetDefaultSection()
4184: @*/
4185: PetscErrorCode DMSetCoordinateDim(DM dm, PetscInt dim)
4186: {
4189:   dm->dimEmbed = dim;
4190:   return(0);
4191: }

4193: /*@
4194:   DMGetCoordinateSection - Retrieve the layout of coordinate values over the mesh.

4196:   Not Collective

4198:   Input Parameter:
4199: . dm - The DM object

4201:   Output Parameter:
4202: . section - The PetscSection object

4204:   Level: intermediate

4206: .keywords: mesh, coordinates
4207: .seealso: DMGetCoordinateDM(), DMGetDefaultSection(), DMSetDefaultSection()
4208: @*/
4209: PetscErrorCode DMGetCoordinateSection(DM dm, PetscSection *section)
4210: {
4211:   DM             cdm;

4217:   DMGetCoordinateDM(dm, &cdm);
4218:   DMGetDefaultSection(cdm, section);
4219:   return(0);
4220: }

4222: /*@
4223:   DMSetCoordinateSection - Set the layout of coordinate values over the mesh.

4225:   Not Collective

4227:   Input Parameters:
4228: + dm      - The DM object
4229: . dim     - The embedding dimension, or PETSC_DETERMINE
4230: - section - The PetscSection object

4232:   Level: intermediate

4234: .keywords: mesh, coordinates
4235: .seealso: DMGetCoordinateSection(), DMGetDefaultSection(), DMSetDefaultSection()
4236: @*/
4237: PetscErrorCode DMSetCoordinateSection(DM dm, PetscInt dim, PetscSection section)
4238: {
4239:   DM             cdm;

4245:   DMGetCoordinateDM(dm, &cdm);
4246:   DMSetDefaultSection(cdm, section);
4247:   if (dim == PETSC_DETERMINE) {
4248:     PetscInt d = dim;
4249:     PetscInt pStart, pEnd, vStart, vEnd, v, dd;

4251:     PetscSectionGetChart(section, &pStart, &pEnd);
4252:     DMGetDimPoints(dm, 0, &vStart, &vEnd);
4253:     pStart = PetscMax(vStart, pStart);
4254:     pEnd   = PetscMin(vEnd, pEnd);
4255:     for (v = pStart; v < pEnd; ++v) {
4256:       PetscSectionGetDof(section, v, &dd);
4257:       if (dd) {d = dd; break;}
4258:     }
4259:     if (d < 0) d = PETSC_DEFAULT;
4260:     DMSetCoordinateDim(dm, d);
4261:   }
4262:   return(0);
4263: }

4265: /*@C
4266:   DMSetPeriodicity - Set the description of mesh periodicity

4268:   Input Parameters:
4269: + dm      - The DM object
4270: . maxCell - Over distances greater than this, we can assume a point has crossed over to another sheet, when trying to localize cell coordinates
4271: . L       - If we assume the mesh is a torus, this is the length of each coordinate
4272: - bd      - This describes the type of periodicity in each topological dimension

4274:   Level: developer

4276: .seealso: DMGetPeriodicity()
4277: @*/
4278: PetscErrorCode DMGetPeriodicity(DM dm, const PetscReal **maxCell, const PetscReal **L, const DMBoundaryType **bd)
4279: {
4282:   if (L)       *L       = dm->L;
4283:   if (maxCell) *maxCell = dm->maxCell;
4284:   if (bd)      *bd      = dm->bdtype;
4285:   return(0);
4286: }

4288: /*@C
4289:   DMSetPeriodicity - Set the description of mesh periodicity

4291:   Input Parameters:
4292: + dm      - The DM object
4293: . maxCell - Over distances greater than this, we can assume a point has crossed over to another sheet, when trying to localize cell coordinates
4294: . L       - If we assume the mesh is a torus, this is the length of each coordinate
4295: - bd      - This describes the type of periodicity in each topological dimension

4297:   Level: developer

4299: .seealso: DMGetPeriodicity()
4300: @*/
4301: PetscErrorCode DMSetPeriodicity(DM dm, const PetscReal maxCell[], const PetscReal L[], const DMBoundaryType bd[])
4302: {
4303:   PetscInt       dim, d;

4309:   PetscFree3(dm->L,dm->maxCell,dm->bdtype);
4310:   DMGetDimension(dm, &dim);
4311:   PetscMalloc3(dim,&dm->L,dim,&dm->maxCell,dim,&dm->bdtype);
4312:   for (d = 0; d < dim; ++d) {dm->L[d] = L[d]; dm->maxCell[d] = maxCell[d]; dm->bdtype[d] = bd[d];}
4313:   return(0);
4314: }

4316: /*@
4317:   DMLocalizeCoordinate - If a mesh is periodic (a torus with lengths L_i, some of which can be infinite), project the coordinate onto [0, L_i) in each dimension.

4319:   Input Parameters:
4320: + dm     - The DM
4321: - in     - The input coordinate point (dim numbers)

4323:   Output Parameter:
4324: . out - The localized coordinate point

4326:   Level: developer

4328: .seealso: DMLocalizeCoordinates(), DMLocalizeAddCoordinate()
4329: @*/
4330: PetscErrorCode DMLocalizeCoordinate(DM dm, const PetscScalar in[], PetscScalar out[])
4331: {
4332:   PetscInt       dim, d;

4336:   DMGetCoordinateDim(dm, &dim);
4337:   if (!dm->maxCell) {
4338:     for (d = 0; d < dim; ++d) out[d] = in[d];
4339:   } else {
4340:     for (d = 0; d < dim; ++d) {
4341:       out[d] = in[d] - dm->L[d]*floor(PetscRealPart(in[d])/dm->L[d]);
4342:     }
4343:   }
4344:   return(0);
4345: }

4347: /*
4348:   DMLocalizeCoordinate_Internal - If a mesh is periodic, and the input point is far from the anchor, pick the coordinate sheet of the torus which moves it closer.

4350:   Input Parameters:
4351: + dm     - The DM
4352: . dim    - The spatial dimension
4353: . anchor - The anchor point, the input point can be no more than maxCell away from it
4354: - in     - The input coordinate point (dim numbers)

4356:   Output Parameter:
4357: . out - The localized coordinate point

4359:   Level: developer

4361:   Note: This is meant to get a set of coordinates close to each other, as in a cell. The anchor is usually the one of the vertices on a containing cell

4363: .seealso: DMLocalizeCoordinates(), DMLocalizeAddCoordinate()
4364: */
4365: PetscErrorCode DMLocalizeCoordinate_Internal(DM dm, PetscInt dim, const PetscScalar anchor[], const PetscScalar in[], PetscScalar out[])
4366: {
4367:   PetscInt d;

4370:   if (!dm->maxCell) {
4371:     for (d = 0; d < dim; ++d) out[d] = in[d];
4372:   } else {
4373:     for (d = 0; d < dim; ++d) {
4374:       if (PetscAbsScalar(anchor[d] - in[d]) > dm->maxCell[d]) {
4375:         out[d] = PetscRealPart(anchor[d]) > PetscRealPart(in[d]) ? dm->L[d] + in[d] : in[d] - dm->L[d];
4376:       } else {
4377:         out[d] = in[d];
4378:       }
4379:     }
4380:   }
4381:   return(0);
4382: }
4383: PetscErrorCode DMLocalizeCoordinateReal_Internal(DM dm, PetscInt dim, const PetscReal anchor[], const PetscReal in[], PetscReal out[])
4384: {
4385:   PetscInt d;

4388:   if (!dm->maxCell) {
4389:     for (d = 0; d < dim; ++d) out[d] = in[d];
4390:   } else {
4391:     for (d = 0; d < dim; ++d) {
4392:       if (PetscAbsReal(anchor[d] - in[d]) > dm->maxCell[d]) {
4393:         out[d] = anchor[d] > in[d] ? dm->L[d] + in[d] : in[d] - dm->L[d];
4394:       } else {
4395:         out[d] = in[d];
4396:       }
4397:     }
4398:   }
4399:   return(0);
4400: }

4402: /*
4403:   DMLocalizeAddCoordinate_Internal - If a mesh is periodic, and the input point is far from the anchor, pick the coordinate sheet of the torus which moves it closer.

4405:   Input Parameters:
4406: + dm     - The DM
4407: . dim    - The spatial dimension
4408: . anchor - The anchor point, the input point can be no more than maxCell away from it
4409: . in     - The input coordinate delta (dim numbers)
4410: - out    - The input coordinate point (dim numbers)

4412:   Output Parameter:
4413: . out    - The localized coordinate in + out

4415:   Level: developer

4417:   Note: This is meant to get a set of coordinates close to each other, as in a cell. The anchor is usually the one of the vertices on a containing cell

4419: .seealso: DMLocalizeCoordinates(), DMLocalizeCoordinate()
4420: */
4421: PetscErrorCode DMLocalizeAddCoordinate_Internal(DM dm, PetscInt dim, const PetscScalar anchor[], const PetscScalar in[], PetscScalar out[])
4422: {
4423:   PetscInt d;

4426:   if (!dm->maxCell) {
4427:     for (d = 0; d < dim; ++d) out[d] += in[d];
4428:   } else {
4429:     for (d = 0; d < dim; ++d) {
4430:       if (PetscAbsScalar(anchor[d] - in[d]) > dm->maxCell[d]) {
4431:         out[d] += PetscRealPart(anchor[d]) > PetscRealPart(in[d]) ? dm->L[d] + in[d] : in[d] - dm->L[d];
4432:       } else {
4433:         out[d] += in[d];
4434:       }
4435:     }
4436:   }
4437:   return(0);
4438: }

4440: /*@
4441:   DMGetCoordinatesLocalized - Check if the DM coordinates have been localized for cells

4443:   Input Parameter:
4444: . dm - The DM

4446:   Output Parameter:
4447:   areLocalized - True if localized

4449:   Level: developer

4451: .seealso: DMLocalizeCoordinates()
4452: @*/
4453: PetscErrorCode DMGetCoordinatesLocalized(DM dm,PetscBool *areLocalized)
4454: {
4455:   DM             cdm;
4456:   PetscSection   coordSection;
4457:   PetscInt       cStart, cEnd, c, sStart, sEnd, dof;
4458:   PetscBool      alreadyLocalized, alreadyLocalizedGlobal;

4463:   if (!dm->maxCell) {
4464:     *areLocalized = PETSC_FALSE;
4465:     return(0);
4466:   }
4467:   /* We need some generic way of refering to cells/vertices */
4468:   DMGetCoordinateDM(dm, &cdm);
4469:   {
4470:     PetscBool isplex;

4472:     PetscObjectTypeCompare((PetscObject) cdm, DMPLEX, &isplex);
4473:     if (isplex) {
4474:       DMPlexGetHeightStratum(cdm, 0, &cStart, &cEnd);
4475:     } else SETERRQ(PetscObjectComm((PetscObject) cdm), PETSC_ERR_ARG_WRONG, "Coordinate localization requires a DMPLEX coordinate DM");
4476:   }
4477:   DMGetCoordinateSection(dm, &coordSection);
4478:   PetscSectionGetChart(coordSection,&sStart,&sEnd);
4479:   alreadyLocalized = alreadyLocalizedGlobal = PETSC_FALSE;
4480:   for (c = cStart; c < cEnd; ++c) {
4481:     if (c < sStart || c >= sEnd) {
4482:       alreadyLocalized = PETSC_FALSE;
4483:       break;
4484:     }
4485:     PetscSectionGetDof(coordSection, c, &dof);
4486:     if (dof) {
4487:       alreadyLocalized = PETSC_TRUE;
4488:       break;
4489:     }
4490:   }
4491:   MPI_Allreduce(&alreadyLocalized,&alreadyLocalizedGlobal,1,MPIU_BOOL,MPI_LOR,PetscObjectComm((PetscObject)dm));
4492:   *areLocalized = alreadyLocalizedGlobal;
4493:   return(0);
4494: }


4497: /*@
4498:   DMLocalizeCoordinates - If a mesh is periodic, create local coordinates for each cell

4500:   Input Parameter:
4501: . dm - The DM

4503:   Level: developer

4505: .seealso: DMLocalizeCoordinate(), DMLocalizeAddCoordinate()
4506: @*/
4507: PetscErrorCode DMLocalizeCoordinates(DM dm)
4508: {
4509:   DM             cdm;
4510:   PetscSection   coordSection, cSection;
4511:   Vec            coordinates,  cVec;
4512:   PetscScalar   *coords, *coords2, *anchor, *localized;
4513:   PetscInt       Nc, vStart, vEnd, v, sStart, sEnd, newStart = PETSC_MAX_INT, newEnd = PETSC_MIN_INT, dof, d, off, off2, bs, coordSize;
4514:   PetscBool      alreadyLocalized, alreadyLocalizedGlobal;
4515:   PetscInt       maxHeight = 0, h;
4516:   PetscInt       *pStart = NULL, *pEnd = NULL;

4521:   if (!dm->maxCell) return(0);
4522:   /* We need some generic way of refering to cells/vertices */
4523:   DMGetCoordinateDM(dm, &cdm);
4524:   {
4525:     PetscBool isplex;

4527:     PetscObjectTypeCompare((PetscObject) cdm, DMPLEX, &isplex);
4528:     if (isplex) {
4529:       DMPlexGetDepthStratum(cdm, 0, &vStart, &vEnd);
4530:       DMPlexGetMaxProjectionHeight(cdm,&maxHeight);
4531:       DMGetWorkArray(dm,2*(maxHeight + 1),PETSC_INT,&pStart);
4532:       pEnd = &pStart[maxHeight + 1];
4533:       newStart = vStart;
4534:       newEnd   = vEnd;
4535:       for (h = 0; h <= maxHeight; h++) {
4536:         DMPlexGetHeightStratum(cdm, h, &pStart[h], &pEnd[h]);
4537:         newStart = PetscMin(newStart,pStart[h]);
4538:         newEnd   = PetscMax(newEnd,pEnd[h]);
4539:       }
4540:     } else SETERRQ(PetscObjectComm((PetscObject) cdm), PETSC_ERR_ARG_WRONG, "Coordinate localization requires a DMPLEX coordinate DM");
4541:   }
4542:   DMGetCoordinatesLocal(dm, &coordinates);
4543:   DMGetCoordinateSection(dm, &coordSection);
4544:   VecGetBlockSize(coordinates, &bs);
4545:   PetscSectionGetChart(coordSection,&sStart,&sEnd);

4547:   PetscSectionCreate(PetscObjectComm((PetscObject) dm), &cSection);
4548:   PetscSectionSetNumFields(cSection, 1);
4549:   PetscSectionGetFieldComponents(coordSection, 0, &Nc);
4550:   PetscSectionSetFieldComponents(cSection, 0, Nc);
4551:   PetscSectionSetChart(cSection, newStart, newEnd);

4553:   DMGetWorkArray(dm, 2 * bs, PETSC_SCALAR, &anchor);
4554:   localized = &anchor[bs];
4555:   alreadyLocalized = alreadyLocalizedGlobal = PETSC_TRUE;
4556:   for (h = 0; h <= maxHeight; h++) {
4557:     PetscInt cStart = pStart[h], cEnd = pEnd[h], c;

4559:     for (c = cStart; c < cEnd; ++c) {
4560:       PetscScalar *cellCoords = NULL;
4561:       PetscInt     b;

4563:       if (c < sStart || c >= sEnd) alreadyLocalized = PETSC_FALSE;
4564:       DMPlexVecGetClosure(cdm, coordSection, coordinates, c, &dof, &cellCoords);
4565:       for (b = 0; b < bs; ++b) anchor[b] = cellCoords[b];
4566:       for (d = 0; d < dof/bs; ++d) {
4567:         DMLocalizeCoordinate_Internal(dm, bs, anchor, &cellCoords[d*bs], localized);
4568:         for (b = 0; b < bs; b++) {
4569:           if (cellCoords[d*bs + b] != localized[b]) break;
4570:         }
4571:         if (b < bs) break;
4572:       }
4573:       if (d < dof/bs) {
4574:         if (c >= sStart && c < sEnd) {
4575:           PetscInt cdof;

4577:           PetscSectionGetDof(coordSection, c, &cdof);
4578:           if (cdof != dof) alreadyLocalized = PETSC_FALSE;
4579:         }
4580:         PetscSectionSetDof(cSection, c, dof);
4581:         PetscSectionSetFieldDof(cSection, c, 0, dof);
4582:       }
4583:       DMPlexVecRestoreClosure(cdm, coordSection, coordinates, c, &dof, &cellCoords);
4584:     }
4585:   }
4586:   MPI_Allreduce(&alreadyLocalized,&alreadyLocalizedGlobal,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)dm));
4587:   if (alreadyLocalizedGlobal) {
4588:     DMRestoreWorkArray(dm, 2 * bs, PETSC_SCALAR, &anchor);
4589:     PetscSectionDestroy(&cSection);
4590:     DMRestoreWorkArray(dm,2*(maxHeight + 1),PETSC_INT,&pStart);
4591:     return(0);
4592:   }
4593:   for (v = vStart; v < vEnd; ++v) {
4594:     PetscSectionGetDof(coordSection, v, &dof);
4595:     PetscSectionSetDof(cSection,     v,  dof);
4596:     PetscSectionSetFieldDof(cSection, v, 0, dof);
4597:   }
4598:   PetscSectionSetUp(cSection);
4599:   PetscSectionGetStorageSize(cSection, &coordSize);
4600:   VecCreate(PETSC_COMM_SELF, &cVec);
4601:   PetscObjectSetName((PetscObject)cVec,"coordinates");
4602:   VecSetBlockSize(cVec,         bs);
4603:   VecSetSizes(cVec, coordSize, PETSC_DETERMINE);
4604:   VecSetType(cVec, VECSTANDARD);
4605:   VecGetArrayRead(coordinates, (const PetscScalar**)&coords);
4606:   VecGetArray(cVec, &coords2);
4607:   for (v = vStart; v < vEnd; ++v) {
4608:     PetscSectionGetDof(coordSection, v, &dof);
4609:     PetscSectionGetOffset(coordSection, v, &off);
4610:     PetscSectionGetOffset(cSection,     v, &off2);
4611:     for (d = 0; d < dof; ++d) coords2[off2+d] = coords[off+d];
4612:   }
4613:   for (h = 0; h <= maxHeight; h++) {
4614:     PetscInt cStart = pStart[h], cEnd = pEnd[h], c;

4616:     for (c = cStart; c < cEnd; ++c) {
4617:       PetscScalar *cellCoords = NULL;
4618:       PetscInt     b, cdof;

4620:       PetscSectionGetDof(cSection,c,&cdof);
4621:       if (!cdof) continue;
4622:       DMPlexVecGetClosure(cdm, coordSection, coordinates, c, &dof, &cellCoords);
4623:       PetscSectionGetOffset(cSection, c, &off2);
4624:       for (b = 0; b < bs; ++b) anchor[b] = cellCoords[b];
4625:       for (d = 0; d < dof/bs; ++d) {DMLocalizeCoordinate_Internal(dm, bs, anchor, &cellCoords[d*bs], &coords2[off2+d*bs]);}
4626:       DMPlexVecRestoreClosure(cdm, coordSection, coordinates, c, &dof, &cellCoords);
4627:     }
4628:   }
4629:   DMRestoreWorkArray(dm, 2 * bs, PETSC_SCALAR, &anchor);
4630:   DMRestoreWorkArray(dm,2*(maxHeight + 1),PETSC_INT,&pStart);
4631:   VecRestoreArrayRead(coordinates, (const PetscScalar**)&coords);
4632:   VecRestoreArray(cVec, &coords2);
4633:   DMSetCoordinateSection(dm, PETSC_DETERMINE, cSection);
4634:   DMSetCoordinatesLocal(dm, cVec);
4635:   VecDestroy(&cVec);
4636:   PetscSectionDestroy(&cSection);
4637:   return(0);
4638: }

4640: /*@
4641:   DMLocatePoints - Locate the points in v in the mesh and return a PetscSF of the containing cells

4643:   Collective on Vec v (see explanation below)

4645:   Input Parameters:
4646: + dm - The DM
4647: . v - The Vec of points
4648: . ltype - The type of point location, e.g. DM_POINTLOCATION_NONE or DM_POINTLOCATION_NEAREST
4649: - cells - Points to either NULL, or a PetscSF with guesses for which cells contain each point.

4651:   Output Parameter:
4652: + v - The Vec of points, which now contains the nearest mesh points to the given points if DM_POINTLOCATION_NEAREST is used
4653: - cells - The PetscSF containing the ranks and local indices of the containing points.


4656:   Level: developer

4658:   Notes:
4659:   To do a search of the local cells of the mesh, v should have PETSC_COMM_SELF as its communicator.
4660:   To do a search of all the cells in the distributed mesh, v should have the same communicator as dm.

4662:   If *cellSF is NULL on input, a PetscSF will be created.
4663:   If *cellSF is not NULL on input, it should point to an existing PetscSF, whose graph will be used as initial guesses.

4665:   An array that maps each point to its containing cell can be obtained with

4667: $    const PetscSFNode *cells;
4668: $    PetscInt           nFound;
4669: $    const PetscSFNode *found;
4670: $
4671: $    PetscSFGetGraph(cells,NULL,&nFound,&found,&cells);

4673:   Where cells[i].rank is the rank of the cell containing point found[i] (or i if found == NULL), and cells[i].index is
4674:   the index of the cell in its rank's local numbering.

4676: .keywords: point location, mesh
4677: .seealso: DMSetCoordinates(), DMSetCoordinatesLocal(), DMGetCoordinates(), DMGetCoordinatesLocal(), DMPointLocationType
4678: @*/
4679: PetscErrorCode DMLocatePoints(DM dm, Vec v, DMPointLocationType ltype, PetscSF *cellSF)
4680: {

4687:   if (*cellSF) {
4688:     PetscMPIInt result;

4691:     MPI_Comm_compare(PetscObjectComm((PetscObject)v),PetscObjectComm((PetscObject)cellSF),&result);
4692:     if (result != MPI_IDENT && result != MPI_CONGRUENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"cellSF must have a communicator congruent to v's");
4693:   } else {
4694:     PetscSFCreate(PetscObjectComm((PetscObject)v),cellSF);
4695:   }
4696:   PetscLogEventBegin(DM_LocatePoints,dm,0,0,0);
4697:   if (dm->ops->locatepoints) {
4698:     (*dm->ops->locatepoints)(dm,v,ltype,*cellSF);
4699:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Point location not available for this DM");
4700:   PetscLogEventEnd(DM_LocatePoints,dm,0,0,0);
4701:   return(0);
4702: }

4704: /*@
4705:   DMGetOutputDM - Retrieve the DM associated with the layout for output

4707:   Input Parameter:
4708: . dm - The original DM

4710:   Output Parameter:
4711: . odm - The DM which provides the layout for output

4713:   Level: intermediate

4715: .seealso: VecView(), DMGetDefaultGlobalSection()
4716: @*/
4717: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
4718: {
4719:   PetscSection   section;
4720:   PetscBool      hasConstraints, ghasConstraints;

4726:   DMGetDefaultSection(dm, &section);
4727:   PetscSectionHasConstraints(section, &hasConstraints);
4728:   MPI_Allreduce(&hasConstraints, &ghasConstraints, 1, MPIU_BOOL, MPI_LOR, PetscObjectComm((PetscObject) dm));
4729:   if (!ghasConstraints) {
4730:     *odm = dm;
4731:     return(0);
4732:   }
4733:   if (!dm->dmBC) {
4734:     PetscDS      ds;
4735:     PetscSection newSection, gsection;
4736:     PetscSF      sf;

4738:     DMClone(dm, &dm->dmBC);
4739:     DMGetDS(dm, &ds);
4740:     DMSetDS(dm->dmBC, ds);
4741:     PetscSectionClone(section, &newSection);
4742:     DMSetDefaultSection(dm->dmBC, newSection);
4743:     PetscSectionDestroy(&newSection);
4744:     DMGetPointSF(dm->dmBC, &sf);
4745:     PetscSectionCreateGlobalSection(section, sf, PETSC_TRUE, PETSC_FALSE, &gsection);
4746:     DMSetDefaultGlobalSection(dm->dmBC, gsection);
4747:     PetscSectionDestroy(&gsection);
4748:   }
4749:   *odm = dm->dmBC;
4750:   return(0);
4751: }

4753: /*@
4754:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

4756:   Input Parameter:
4757: . dm - The original DM

4759:   Output Parameters:
4760: + num - The output sequence number
4761: - val - The output sequence value

4763:   Level: intermediate

4765:   Note: This is intended for output that should appear in sequence, for instance
4766:   a set of timesteps in an HDF5 file, or a set of realizations of a stochastic system.

4768: .seealso: VecView()
4769: @*/
4770: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
4771: {
4776:   return(0);
4777: }

4779: /*@
4780:   DMSetOutputSequenceNumber - Set the sequence number/value for output

4782:   Input Parameters:
4783: + dm - The original DM
4784: . num - The output sequence number
4785: - val - The output sequence value

4787:   Level: intermediate

4789:   Note: This is intended for output that should appear in sequence, for instance
4790:   a set of timesteps in an HDF5 file, or a set of realizations of a stochastic system.

4792: .seealso: VecView()
4793: @*/
4794: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
4795: {
4798:   dm->outputSequenceNum = num;
4799:   dm->outputSequenceVal = val;
4800:   return(0);
4801: }

4803: /*@C
4804:   DMOutputSequenceLoad - Retrieve the sequence value from a Viewer

4806:   Input Parameters:
4807: + dm   - The original DM
4808: . name - The sequence name
4809: - num  - The output sequence number

4811:   Output Parameter:
4812: . val  - The output sequence value

4814:   Level: intermediate

4816:   Note: This is intended for output that should appear in sequence, for instance
4817:   a set of timesteps in an HDF5 file, or a set of realizations of a stochastic system.

4819: .seealso: DMGetOutputSequenceNumber(), DMSetOutputSequenceNumber(), VecView()
4820: @*/
4821: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char *name, PetscInt num, PetscReal *val)
4822: {
4823:   PetscBool      ishdf5;

4830:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5, &ishdf5);
4831:   if (ishdf5) {
4832: #if defined(PETSC_HAVE_HDF5)
4833:     PetscScalar value;

4835:     DMSequenceLoad_HDF5_Internal(dm, name, num, &value, viewer);
4836:     *val = PetscRealPart(value);
4837: #endif
4838:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
4839:   return(0);
4840: }

4842: /*@
4843:   DMGetUseNatural - Get the flag for creating a mapping to the natural order on distribution

4845:   Not collective

4847:   Input Parameter:
4848: . dm - The DM

4850:   Output Parameter:
4851: . useNatural - The flag to build the mapping to a natural order during distribution

4853:   Level: beginner

4855: .seealso: DMSetUseNatural(), DMCreate()
4856: @*/
4857: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
4858: {
4862:   *useNatural = dm->useNatural;
4863:   return(0);
4864: }

4866: /*@
4867:   DMSetUseNatural - Set the flag for creating a mapping to the natural order on distribution

4869:   Collective on dm

4871:   Input Parameters:
4872: + dm - The DM
4873: - useNatural - The flag to build the mapping to a natural order during distribution

4875:   Level: beginner

4877: .seealso: DMGetUseNatural(), DMCreate()
4878: @*/
4879: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
4880: {
4884:   dm->useNatural = useNatural;
4885:   return(0);
4886: }


4889: /*@C
4890:   DMCreateLabel - Create a label of the given name if it does not already exist

4892:   Not Collective

4894:   Input Parameters:
4895: + dm   - The DM object
4896: - name - The label name

4898:   Level: intermediate

4900: .keywords: mesh
4901: .seealso: DMLabelCreate(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
4902: @*/
4903: PetscErrorCode DMCreateLabel(DM dm, const char name[])
4904: {
4905:   DMLabelLink    next  = dm->labels->next;
4906:   PetscBool      flg   = PETSC_FALSE;

4912:   while (next) {
4913:     PetscStrcmp(name, next->label->name, &flg);
4914:     if (flg) break;
4915:     next = next->next;
4916:   }
4917:   if (!flg) {
4918:     DMLabelLink tmpLabel;

4920:     PetscCalloc1(1, &tmpLabel);
4921:     DMLabelCreate(name, &tmpLabel->label);
4922:     tmpLabel->output = PETSC_TRUE;
4923:     tmpLabel->next   = dm->labels->next;
4924:     dm->labels->next = tmpLabel;
4925:   }
4926:   return(0);
4927: }

4929: /*@C
4930:   DMGetLabelValue - Get the value in a Sieve Label for the given point, with 0 as the default

4932:   Not Collective

4934:   Input Parameters:
4935: + dm   - The DM object
4936: . name - The label name
4937: - point - The mesh point

4939:   Output Parameter:
4940: . value - The label value for this point, or -1 if the point is not in the label

4942:   Level: beginner

4944: .keywords: mesh
4945: .seealso: DMLabelGetValue(), DMSetLabelValue(), DMGetStratumIS()
4946: @*/
4947: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
4948: {
4949:   DMLabel        label;

4955:   DMGetLabel(dm, name, &label);
4956:   if (!label) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
4957:   DMLabelGetValue(label, point, value);
4958:   return(0);
4959: }

4961: /*@C
4962:   DMSetLabelValue - Add a point to a Sieve Label with given value

4964:   Not Collective

4966:   Input Parameters:
4967: + dm   - The DM object
4968: . name - The label name
4969: . point - The mesh point
4970: - value - The label value for this point

4972:   Output Parameter:

4974:   Level: beginner

4976: .keywords: mesh
4977: .seealso: DMLabelSetValue(), DMGetStratumIS(), DMClearLabelValue()
4978: @*/
4979: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
4980: {
4981:   DMLabel        label;

4987:   DMGetLabel(dm, name, &label);
4988:   if (!label) {
4989:     DMCreateLabel(dm, name);
4990:     DMGetLabel(dm, name, &label);
4991:   }
4992:   DMLabelSetValue(label, point, value);
4993:   return(0);
4994: }

4996: /*@C
4997:   DMClearLabelValue - Remove a point from a Sieve Label with given value

4999:   Not Collective

5001:   Input Parameters:
5002: + dm   - The DM object
5003: . name - The label name
5004: . point - The mesh point
5005: - value - The label value for this point

5007:   Output Parameter:

5009:   Level: beginner

5011: .keywords: mesh
5012: .seealso: DMLabelClearValue(), DMSetLabelValue(), DMGetStratumIS()
5013: @*/
5014: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
5015: {
5016:   DMLabel        label;

5022:   DMGetLabel(dm, name, &label);
5023:   if (!label) return(0);
5024:   DMLabelClearValue(label, point, value);
5025:   return(0);
5026: }

5028: /*@C
5029:   DMGetLabelSize - Get the number of different integer ids in a Label

5031:   Not Collective

5033:   Input Parameters:
5034: + dm   - The DM object
5035: - name - The label name

5037:   Output Parameter:
5038: . size - The number of different integer ids, or 0 if the label does not exist

5040:   Level: beginner

5042: .keywords: mesh
5043: .seealso: DMLabeGetNumValues(), DMSetLabelValue()
5044: @*/
5045: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
5046: {
5047:   DMLabel        label;

5054:   DMGetLabel(dm, name, &label);
5055:   *size = 0;
5056:   if (!label) return(0);
5057:   DMLabelGetNumValues(label, size);
5058:   return(0);
5059: }

5061: /*@C
5062:   DMGetLabelIdIS - Get the integer ids in a label

5064:   Not Collective

5066:   Input Parameters:
5067: + mesh - The DM object
5068: - name - The label name

5070:   Output Parameter:
5071: . ids - The integer ids, or NULL if the label does not exist

5073:   Level: beginner

5075: .keywords: mesh
5076: .seealso: DMLabelGetValueIS(), DMGetLabelSize()
5077: @*/
5078: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
5079: {
5080:   DMLabel        label;

5087:   DMGetLabel(dm, name, &label);
5088:   *ids = NULL;
5089:   if (!label) return(0);
5090:   DMLabelGetValueIS(label, ids);
5091:   return(0);
5092: }

5094: /*@C
5095:   DMGetStratumSize - Get the number of points in a label stratum

5097:   Not Collective

5099:   Input Parameters:
5100: + dm - The DM object
5101: . name - The label name
5102: - value - The stratum value

5104:   Output Parameter:
5105: . size - The stratum size

5107:   Level: beginner

5109: .keywords: mesh
5110: .seealso: DMLabelGetStratumSize(), DMGetLabelSize(), DMGetLabelIds()
5111: @*/
5112: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
5113: {
5114:   DMLabel        label;

5121:   DMGetLabel(dm, name, &label);
5122:   *size = 0;
5123:   if (!label) return(0);
5124:   DMLabelGetStratumSize(label, value, size);
5125:   return(0);
5126: }

5128: /*@C
5129:   DMGetStratumIS - Get the points in a label stratum

5131:   Not Collective

5133:   Input Parameters:
5134: + dm - The DM object
5135: . name - The label name
5136: - value - The stratum value

5138:   Output Parameter:
5139: . points - The stratum points, or NULL if the label does not exist or does not have that value

5141:   Level: beginner

5143: .keywords: mesh
5144: .seealso: DMLabelGetStratumIS(), DMGetStratumSize()
5145: @*/
5146: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
5147: {
5148:   DMLabel        label;

5155:   DMGetLabel(dm, name, &label);
5156:   *points = NULL;
5157:   if (!label) return(0);
5158:   DMLabelGetStratumIS(label, value, points);
5159:   return(0);
5160: }

5162: /*@C
5163:   DMGetStratumIS - Set the points in a label stratum

5165:   Not Collective

5167:   Input Parameters:
5168: + dm - The DM object
5169: . name - The label name
5170: . value - The stratum value
5171: - points - The stratum points

5173:   Level: beginner

5175: .keywords: mesh
5176: .seealso: DMLabelSetStratumIS(), DMGetStratumSize()
5177: @*/
5178: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
5179: {
5180:   DMLabel        label;

5187:   DMGetLabel(dm, name, &label);
5188:   if (!label) return(0);
5189:   DMLabelSetStratumIS(label, value, points);
5190:   return(0);
5191: }

5193: /*@C
5194:   DMClearLabelStratum - Remove all points from a stratum from a Sieve Label

5196:   Not Collective

5198:   Input Parameters:
5199: + dm   - The DM object
5200: . name - The label name
5201: - value - The label value for this point

5203:   Output Parameter:

5205:   Level: beginner

5207: .keywords: mesh
5208: .seealso: DMLabelClearStratum(), DMSetLabelValue(), DMGetStratumIS(), DMClearLabelValue()
5209: @*/
5210: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
5211: {
5212:   DMLabel        label;

5218:   DMGetLabel(dm, name, &label);
5219:   if (!label) return(0);
5220:   DMLabelClearStratum(label, value);
5221:   return(0);
5222: }

5224: /*@
5225:   DMGetNumLabels - Return the number of labels defined by the mesh

5227:   Not Collective

5229:   Input Parameter:
5230: . dm   - The DM object

5232:   Output Parameter:
5233: . numLabels - the number of Labels

5235:   Level: intermediate

5237: .keywords: mesh
5238: .seealso: DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5239: @*/
5240: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
5241: {
5242:   DMLabelLink next = dm->labels->next;
5243:   PetscInt  n    = 0;

5248:   while (next) {++n; next = next->next;}
5249:   *numLabels = n;
5250:   return(0);
5251: }

5253: /*@C
5254:   DMGetLabelName - Return the name of nth label

5256:   Not Collective

5258:   Input Parameters:
5259: + dm - The DM object
5260: - n  - the label number

5262:   Output Parameter:
5263: . name - the label name

5265:   Level: intermediate

5267: .keywords: mesh
5268: .seealso: DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5269: @*/
5270: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char **name)
5271: {
5272:   DMLabelLink next = dm->labels->next;
5273:   PetscInt  l    = 0;

5278:   while (next) {
5279:     if (l == n) {
5280:       *name = next->label->name;
5281:       return(0);
5282:     }
5283:     ++l;
5284:     next = next->next;
5285:   }
5286:   SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %D does not exist in this DM", n);
5287: }

5289: /*@C
5290:   DMHasLabel - Determine whether the mesh has a label of a given name

5292:   Not Collective

5294:   Input Parameters:
5295: + dm   - The DM object
5296: - name - The label name

5298:   Output Parameter:
5299: . hasLabel - PETSC_TRUE if the label is present

5301:   Level: intermediate

5303: .keywords: mesh
5304: .seealso: DMCreateLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5305: @*/
5306: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
5307: {
5308:   DMLabelLink    next = dm->labels->next;

5315:   *hasLabel = PETSC_FALSE;
5316:   while (next) {
5317:     PetscStrcmp(name, next->label->name, hasLabel);
5318:     if (*hasLabel) break;
5319:     next = next->next;
5320:   }
5321:   return(0);
5322: }

5324: /*@C
5325:   DMGetLabel - Return the label of a given name, or NULL

5327:   Not Collective

5329:   Input Parameters:
5330: + dm   - The DM object
5331: - name - The label name

5333:   Output Parameter:
5334: . label - The DMLabel, or NULL if the label is absent

5336:   Level: intermediate

5338: .keywords: mesh
5339: .seealso: DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5340: @*/
5341: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
5342: {
5343:   DMLabelLink    next = dm->labels->next;
5344:   PetscBool      hasLabel;

5351:   *label = NULL;
5352:   while (next) {
5353:     PetscStrcmp(name, next->label->name, &hasLabel);
5354:     if (hasLabel) {
5355:       *label = next->label;
5356:       break;
5357:     }
5358:     next = next->next;
5359:   }
5360:   return(0);
5361: }

5363: /*@C
5364:   DMGetLabelByNum - Return the nth label

5366:   Not Collective

5368:   Input Parameters:
5369: + dm - The DM object
5370: - n  - the label number

5372:   Output Parameter:
5373: . label - the label

5375:   Level: intermediate

5377: .keywords: mesh
5378: .seealso: DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5379: @*/
5380: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
5381: {
5382:   DMLabelLink next = dm->labels->next;
5383:   PetscInt    l    = 0;

5388:   while (next) {
5389:     if (l == n) {
5390:       *label = next->label;
5391:       return(0);
5392:     }
5393:     ++l;
5394:     next = next->next;
5395:   }
5396:   SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %D does not exist in this DM", n);
5397: }

5399: /*@C
5400:   DMAddLabel - Add the label to this mesh

5402:   Not Collective

5404:   Input Parameters:
5405: + dm   - The DM object
5406: - label - The DMLabel

5408:   Level: developer

5410: .keywords: mesh
5411: .seealso: DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5412: @*/
5413: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
5414: {
5415:   DMLabelLink    tmpLabel;
5416:   PetscBool      hasLabel;

5421:   DMHasLabel(dm, label->name, &hasLabel);
5422:   if (hasLabel) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", label->name);
5423:   PetscCalloc1(1, &tmpLabel);
5424:   tmpLabel->label  = label;
5425:   tmpLabel->output = PETSC_TRUE;
5426:   tmpLabel->next   = dm->labels->next;
5427:   dm->labels->next = tmpLabel;
5428:   return(0);
5429: }

5431: /*@C
5432:   DMRemoveLabel - Remove the label from this mesh

5434:   Not Collective

5436:   Input Parameters:
5437: + dm   - The DM object
5438: - name - The label name

5440:   Output Parameter:
5441: . label - The DMLabel, or NULL if the label is absent

5443:   Level: developer

5445: .keywords: mesh
5446: .seealso: DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5447: @*/
5448: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
5449: {
5450:   DMLabelLink    next = dm->labels->next;
5451:   DMLabelLink    last = NULL;
5452:   PetscBool      hasLabel;

5457:   DMHasLabel(dm, name, &hasLabel);
5458:   *label = NULL;
5459:   if (!hasLabel) return(0);
5460:   while (next) {
5461:     PetscStrcmp(name, next->label->name, &hasLabel);
5462:     if (hasLabel) {
5463:       if (last) last->next       = next->next;
5464:       else      dm->labels->next = next->next;
5465:       next->next = NULL;
5466:       *label     = next->label;
5467:       PetscStrcmp(name, "depth", &hasLabel);
5468:       if (hasLabel) {
5469:         dm->depthLabel = NULL;
5470:       }
5471:       PetscFree(next);
5472:       break;
5473:     }
5474:     last = next;
5475:     next = next->next;
5476:   }
5477:   return(0);
5478: }

5480: /*@C
5481:   DMGetLabelOutput - Get the output flag for a given label

5483:   Not Collective

5485:   Input Parameters:
5486: + dm   - The DM object
5487: - name - The label name

5489:   Output Parameter:
5490: . output - The flag for output

5492:   Level: developer

5494: .keywords: mesh
5495: .seealso: DMSetLabelOutput(), DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5496: @*/
5497: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
5498: {
5499:   DMLabelLink    next = dm->labels->next;

5506:   while (next) {
5507:     PetscBool flg;

5509:     PetscStrcmp(name, next->label->name, &flg);
5510:     if (flg) {*output = next->output; return(0);}
5511:     next = next->next;
5512:   }
5513:   SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
5514: }

5516: /*@C
5517:   DMSetLabelOutput - Set the output flag for a given label

5519:   Not Collective

5521:   Input Parameters:
5522: + dm     - The DM object
5523: . name   - The label name
5524: - output - The flag for output

5526:   Level: developer

5528: .keywords: mesh
5529: .seealso: DMGetLabelOutput(), DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5530: @*/
5531: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
5532: {
5533:   DMLabelLink    next = dm->labels->next;

5539:   while (next) {
5540:     PetscBool flg;

5542:     PetscStrcmp(name, next->label->name, &flg);
5543:     if (flg) {next->output = output; return(0);}
5544:     next = next->next;
5545:   }
5546:   SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
5547: }


5550: /*@
5551:   DMCopyLabels - Copy labels from one mesh to another with a superset of the points

5553:   Collective on DM

5555:   Input Parameter:
5556: . dmA - The DM object with initial labels

5558:   Output Parameter:
5559: . dmB - The DM object with copied labels

5561:   Level: intermediate

5563:   Note: This is typically used when interpolating or otherwise adding to a mesh

5565: .keywords: mesh
5566: .seealso: DMCopyCoordinates(), DMGetCoordinates(), DMGetCoordinatesLocal(), DMGetCoordinateDM(), DMGetCoordinateSection()
5567: @*/
5568: PetscErrorCode DMCopyLabels(DM dmA, DM dmB)
5569: {
5570:   PetscInt       numLabels, l;

5574:   if (dmA == dmB) return(0);
5575:   DMGetNumLabels(dmA, &numLabels);
5576:   for (l = 0; l < numLabels; ++l) {
5577:     DMLabel     label, labelNew;
5578:     const char *name;
5579:     PetscBool   flg;

5581:     DMGetLabelName(dmA, l, &name);
5582:     PetscStrcmp(name, "depth", &flg);
5583:     if (flg) continue;
5584:     DMGetLabel(dmA, name, &label);
5585:     DMLabelDuplicate(label, &labelNew);
5586:     DMAddLabel(dmB, labelNew);
5587:   }
5588:   return(0);
5589: }

5591: /*@
5592:   DMGetCoarseDM - Get the coarse mesh from which this was obtained by refinement

5594:   Input Parameter:
5595: . dm - The DM object

5597:   Output Parameter:
5598: . cdm - The coarse DM

5600:   Level: intermediate

5602: .seealso: DMSetCoarseDM()
5603: @*/
5604: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
5605: {
5609:   *cdm = dm->coarseMesh;
5610:   return(0);
5611: }

5613: /*@
5614:   DMSetCoarseDM - Set the coarse mesh from which this was obtained by refinement

5616:   Input Parameters:
5617: + dm - The DM object
5618: - cdm - The coarse DM

5620:   Level: intermediate

5622: .seealso: DMGetCoarseDM()
5623: @*/
5624: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
5625: {

5631:   PetscObjectReference((PetscObject)cdm);
5632:   DMDestroy(&dm->coarseMesh);
5633:   dm->coarseMesh = cdm;
5634:   return(0);
5635: }

5637: /*@
5638:   DMGetFineDM - Get the fine mesh from which this was obtained by refinement

5640:   Input Parameter:
5641: . dm - The DM object

5643:   Output Parameter:
5644: . fdm - The fine DM

5646:   Level: intermediate

5648: .seealso: DMSetFineDM()
5649: @*/
5650: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
5651: {
5655:   *fdm = dm->fineMesh;
5656:   return(0);
5657: }

5659: /*@
5660:   DMSetFineDM - Set the fine mesh from which this was obtained by refinement

5662:   Input Parameters:
5663: + dm - The DM object
5664: - fdm - The fine DM

5666:   Level: intermediate

5668: .seealso: DMGetFineDM()
5669: @*/
5670: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
5671: {

5677:   PetscObjectReference((PetscObject)fdm);
5678:   DMDestroy(&dm->fineMesh);
5679:   dm->fineMesh = fdm;
5680:   return(0);
5681: }

5683: /*=== DMBoundary code ===*/

5685: PetscErrorCode DMCopyBoundary(DM dm, DM dmNew)
5686: {

5690:   PetscDSCopyBoundary(dm->prob,dmNew->prob);
5691:   return(0);
5692: }

5694: /*@C
5695:   DMAddBoundary - Add a boundary condition to the model

5697:   Input Parameters:
5698: + dm          - The DM, with a PetscDS that matches the problem being constrained
5699: . type        - The type of condition, e.g. DM_BC_ESSENTIAL_ANALYTIC/DM_BC_ESSENTIAL_FIELD (Dirichlet), or DM_BC_NATURAL (Neumann)
5700: . name        - The BC name
5701: . labelname   - The label defining constrained points
5702: . field       - The field to constrain
5703: . numcomps    - The number of constrained field components
5704: . comps       - An array of constrained component numbers
5705: . bcFunc      - A pointwise function giving boundary values
5706: . numids      - The number of DMLabel ids for constrained points
5707: . ids         - An array of ids for constrained points
5708: - ctx         - An optional user context for bcFunc

5710:   Options Database Keys:
5711: + -bc_<boundary name> <num> - Overrides the boundary ids
5712: - -bc_<boundary name>_comp <num> - Overrides the boundary components

5714:   Level: developer

5716: .seealso: DMGetBoundary()
5717: @*/
5718: PetscErrorCode DMAddBoundary(DM dm, DMBoundaryConditionType type, const char name[], const char labelname[], PetscInt field, PetscInt numcomps, const PetscInt *comps, void (*bcFunc)(void), PetscInt numids, const PetscInt *ids, void *ctx)
5719: {

5724:   PetscDSAddBoundary(dm->prob,type,name,labelname,field,numcomps,comps,bcFunc,numids,ids,ctx);
5725:   return(0);
5726: }

5728: /*@
5729:   DMGetNumBoundary - Get the number of registered BC

5731:   Input Parameters:
5732: . dm - The mesh object

5734:   Output Parameters:
5735: . numBd - The number of BC

5737:   Level: intermediate

5739: .seealso: DMAddBoundary(), DMGetBoundary()
5740: @*/
5741: PetscErrorCode DMGetNumBoundary(DM dm, PetscInt *numBd)
5742: {

5747:   PetscDSGetNumBoundary(dm->prob,numBd);
5748:   return(0);
5749: }

5751: /*@C
5752:   DMGetBoundary - Add a boundary condition to the model

5754:   Input Parameters:
5755: + dm          - The mesh object
5756: - bd          - The BC number

5758:   Output Parameters:
5759: + type        - The type of condition, e.g. DM_BC_ESSENTIAL_ANALYTIC/DM_BC_ESSENTIAL_FIELD (Dirichlet), or DM_BC_NATURAL (Neumann)
5760: . name        - The BC name
5761: . labelname   - The label defining constrained points
5762: . field       - The field to constrain
5763: . numcomps    - The number of constrained field components
5764: . comps       - An array of constrained component numbers
5765: . bcFunc      - A pointwise function giving boundary values
5766: . numids      - The number of DMLabel ids for constrained points
5767: . ids         - An array of ids for constrained points
5768: - ctx         - An optional user context for bcFunc

5770:   Options Database Keys:
5771: + -bc_<boundary name> <num> - Overrides the boundary ids
5772: - -bc_<boundary name>_comp <num> - Overrides the boundary components

5774:   Level: developer

5776: .seealso: DMAddBoundary()
5777: @*/
5778: PetscErrorCode DMGetBoundary(DM dm, PetscInt bd, DMBoundaryConditionType *type, const char **name, const char **labelname, PetscInt *field, PetscInt *numcomps, const PetscInt **comps, void (**func)(void), PetscInt *numids, const PetscInt **ids, void **ctx)
5779: {

5784:   PetscDSGetBoundary(dm->prob,bd,type,name,labelname,field,numcomps,comps,func,numids,ids,ctx);
5785:   return(0);
5786: }

5788: static PetscErrorCode DMPopulateBoundary(DM dm)
5789: {
5790:   DMBoundary *lastnext;
5791:   DSBoundary dsbound;

5795:   dsbound = dm->prob->boundary;
5796:   if (dm->boundary) {
5797:     DMBoundary next = dm->boundary;

5799:     /* quick check to see if the PetscDS has changed */
5800:     if (next->dsboundary == dsbound) return(0);
5801:     /* the PetscDS has changed: tear down and rebuild */
5802:     while (next) {
5803:       DMBoundary b = next;

5805:       next = b->next;
5806:       PetscFree(b);
5807:     }
5808:     dm->boundary = NULL;
5809:   }

5811:   lastnext = &(dm->boundary);
5812:   while (dsbound) {
5813:     DMBoundary dmbound;

5815:     PetscNew(&dmbound);
5816:     dmbound->dsboundary = dsbound;
5817:     DMGetLabel(dm, dsbound->labelname, &(dmbound->label));
5818:     if (!dmbound->label) PetscInfo2(dm, "DSBoundary %s wants label %s, which is not in this dm.\n",dsbound->name,dsbound->labelname);
5819:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
5820:     *lastnext = dmbound;
5821:     lastnext = &(dmbound->next);
5822:     dsbound = dsbound->next;
5823:   }
5824:   return(0);
5825: }

5827: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
5828: {
5829:   DMBoundary     b;

5835:   *isBd = PETSC_FALSE;
5836:   DMPopulateBoundary(dm);
5837:   b = dm->boundary;
5838:   while (b && !(*isBd)) {
5839:     DMLabel    label = b->label;
5840:     DSBoundary dsb = b->dsboundary;

5842:     if (label) {
5843:       PetscInt i;

5845:       for (i = 0; i < dsb->numids && !(*isBd); ++i) {
5846:         DMLabelStratumHasPoint(label, dsb->ids[i], point, isBd);
5847:       }
5848:     }
5849:     b = b->next;
5850:   }
5851:   return(0);
5852: }

5854: /*@C
5855:   DMProjectFunction - This projects the given function into the function space provided.

5857:   Input Parameters:
5858: + dm      - The DM
5859: . time    - The time
5860: . funcs   - The coordinate functions to evaluate, one per field
5861: . ctxs    - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
5862: - mode    - The insertion mode for values

5864:   Output Parameter:
5865: . X - vector

5867:    Calling sequence of func:
5868: $    func(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar u[], void *ctx);

5870: +  dim - The spatial dimension
5871: .  x   - The coordinates
5872: .  Nf  - The number of fields
5873: .  u   - The output field values
5874: -  ctx - optional user-defined function context

5876:   Level: developer

5878: .seealso: DMComputeL2Diff()
5879: @*/
5880: PetscErrorCode DMProjectFunction(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec X)
5881: {
5882:   Vec            localX;

5887:   DMGetLocalVector(dm, &localX);
5888:   DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX);
5889:   DMLocalToGlobalBegin(dm, localX, mode, X);
5890:   DMLocalToGlobalEnd(dm, localX, mode, X);
5891:   DMRestoreLocalVector(dm, &localX);
5892:   return(0);
5893: }

5895: PetscErrorCode DMProjectFunctionLocal(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec localX)
5896: {

5902:   if (!dm->ops->projectfunctionlocal) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMProjectFunctionLocal",((PetscObject)dm)->type_name);
5903:   (dm->ops->projectfunctionlocal) (dm, time, funcs, ctxs, mode, localX);
5904:   return(0);
5905: }

5907: PetscErrorCode DMProjectFunctionLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec localX)
5908: {

5914:   if (!dm->ops->projectfunctionlabellocal) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMProjectFunctionLabelLocal",((PetscObject)dm)->type_name);
5915:   (dm->ops->projectfunctionlabellocal) (dm, time, label, numIds, ids, funcs, ctxs, mode, localX);
5916:   return(0);
5917: }

5919: PetscErrorCode DMProjectFieldLocal(DM dm, PetscReal time, Vec localU,
5920:                                    void (**funcs)(PetscInt, PetscInt, PetscInt,
5921:                                                   const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[],
5922:                                                   const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[],
5923:                                                   PetscReal, const PetscReal[], PetscScalar[]),
5924:                                    InsertMode mode, Vec localX)
5925: {

5932:   if (!dm->ops->projectfieldlocal) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMProjectFieldLocal",((PetscObject)dm)->type_name);
5933:   (dm->ops->projectfieldlocal) (dm, time, localU, funcs, mode, localX);
5934:   return(0);
5935: }

5937: PetscErrorCode DMProjectFieldLabelLocal(DM dm, PetscReal time, DMLabel label, PetscInt numIds, const PetscInt ids[], Vec localU,
5938:                                         void (**funcs)(PetscInt, PetscInt, PetscInt,
5939:                                                        const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[],
5940:                                                        const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[],
5941:                                                        PetscReal, const PetscReal[], PetscScalar[]),
5942:                                         InsertMode mode, Vec localX)
5943: {

5950:   if (!dm->ops->projectfieldlabellocal) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMProjectFieldLocal",((PetscObject)dm)->type_name);
5951:   (dm->ops->projectfieldlabellocal)(dm, time, label, numIds, ids, localU, funcs, mode, localX);
5952:   return(0);
5953: }

5955: /*@C
5956:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

5958:   Input Parameters:
5959: + dm    - The DM
5960: . time  - The time
5961: . funcs - The functions to evaluate for each field component
5962: . ctxs  - Optional array of contexts to pass to each function, or NULL.
5963: - X     - The coefficient vector u_h

5965:   Output Parameter:
5966: . diff - The diff ||u - u_h||_2

5968:   Level: developer

5970: .seealso: DMProjectFunction(), DMComputeL2FieldDiff(), DMComputeL2GradientDiff()
5971: @*/
5972: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
5973: {

5979:   if (!dm->ops->computel2diff) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMComputeL2Diff",((PetscObject)dm)->type_name);
5980:   (dm->ops->computel2diff)(dm,time,funcs,ctxs,X,diff);
5981:   return(0);
5982: }

5984: /*@C
5985:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

5987:   Input Parameters:
5988: + dm    - The DM
5989: , time  - The time
5990: . funcs - The gradient functions to evaluate for each field component
5991: . ctxs  - Optional array of contexts to pass to each function, or NULL.
5992: . X     - The coefficient vector u_h
5993: - n     - The vector to project along

5995:   Output Parameter:
5996: . diff - The diff ||(grad u - grad u_h) . n||_2

5998:   Level: developer

6000: .seealso: DMProjectFunction(), DMComputeL2Diff()
6001: @*/
6002: PetscErrorCode DMComputeL2GradientDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], const PetscReal[], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, const PetscReal n[], PetscReal *diff)
6003: {

6009:   if (!dm->ops->computel2gradientdiff) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implement DMComputeL2GradientDiff",((PetscObject)dm)->type_name);
6010:   (dm->ops->computel2gradientdiff)(dm,time,funcs,ctxs,X,n,diff);
6011:   return(0);
6012: }

6014: /*@C
6015:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

6017:   Input Parameters:
6018: + dm    - The DM
6019: . time  - The time
6020: . funcs - The functions to evaluate for each field component
6021: . ctxs  - Optional array of contexts to pass to each function, or NULL.
6022: - X     - The coefficient vector u_h

6024:   Output Parameter:
6025: . diff - The array of differences, ||u^f - u^f_h||_2

6027:   Level: developer

6029: .seealso: DMProjectFunction(), DMComputeL2FieldDiff(), DMComputeL2GradientDiff()
6030: @*/
6031: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
6032: {

6038:   if (!dm->ops->computel2fielddiff) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMComputeL2FieldDiff",((PetscObject)dm)->type_name);
6039:   (dm->ops->computel2fielddiff)(dm,time,funcs,ctxs,X,diff);
6040:   return(0);
6041: }

6043: /*@C
6044:   DMAdaptLabel - Adapt a dm based on a label with values interpreted as coarsening and refining flags.  Specific implementations of DM maybe have
6045:                  specialized flags, but all implementations should accept flag values DM_ADAPT_DETERMINE, DM_ADAPT_KEEP, DM_ADAPT_REFINE, and DM_ADAPT_COARSEN.

6047:   Collective on dm

6049:   Input parameters:
6050: + dm - the pre-adaptation DM object
6051: - label - label with the flags

6053:   Output parameters:
6054: . adaptedDM - the adapted DM object: may be NULL if an adapted DM could not be produced.

6056:   Level: intermediate
6057: @*/
6058: PetscErrorCode DMAdaptLabel(DM dm, DMLabel label, DM *adaptedDM)
6059: {

6066:   *adaptedDM = NULL;
6067:   PetscTryMethod((PetscObject)dm,"DMAdaptLabel_C",(DM,DMLabel, DM*),(dm,label,adaptedDM));
6068:   return(0);
6069: }

6071: /*@C
6072:  DMGetNeighbors - Gets an array containing the MPI rank of all the processes neighbors

6074:  Not Collective

6076:  Input Parameter:
6077:  . dm    - The DM

6079:  Output Parameter:
6080:  . nranks - the number of neighbours
6081:  . ranks - the neighbors ranks

6083:  Notes:
6084:  Do not free the array, it is freed when the DM is destroyed.

6086:  Level: beginner

6088:  .seealso: DMDAGetNeighbors(), PetscSFGetRanks()
6089: @*/
6090: PetscErrorCode DMGetNeighbors(DM dm,PetscInt *nranks,const PetscMPIInt *ranks[])
6091: {

6096:   if (!dm->ops->getneighbors) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMGetNeighbors",((PetscObject)dm)->type_name);
6097:   (dm->ops->getneighbors)(dm,nranks,ranks);
6098:   return(0);
6099: }

6101: #include <petsc/private/matimpl.h> /* Needed because of coloring->ctype below */

6103: /*
6104:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
6105:     This has be a different function because it requires DM which is not defined in the Mat library
6106: */
6107: PetscErrorCode  MatFDColoringApply_AIJDM(Mat J,MatFDColoring coloring,Vec x1,void *sctx)
6108: {

6112:   if (coloring->ctype == IS_COLORING_LOCAL) {
6113:     Vec x1local;
6114:     DM  dm;
6115:     MatGetDM(J,&dm);
6116:     if (!dm) SETERRQ(PetscObjectComm((PetscObject)J),PETSC_ERR_ARG_INCOMP,"IS_COLORING_LOCAL requires a DM");
6117:     DMGetLocalVector(dm,&x1local);
6118:     DMGlobalToLocalBegin(dm,x1,INSERT_VALUES,x1local);
6119:     DMGlobalToLocalEnd(dm,x1,INSERT_VALUES,x1local);
6120:     x1   = x1local;
6121:   }
6122:   MatFDColoringApply_AIJ(J,coloring,x1,sctx);
6123:   if (coloring->ctype == IS_COLORING_LOCAL) {
6124:     DM  dm;
6125:     MatGetDM(J,&dm);
6126:     DMRestoreLocalVector(dm,&x1);
6127:   }
6128:   return(0);
6129: }

6131: /*@
6132:     MatFDColoringUseDM - allows a MatFDColoring object to use the DM associated with the matrix to use a IS_COLORING_LOCAL coloring

6134:     Input Parameter:
6135: .    coloring - the MatFDColoring object

6137:     Developer Notes: this routine exists because the PETSc Mat library does not know about the DM objects

6139:     Level: advanced

6141: .seealso: MatFDColoring, MatFDColoringCreate(), ISColoringType
6142: @*/
6143: PetscErrorCode  MatFDColoringUseDM(Mat coloring,MatFDColoring fdcoloring)
6144: {
6146:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
6147:   return(0);
6148: }