Actual source code: dm.c

petsc-master 2016-09-25
Report Typos and Errors
  1: #include <petsc/private/dmimpl.h>           /*I      "petscdm.h"          I*/
 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_CreateInterpolation, DM_CreateRestriction;

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

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

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

 21:   Collective on MPI_Comm

 23:   Input Parameter:
 24: . comm - The communicator for the DM object

 26:   Output Parameter:
 27: . dm - The DM object

 29:   Level: beginner

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

 40:   *dm = NULL;
 41:   PetscSysInitializePackage();
 42:   VecInitializePackage();
 43:   MatInitializePackage();
 44:   DMInitializePackage();

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

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

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

 87:   Collective on MPI_Comm

 89:   Input Parameter:
 90: . dm - The original DM object

 92:   Output Parameter:
 93: . newdm  - The new DM object

 95:   Level: beginner

 97: .keywords: DM, topology, create
 98: @*/
 99: PetscErrorCode DMClone(DM dm, DM *newdm)
100: {
101:   PetscSF        sf;
102:   Vec            coords;
103:   void          *ctx;
104:   PetscInt       dim;

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

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

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

161:    Logically Collective on DM

163:    Input Parameter:
164: +  da - initial distributed array
165: .  ctype - the vector type, currently either VECSTANDARD or VECCUSP

167:    Options Database:
168: .   -dm_vec_type ctype

170:    Level: intermediate

172: .seealso: DMCreate(), DMDestroy(), DM, DMDAInterpolationType, VecType, DMGetVecType()
173: @*/
174: PetscErrorCode  DMSetVecType(DM da,VecType ctype)
175: {

180:   PetscFree(da->vectype);
181:   PetscStrallocpy(ctype,(char**)&da->vectype);
182:   return(0);
183: }

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

190:    Logically Collective on DM

192:    Input Parameter:
193: .  da - initial distributed array

195:    Output Parameter:
196: .  ctype - the vector type

198:    Level: intermediate

200: .seealso: DMCreate(), DMDestroy(), DM, DMDAInterpolationType, VecType
201: @*/
202: PetscErrorCode  DMGetVecType(DM da,VecType *ctype)
203: {
206:   *ctype = da->vectype;
207:   return(0);
208: }

212: /*@
213:   VecGetDM - Gets the DM defining the data layout of the vector

215:   Not collective

217:   Input Parameter:
218: . v - The Vec

220:   Output Parameter:
221: . dm - The DM

223:   Level: intermediate

225: .seealso: VecSetDM(), DMGetLocalVector(), DMGetGlobalVector(), DMSetVecType()
226: @*/
227: PetscErrorCode VecGetDM(Vec v, DM *dm)
228: {

234:   PetscObjectQuery((PetscObject) v, "__PETSc_dm", (PetscObject*) dm);
235:   return(0);
236: }

240: /*@
241:   VecSetDM - Sets the DM defining the data layout of the vector.

243:   Not collective

245:   Input Parameters:
246: + v - The Vec
247: - dm - The DM

249:   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.

251:   Level: intermediate

253: .seealso: VecGetDM(), DMGetLocalVector(), DMGetGlobalVector(), DMSetVecType()
254: @*/
255: PetscErrorCode VecSetDM(Vec v, DM dm)
256: {

262:   PetscObjectCompose((PetscObject) v, "__PETSc_dm", (PetscObject) dm);
263:   return(0);
264: }

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

271:    Logically Collective on DM

273:    Input Parameter:
274: +  dm - the DM context
275: .  ctype - the matrix type

277:    Options Database:
278: .   -dm_mat_type ctype

280:    Level: intermediate

282: .seealso: DMDACreate1d(), DMDACreate2d(), DMDACreate3d(), DMCreateMatrix(), DMSetMatrixPreallocateOnly(), MatType, DMGetMatType()
283: @*/
284: PetscErrorCode  DMSetMatType(DM dm,MatType ctype)
285: {

290:   PetscFree(dm->mattype);
291:   PetscStrallocpy(ctype,(char**)&dm->mattype);
292:   return(0);
293: }

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

300:    Logically Collective on DM

302:    Input Parameter:
303: .  dm - the DM context

305:    Output Parameter:
306: .  ctype - the matrix type

308:    Options Database:
309: .   -dm_mat_type ctype

311:    Level: intermediate

313: .seealso: DMDACreate1d(), DMDACreate2d(), DMDACreate3d(), DMCreateMatrix(), DMSetMatrixPreallocateOnly(), MatType, DMSetMatType()
314: @*/
315: PetscErrorCode  DMGetMatType(DM dm,MatType *ctype)
316: {
319:   *ctype = dm->mattype;
320:   return(0);
321: }

325: /*@
326:   MatGetDM - Gets the DM defining the data layout of the matrix

328:   Not collective

330:   Input Parameter:
331: . A - The Mat

333:   Output Parameter:
334: . dm - The DM

336:   Level: intermediate

338: .seealso: MatSetDM(), DMCreateMatrix(), DMSetMatType()
339: @*/
340: PetscErrorCode MatGetDM(Mat A, DM *dm)
341: {

347:   PetscObjectQuery((PetscObject) A, "__PETSc_dm", (PetscObject*) dm);
348:   return(0);
349: }

353: /*@
354:   MatSetDM - Sets the DM defining the data layout of the matrix

356:   Not collective

358:   Input Parameters:
359: + A - The Mat
360: - dm - The DM

362:   Level: intermediate

364: .seealso: MatGetDM(), DMCreateMatrix(), DMSetMatType()
365: @*/
366: PetscErrorCode MatSetDM(Mat A, DM dm)
367: {

373:   PetscObjectCompose((PetscObject) A, "__PETSc_dm", (PetscObject) dm);
374:   return(0);
375: }

379: /*@C
380:    DMSetOptionsPrefix - Sets the prefix used for searching for all
381:    DM options in the database.

383:    Logically Collective on DM

385:    Input Parameter:
386: +  da - the DM context
387: -  prefix - the prefix to prepend to all option names

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

393:    Level: advanced

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

397: .seealso: DMSetFromOptions()
398: @*/
399: PetscErrorCode  DMSetOptionsPrefix(DM dm,const char prefix[])
400: {

405:   PetscObjectSetOptionsPrefix((PetscObject)dm,prefix);
406:   if (dm->sf) {
407:     PetscObjectSetOptionsPrefix((PetscObject)dm->sf,prefix);
408:   }
409:   if (dm->defaultSF) {
410:     PetscObjectSetOptionsPrefix((PetscObject)dm->defaultSF,prefix);
411:   }
412:   return(0);
413: }

417: /*@C
418:    DMAppendOptionsPrefix - Appends to the prefix used for searching for all
419:    DM options in the database.

421:    Logically Collective on DM

423:    Input Parameters:
424: +  dm - the DM context
425: -  prefix - the prefix string to prepend to all DM option requests

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

431:    Level: advanced

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

435: .seealso: DMSetOptionsPrefix(), DMGetOptionsPrefix()
436: @*/
437: PetscErrorCode  DMAppendOptionsPrefix(DM dm,const char prefix[])
438: {

443:   PetscObjectAppendOptionsPrefix((PetscObject)dm,prefix);
444:   return(0);
445: }

449: /*@C
450:    DMGetOptionsPrefix - Gets the prefix used for searching for all
451:    DM options in the database.

453:    Not Collective

455:    Input Parameters:
456: .  dm - the DM context

458:    Output Parameters:
459: .  prefix - pointer to the prefix string used is returned

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

464:    Level: advanced

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

468: .seealso: DMSetOptionsPrefix(), DMAppendOptionsPrefix()
469: @*/
470: PetscErrorCode  DMGetOptionsPrefix(DM dm,const char *prefix[])
471: {

476:   PetscObjectGetOptionsPrefix((PetscObject)dm,prefix);
477:   return(0);
478: }

482: static PetscErrorCode DMCountNonCyclicReferences(DM dm, PetscBool recurseCoarse, PetscBool recurseFine, PetscInt *ncrefct)
483: {
484:   PetscInt i, refct = ((PetscObject) dm)->refct;
485:   DMNamedVecLink nlink;

489:   /* count all the circular references of DM and its contained Vecs */
490:   for (i=0; i<DM_MAX_WORK_VECTORS; i++) {
491:     if (dm->localin[i])  refct--;
492:     if (dm->globalin[i]) refct--;
493:   }
494:   for (nlink=dm->namedglobal; nlink; nlink=nlink->next) refct--;
495:   for (nlink=dm->namedlocal; nlink; nlink=nlink->next) refct--;
496:   if (dm->x) {
497:     DM obj;
498:     VecGetDM(dm->x, &obj);
499:     if (obj == dm) refct--;
500:   }
501:   if (dm->coarseMesh && dm->coarseMesh->fineMesh == dm) {
502:     refct--;
503:     if (recurseCoarse) {
504:       PetscInt coarseCount;

506:       DMCountNonCyclicReferences(dm->coarseMesh, PETSC_TRUE, PETSC_FALSE,&coarseCount);
507:       refct += coarseCount;
508:     }
509:   }
510:   if (dm->fineMesh && dm->fineMesh->coarseMesh == dm) {
511:     refct--;
512:     if (recurseFine) {
513:       PetscInt fineCount;

515:       DMCountNonCyclicReferences(dm->fineMesh, PETSC_FALSE, PETSC_TRUE,&fineCount);
516:       refct += fineCount;
517:     }
518:   }
519:   *ncrefct = refct;
520:   return(0);
521: }

525: PetscErrorCode DMDestroyLabelLinkList(DM dm)
526: {

530:   if (!--(dm->labels->refct)) {
531:     DMLabelLink next = dm->labels->next;

533:     /* destroy the labels */
534:     while (next) {
535:       DMLabelLink tmp = next->next;

537:       DMLabelDestroy(&next->label);
538:       PetscFree(next);
539:       next = tmp;
540:     }
541:     PetscFree(dm->labels);
542:   }
543:   return(0);
544: }

548: /*@
549:     DMDestroy - Destroys a vector packer or DM.

551:     Collective on DM

553:     Input Parameter:
554: .   dm - the DM object to destroy

556:     Level: developer

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

560: @*/
561: PetscErrorCode  DMDestroy(DM *dm)
562: {
563:   PetscInt       i, cnt;
564:   DMNamedVecLink nlink,nnext;

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

571:   /* count all non-cyclic references in the doubly-linked list of coarse<->fine meshes */
572:   DMCountNonCyclicReferences(*dm,PETSC_TRUE,PETSC_TRUE,&cnt);
573:   --((PetscObject)(*dm))->refct;
574:   if (--cnt > 0) {*dm = 0; return(0);}
575:   /*
576:      Need this test because the dm references the vectors that
577:      reference the dm, so destroying the dm calls destroy on the
578:      vectors that cause another destroy on the dm
579:   */
580:   if (((PetscObject)(*dm))->refct < 0) return(0);
581:   ((PetscObject) (*dm))->refct = 0;
582:   for (i=0; i<DM_MAX_WORK_VECTORS; i++) {
583:     if ((*dm)->localout[i]) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Destroying a DM that has a local vector obtained with DMGetLocalVector()");
584:     VecDestroy(&(*dm)->localin[i]);
585:   }
586:   nnext=(*dm)->namedglobal;
587:   (*dm)->namedglobal = NULL;
588:   for (nlink=nnext; nlink; nlink=nnext) { /* Destroy the named vectors */
589:     nnext = nlink->next;
590:     if (nlink->status != DMVEC_STATUS_IN) SETERRQ1(((PetscObject)*dm)->comm,PETSC_ERR_ARG_WRONGSTATE,"DM still has Vec named '%s' checked out",nlink->name);
591:     PetscFree(nlink->name);
592:     VecDestroy(&nlink->X);
593:     PetscFree(nlink);
594:   }
595:   nnext=(*dm)->namedlocal;
596:   (*dm)->namedlocal = NULL;
597:   for (nlink=nnext; nlink; nlink=nnext) { /* Destroy the named local vectors */
598:     nnext = nlink->next;
599:     if (nlink->status != DMVEC_STATUS_IN) SETERRQ1(((PetscObject)*dm)->comm,PETSC_ERR_ARG_WRONGSTATE,"DM still has Vec named '%s' checked out",nlink->name);
600:     PetscFree(nlink->name);
601:     VecDestroy(&nlink->X);
602:     PetscFree(nlink);
603:   }

605:   /* Destroy the list of hooks */
606:   {
607:     DMCoarsenHookLink link,next;
608:     for (link=(*dm)->coarsenhook; link; link=next) {
609:       next = link->next;
610:       PetscFree(link);
611:     }
612:     (*dm)->coarsenhook = NULL;
613:   }
614:   {
615:     DMRefineHookLink link,next;
616:     for (link=(*dm)->refinehook; link; link=next) {
617:       next = link->next;
618:       PetscFree(link);
619:     }
620:     (*dm)->refinehook = NULL;
621:   }
622:   {
623:     DMSubDomainHookLink link,next;
624:     for (link=(*dm)->subdomainhook; link; link=next) {
625:       next = link->next;
626:       PetscFree(link);
627:     }
628:     (*dm)->subdomainhook = NULL;
629:   }
630:   {
631:     DMGlobalToLocalHookLink link,next;
632:     for (link=(*dm)->gtolhook; link; link=next) {
633:       next = link->next;
634:       PetscFree(link);
635:     }
636:     (*dm)->gtolhook = NULL;
637:   }
638:   {
639:     DMLocalToGlobalHookLink link,next;
640:     for (link=(*dm)->ltoghook; link; link=next) {
641:       next = link->next;
642:       PetscFree(link);
643:     }
644:     (*dm)->ltoghook = NULL;
645:   }
646:   /* Destroy the work arrays */
647:   {
648:     DMWorkLink link,next;
649:     if ((*dm)->workout) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Work array still checked out");
650:     for (link=(*dm)->workin; link; link=next) {
651:       next = link->next;
652:       PetscFree(link->mem);
653:       PetscFree(link);
654:     }
655:     (*dm)->workin = NULL;
656:   }
657:   if (!--((*dm)->labels->refct)) {
658:     DMLabelLink next = (*dm)->labels->next;

660:     /* destroy the labels */
661:     while (next) {
662:       DMLabelLink tmp = next->next;

664:       DMLabelDestroy(&next->label);
665:       PetscFree(next);
666:       next = tmp;
667:     }
668:     PetscFree((*dm)->labels);
669:   }
670:   {
671:     DMBoundary next = (*dm)->boundary;
672:     while (next) {
673:       DMBoundary b = next;

675:       next = b->next;
676:       PetscFree(b);
677:     }
678:   }

680:   PetscObjectDestroy(&(*dm)->dmksp);
681:   PetscObjectDestroy(&(*dm)->dmsnes);
682:   PetscObjectDestroy(&(*dm)->dmts);

684:   if ((*dm)->ctx && (*dm)->ctxdestroy) {
685:     (*(*dm)->ctxdestroy)(&(*dm)->ctx);
686:   }
687:   VecDestroy(&(*dm)->x);
688:   MatFDColoringDestroy(&(*dm)->fd);
689:   DMClearGlobalVectors(*dm);
690:   ISLocalToGlobalMappingDestroy(&(*dm)->ltogmap);
691:   PetscFree((*dm)->vectype);
692:   PetscFree((*dm)->mattype);

694:   PetscSectionDestroy(&(*dm)->defaultSection);
695:   PetscSectionDestroy(&(*dm)->defaultGlobalSection);
696:   PetscLayoutDestroy(&(*dm)->map);
697:   PetscSectionDestroy(&(*dm)->defaultConstraintSection);
698:   MatDestroy(&(*dm)->defaultConstraintMat);
699:   PetscSFDestroy(&(*dm)->sf);
700:   PetscSFDestroy(&(*dm)->defaultSF);
701:   PetscSFDestroy(&(*dm)->sfNatural);

703:   if ((*dm)->coarseMesh && (*dm)->coarseMesh->fineMesh == *dm) {
704:     DMSetFineDM((*dm)->coarseMesh,NULL);
705:   }
706:   DMDestroy(&(*dm)->coarseMesh);
707:   if ((*dm)->fineMesh && (*dm)->fineMesh->coarseMesh == *dm) {
708:     DMSetCoarseDM((*dm)->fineMesh,NULL);
709:   }
710:   DMDestroy(&(*dm)->fineMesh);
711:   DMDestroy(&(*dm)->coordinateDM);
712:   VecDestroy(&(*dm)->coordinates);
713:   VecDestroy(&(*dm)->coordinatesLocal);
714:   PetscFree3((*dm)->L,(*dm)->maxCell,(*dm)->bdtype);

716:   PetscDSDestroy(&(*dm)->prob);
717:   DMDestroy(&(*dm)->dmBC);
718:   /* if memory was published with SAWs then destroy it */
719:   PetscObjectSAWsViewOff((PetscObject)*dm);

721:   (*(*dm)->ops->destroy)(*dm);
722:   /* We do not destroy (*dm)->data here so that we can reference count backend objects */
723:   PetscHeaderDestroy(dm);
724:   return(0);
725: }

729: /*@
730:     DMSetUp - sets up the data structures inside a DM object

732:     Collective on DM

734:     Input Parameter:
735: .   dm - the DM object to setup

737:     Level: developer

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

741: @*/
742: PetscErrorCode  DMSetUp(DM dm)
743: {

748:   if (dm->setupcalled) return(0);
749:   if (dm->ops->setup) {
750:     (*dm->ops->setup)(dm);
751:   }
752:   dm->setupcalled = PETSC_TRUE;
753:   return(0);
754: }

758: /*@
759:     DMSetFromOptions - sets parameters in a DM from the options database

761:     Collective on DM

763:     Input Parameter:
764: .   dm - the DM object to set options for

766:     Options Database:
767: +   -dm_preallocate_only - Only preallocate the matrix for DMCreateMatrix(), but do not fill it with zeros
768: .   -dm_vec_type <type>  - type of vector to create inside DM
769: .   -dm_mat_type <type>  - type of matrix to create inside DM
770: -   -dm_coloring_type    - <global or ghosted>

772:     Level: developer

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

776: @*/
777: PetscErrorCode  DMSetFromOptions(DM dm)
778: {
779:   char           typeName[256];
780:   PetscBool      flg;

785:   if (dm->prob) {
786:     PetscDSSetFromOptions(dm->prob);
787:   }
788:   if (dm->sf) {
789:     PetscSFSetFromOptions(dm->sf);
790:   }
791:   if (dm->defaultSF) {
792:     PetscSFSetFromOptions(dm->defaultSF);
793:   }
794:   PetscObjectOptionsBegin((PetscObject)dm);
795:   PetscOptionsBool("-dm_preallocate_only","only preallocate matrix, but do not set column indices","DMSetMatrixPreallocateOnly",dm->prealloc_only,&dm->prealloc_only,NULL);
796:   PetscOptionsFList("-dm_vec_type","Vector type used for created vectors","DMSetVecType",VecList,dm->vectype,typeName,256,&flg);
797:   if (flg) {
798:     DMSetVecType(dm,typeName);
799:   }
800:   PetscOptionsFList("-dm_mat_type","Matrix type used for created matrices","DMSetMatType",MatList,dm->mattype ? dm->mattype : typeName,typeName,sizeof(typeName),&flg);
801:   if (flg) {
802:     DMSetMatType(dm,typeName);
803:   }
804:   PetscOptionsEnum("-dm_is_coloring_type","Global or local coloring of Jacobian","ISColoringType",ISColoringTypes,(PetscEnum)dm->coloringtype,(PetscEnum*)&dm->coloringtype,NULL);
805:   if (dm->ops->setfromoptions) {
806:     (*dm->ops->setfromoptions)(PetscOptionsObject,dm);
807:   }
808:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
809:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject) dm);
810:   PetscOptionsEnd();
811:   return(0);
812: }

816: /*@C
817:     DMView - Views a DM

819:     Collective on DM

821:     Input Parameter:
822: +   dm - the DM object to view
823: -   v - the viewer

825:     Level: beginner

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

829: @*/
830: PetscErrorCode  DMView(DM dm,PetscViewer v)
831: {
833:   PetscBool      isbinary;

837:   if (!v) {
838:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)dm),&v);
839:   }
840:   PetscObjectPrintClassNamePrefixType((PetscObject)dm,v);
841:   PetscObjectTypeCompare((PetscObject)v,PETSCVIEWERBINARY,&isbinary);
842:   if (isbinary) {
843:     PetscInt classid = DM_FILE_CLASSID;
844:     char     type[256];

846:     PetscViewerBinaryWrite(v,&classid,1,PETSC_INT,PETSC_FALSE);
847:     PetscStrncpy(type,((PetscObject)dm)->type_name,256);
848:     PetscViewerBinaryWrite(v,type,256,PETSC_CHAR,PETSC_FALSE);
849:   }
850:   if (dm->ops->view) {
851:     (*dm->ops->view)(dm,v);
852:   }
853:   return(0);
854: }

858: /*@
859:     DMCreateGlobalVector - Creates a global vector from a DM object

861:     Collective on DM

863:     Input Parameter:
864: .   dm - the DM object

866:     Output Parameter:
867: .   vec - the global vector

869:     Level: beginner

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

873: @*/
874: PetscErrorCode  DMCreateGlobalVector(DM dm,Vec *vec)
875: {

880:   (*dm->ops->createglobalvector)(dm,vec);
881:   return(0);
882: }

886: /*@
887:     DMCreateLocalVector - Creates a local vector from a DM object

889:     Not Collective

891:     Input Parameter:
892: .   dm - the DM object

894:     Output Parameter:
895: .   vec - the local vector

897:     Level: beginner

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

901: @*/
902: PetscErrorCode  DMCreateLocalVector(DM dm,Vec *vec)
903: {

908:   (*dm->ops->createlocalvector)(dm,vec);
909:   return(0);
910: }

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

917:    Collective on DM

919:    Input Parameter:
920: .  dm - the DM that provides the mapping

922:    Output Parameter:
923: .  ltog - the mapping

925:    Level: intermediate

927:    Notes:
928:    This mapping can then be used by VecSetLocalToGlobalMapping() or
929:    MatSetLocalToGlobalMapping().

931: .seealso: DMCreateLocalVector()
932: @*/
933: PetscErrorCode DMGetLocalToGlobalMapping(DM dm,ISLocalToGlobalMapping *ltog)
934: {
935:   PetscInt       bs = -1, bsLocal, bsMin, bsMax;

941:   if (!dm->ltogmap) {
942:     PetscSection section, sectionGlobal;

944:     DMGetDefaultSection(dm, &section);
945:     if (section) {
946:       const PetscInt *cdofs;
947:       PetscInt       *ltog;
948:       PetscInt        pStart, pEnd, size, p, l;

950:       DMGetDefaultGlobalSection(dm, &sectionGlobal);
951:       PetscSectionGetChart(section, &pStart, &pEnd);
952:       PetscSectionGetStorageSize(section, &size);
953:       PetscMalloc1(size, &ltog); /* We want the local+overlap size */
954:       for (p = pStart, l = 0; p < pEnd; ++p) {
955:         PetscInt bdof, cdof, dof, off, c, cind = 0;

957:         /* Should probably use constrained dofs */
958:         PetscSectionGetDof(section, p, &dof);
959:         PetscSectionGetConstraintDof(section, p, &cdof);
960:         PetscSectionGetConstraintIndices(section, p, &cdofs);
961:         PetscSectionGetOffset(sectionGlobal, p, &off);
962:         /* If you have dofs, and constraints, and they are unequal, we set the blocksize to 1 */
963:         bdof = cdof && (dof-cdof) ? 1 : dof;
964:         if (dof) {
965:           if (bs < 0)          {bs = bdof;}
966:           else if (bs != bdof) {bs = 1;}
967:         }
968:         for (c = 0; c < dof; ++c, ++l) {
969:           if ((cind < cdof) && (c == cdofs[cind])) ltog[l] = off < 0 ? off-c : off+c;
970:           else                                     ltog[l] = (off < 0 ? -(off+1) : off) + c;
971:         }
972:       }
973:       /* Must have same blocksize on all procs (some might have no points) */
974:       bsLocal = bs;
975:       MPIU_Allreduce(&bsLocal, &bsMax, 1, MPIU_INT, MPI_MAX, PetscObjectComm((PetscObject)dm));
976:       bsLocal = bs < 0 ? bsMax : bs;
977:       MPIU_Allreduce(&bsLocal, &bsMin, 1, MPIU_INT, MPI_MIN, PetscObjectComm((PetscObject)dm));
978:       if (bsMin != bsMax) {bs = 1;}
979:       else                {bs = bsMax;}
980:       ISLocalToGlobalMappingCreate(PetscObjectComm((PetscObject)dm), bs < 0 ? 1 : bs, size, ltog, PETSC_OWN_POINTER, &dm->ltogmap);
981:       PetscLogObjectParent((PetscObject)dm, (PetscObject)dm->ltogmap);
982:     } else {
983:       if (!dm->ops->getlocaltoglobalmapping) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM can not create LocalToGlobalMapping");
984:       (*dm->ops->getlocaltoglobalmapping)(dm);
985:     }
986:   }
987:   *ltog = dm->ltogmap;
988:   return(0);
989: }

993: /*@
994:    DMGetBlockSize - Gets the inherent block size associated with a DM

996:    Not Collective

998:    Input Parameter:
999: .  dm - the DM with block structure

1001:    Output Parameter:
1002: .  bs - the block size, 1 implies no exploitable block structure

1004:    Level: intermediate

1006: .seealso: ISCreateBlock(), VecSetBlockSize(), MatSetBlockSize(), DMGetLocalToGlobalMapping()
1007: @*/
1008: PetscErrorCode  DMGetBlockSize(DM dm,PetscInt *bs)
1009: {
1013:   if (dm->bs < 1) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"DM does not have enough information to provide a block size yet");
1014:   *bs = dm->bs;
1015:   return(0);
1016: }

1020: /*@
1021:     DMCreateInterpolation - Gets interpolation matrix between two DM objects

1023:     Collective on DM

1025:     Input Parameter:
1026: +   dm1 - the DM object
1027: -   dm2 - the second, finer DM object

1029:     Output Parameter:
1030: +  mat - the interpolation
1031: -  vec - the scaling (optional)

1033:     Level: developer

1035:     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
1036:         DMCoarsen(). The coordinates set into the DMDA are completely ignored in computing the interpolation.

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


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

1044: @*/
1045: PetscErrorCode  DMCreateInterpolation(DM dm1,DM dm2,Mat *mat,Vec *vec)
1046: {

1052:   PetscLogEventBegin(DM_CreateInterpolation,dm1,dm2,0,0);
1053:   (*dm1->ops->createinterpolation)(dm1,dm2,mat,vec);
1054:   PetscLogEventEnd(DM_CreateInterpolation,dm1,dm2,0,0);
1055:   return(0);
1056: }

1060: /*@
1061:     DMCreateRestriction - Gets restriction matrix between two DM objects

1063:     Collective on DM

1065:     Input Parameter:
1066: +   dm1 - the DM object
1067: -   dm2 - the second, finer DM object

1069:     Output Parameter:
1070: .  mat - the restriction


1073:     Level: developer

1075:     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
1076:         DMCoarsen(). The coordinates set into the DMDA are completely ignored in computing the interpolation.

1078:  
1079: .seealso DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateColoring(), DMCreateMatrix(), DMRefine(), DMCoarsen(), DMCreateInterpolation()

1081: @*/
1082: PetscErrorCode  DMCreateRestriction(DM dm1,DM dm2,Mat *mat)
1083: {

1089:   PetscLogEventBegin(DM_CreateRestriction,dm1,dm2,0,0);
1090:   (*dm1->ops->createrestriction)(dm1,dm2,mat);
1091:   PetscLogEventEnd(DM_CreateRestriction,dm1,dm2,0,0);
1092:   return(0);
1093: }

1097: /*@
1098:     DMCreateInjection - Gets injection matrix between two DM objects

1100:     Collective on DM

1102:     Input Parameter:
1103: +   dm1 - the DM object
1104: -   dm2 - the second, finer DM object

1106:     Output Parameter:
1107: .   mat - the injection

1109:     Level: developer

1111:    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
1112:         DMCoarsen(). The coordinates set into the DMDA are completely ignored in computing the injection.

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

1116: @*/
1117: PetscErrorCode  DMCreateInjection(DM dm1,DM dm2,Mat *mat)
1118: {

1124:   if (!dm1->ops->getinjection) SETERRQ(PetscObjectComm((PetscObject)dm1),PETSC_ERR_SUP,"DMCreateInjection not implemented for this type");
1125:   (*dm1->ops->getinjection)(dm1,dm2,mat);
1126:   return(0);
1127: }

1131: /*@
1132:     DMCreateColoring - Gets coloring for a DM

1134:     Collective on DM

1136:     Input Parameter:
1137: +   dm - the DM object
1138: -   ctype - IS_COLORING_LOCAL or IS_COLORING_GLOBAL

1140:     Output Parameter:
1141: .   coloring - the coloring

1143:     Level: developer

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

1147: @*/
1148: PetscErrorCode  DMCreateColoring(DM dm,ISColoringType ctype,ISColoring *coloring)
1149: {

1154:   if (!dm->ops->getcoloring) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"No coloring for this type of DM yet");
1155:   (*dm->ops->getcoloring)(dm,ctype,coloring);
1156:   return(0);
1157: }

1161: /*@
1162:     DMCreateMatrix - Gets empty Jacobian for a DM

1164:     Collective on DM

1166:     Input Parameter:
1167: .   dm - the DM object

1169:     Output Parameter:
1170: .   mat - the empty Jacobian

1172:     Level: beginner

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

1177:        By default it also sets the nonzero structure and puts in the zero entries. To prevent setting
1178:        the nonzero pattern call DMDASetMatPreallocateOnly()

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

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

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

1188: @*/
1189: PetscErrorCode  DMCreateMatrix(DM dm,Mat *mat)
1190: {

1195:   MatInitializePackage();
1198:   (*dm->ops->creatematrix)(dm,mat);
1199:   return(0);
1200: }

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

1208:   Logically Collective on DM

1210:   Input Parameter:
1211: + dm - the DM
1212: - only - PETSC_TRUE if only want preallocation

1214:   Level: developer
1215: .seealso DMCreateMatrix()
1216: @*/
1217: PetscErrorCode DMSetMatrixPreallocateOnly(DM dm, PetscBool only)
1218: {
1221:   dm->prealloc_only = only;
1222:   return(0);
1223: }

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

1230:   Not Collective

1232:   Input Parameters:
1233: + dm - the DM object
1234: . count - The minium size
1235: - dtype - data type (PETSC_REAL, PETSC_SCALAR, PETSC_INT)

1237:   Output Parameter:
1238: . array - the work array

1240:   Level: developer

1242: .seealso DMDestroy(), DMCreate()
1243: @*/
1244: PetscErrorCode DMGetWorkArray(DM dm,PetscInt count,PetscDataType dtype,void *mem)
1245: {
1247:   DMWorkLink     link;
1248:   size_t         dsize;

1253:   if (dm->workin) {
1254:     link       = dm->workin;
1255:     dm->workin = dm->workin->next;
1256:   } else {
1257:     PetscNewLog(dm,&link);
1258:   }
1259:   PetscDataTypeGetSize(dtype,&dsize);
1260:   if (dsize*count > link->bytes) {
1261:     PetscFree(link->mem);
1262:     PetscMalloc(dsize*count,&link->mem);
1263:     link->bytes = dsize*count;
1264:   }
1265:   link->next   = dm->workout;
1266:   dm->workout  = link;
1267:   *(void**)mem = link->mem;
1268:   return(0);
1269: }

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

1276:   Not Collective

1278:   Input Parameters:
1279: + dm - the DM object
1280: . count - The minium size
1281: - dtype - data type (PETSC_REAL, PETSC_SCALAR, PETSC_INT)

1283:   Output Parameter:
1284: . array - the work array

1286:   Level: developer

1288: .seealso DMDestroy(), DMCreate()
1289: @*/
1290: PetscErrorCode DMRestoreWorkArray(DM dm,PetscInt count,PetscDataType dtype,void *mem)
1291: {
1292:   DMWorkLink *p,link;

1297:   for (p=&dm->workout; (link=*p); p=&link->next) {
1298:     if (link->mem == *(void**)mem) {
1299:       *p           = link->next;
1300:       link->next   = dm->workin;
1301:       dm->workin   = link;
1302:       *(void**)mem = NULL;
1303:       return(0);
1304:     }
1305:   }
1306:   SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Array was not checked out");
1307: }

1311: PetscErrorCode DMSetNullSpaceConstructor(DM dm, PetscInt field, PetscErrorCode (*nullsp)(DM dm, PetscInt field, MatNullSpace *nullSpace))
1312: {
1315:   if (field >= 10) SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Cannot handle %d >= 10 fields", field);
1316:   dm->nullspaceConstructors[field] = nullsp;
1317:   return(0);
1318: }

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

1325:   Not collective

1327:   Input Parameter:
1328: . dm - the DM object

1330:   Output Parameters:
1331: + numFields  - The number of fields (or NULL if not requested)
1332: . fieldNames - The name for each field (or NULL if not requested)
1333: - fields     - The global indices for each field (or NULL if not requested)

1335:   Level: intermediate

1337:   Notes:
1338:   The user is responsible for freeing all requested arrays. In particular, every entry of names should be freed with
1339:   PetscFree(), every entry of fields should be destroyed with ISDestroy(), and both arrays should be freed with
1340:   PetscFree().

1342: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix()
1343: @*/
1344: PetscErrorCode DMCreateFieldIS(DM dm, PetscInt *numFields, char ***fieldNames, IS **fields)
1345: {
1346:   PetscSection   section, sectionGlobal;

1351:   if (numFields) {
1353:     *numFields = 0;
1354:   }
1355:   if (fieldNames) {
1357:     *fieldNames = NULL;
1358:   }
1359:   if (fields) {
1361:     *fields = NULL;
1362:   }
1363:   DMGetDefaultSection(dm, &section);
1364:   if (section) {
1365:     PetscInt *fieldSizes, **fieldIndices;
1366:     PetscInt nF, f, pStart, pEnd, p;

1368:     DMGetDefaultGlobalSection(dm, &sectionGlobal);
1369:     PetscSectionGetNumFields(section, &nF);
1370:     PetscMalloc2(nF,&fieldSizes,nF,&fieldIndices);
1371:     PetscSectionGetChart(sectionGlobal, &pStart, &pEnd);
1372:     for (f = 0; f < nF; ++f) {
1373:       fieldSizes[f] = 0;
1374:     }
1375:     for (p = pStart; p < pEnd; ++p) {
1376:       PetscInt gdof;

1378:       PetscSectionGetDof(sectionGlobal, p, &gdof);
1379:       if (gdof > 0) {
1380:         for (f = 0; f < nF; ++f) {
1381:           PetscInt fdof, fcdof;

1383:           PetscSectionGetFieldDof(section, p, f, &fdof);
1384:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
1385:           fieldSizes[f] += fdof-fcdof;
1386:         }
1387:       }
1388:     }
1389:     for (f = 0; f < nF; ++f) {
1390:       PetscMalloc1(fieldSizes[f], &fieldIndices[f]);
1391:       fieldSizes[f] = 0;
1392:     }
1393:     for (p = pStart; p < pEnd; ++p) {
1394:       PetscInt gdof, goff;

1396:       PetscSectionGetDof(sectionGlobal, p, &gdof);
1397:       if (gdof > 0) {
1398:         PetscSectionGetOffset(sectionGlobal, p, &goff);
1399:         for (f = 0; f < nF; ++f) {
1400:           PetscInt fdof, fcdof, fc;

1402:           PetscSectionGetFieldDof(section, p, f, &fdof);
1403:           PetscSectionGetFieldConstraintDof(section, p, f, &fcdof);
1404:           for (fc = 0; fc < fdof-fcdof; ++fc, ++fieldSizes[f]) {
1405:             fieldIndices[f][fieldSizes[f]] = goff++;
1406:           }
1407:         }
1408:       }
1409:     }
1410:     if (numFields) *numFields = nF;
1411:     if (fieldNames) {
1412:       PetscMalloc1(nF, fieldNames);
1413:       for (f = 0; f < nF; ++f) {
1414:         const char *fieldName;

1416:         PetscSectionGetFieldName(section, f, &fieldName);
1417:         PetscStrallocpy(fieldName, (char**) &(*fieldNames)[f]);
1418:       }
1419:     }
1420:     if (fields) {
1421:       PetscMalloc1(nF, fields);
1422:       for (f = 0; f < nF; ++f) {
1423:         ISCreateGeneral(PetscObjectComm((PetscObject)dm), fieldSizes[f], fieldIndices[f], PETSC_OWN_POINTER, &(*fields)[f]);
1424:       }
1425:     }
1426:     PetscFree2(fieldSizes,fieldIndices);
1427:   } else if (dm->ops->createfieldis) {
1428:     (*dm->ops->createfieldis)(dm, numFields, fieldNames, fields);
1429:   }
1430:   return(0);
1431: }


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

1442:   Not collective

1444:   Input Parameter:
1445: . dm - the DM object

1447:   Output Parameters:
1448: + len       - The number of subproblems in the field decomposition (or NULL if not requested)
1449: . namelist  - The name for each field (or NULL if not requested)
1450: . islist    - The global indices for each field (or NULL if not requested)
1451: - dmlist    - The DMs for each field subproblem (or NULL, if not requested; if NULL is returned, no DMs are defined)

1453:   Level: intermediate

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

1460: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMCreateFieldIS()
1461: @*/
1462: PetscErrorCode DMCreateFieldDecomposition(DM dm, PetscInt *len, char ***namelist, IS **islist, DM **dmlist)
1463: {

1468:   if (len) {
1470:     *len = 0;
1471:   }
1472:   if (namelist) {
1474:     *namelist = 0;
1475:   }
1476:   if (islist) {
1478:     *islist = 0;
1479:   }
1480:   if (dmlist) {
1482:     *dmlist = 0;
1483:   }
1484:   /*
1485:    Is it a good idea to apply the following check across all impls?
1486:    Perhaps some impls can have a well-defined decomposition before DMSetUp?
1487:    This, however, follows the general principle that accessors are not well-behaved until the object is set up.
1488:    */
1489:   if (!dm->setupcalled) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
1490:   if (!dm->ops->createfielddecomposition) {
1491:     PetscSection section;
1492:     PetscInt     numFields, f;

1494:     DMGetDefaultSection(dm, &section);
1495:     if (section) {PetscSectionGetNumFields(section, &numFields);}
1496:     if (section && numFields && dm->ops->createsubdm) {
1497:       if (len) *len = numFields;
1498:       if (namelist) {PetscMalloc1(numFields,namelist);}
1499:       if (islist)   {PetscMalloc1(numFields,islist);}
1500:       if (dmlist)   {PetscMalloc1(numFields,dmlist);}
1501:       for (f = 0; f < numFields; ++f) {
1502:         const char *fieldName;

1504:         DMCreateSubDM(dm, 1, &f, islist ? &(*islist)[f] : NULL, dmlist ? &(*dmlist)[f] : NULL);
1505:         if (namelist) {
1506:           PetscSectionGetFieldName(section, f, &fieldName);
1507:           PetscStrallocpy(fieldName, (char**) &(*namelist)[f]);
1508:         }
1509:       }
1510:     } else {
1511:       DMCreateFieldIS(dm, len, namelist, islist);
1512:       /* By default there are no DMs associated with subproblems. */
1513:       if (dmlist) *dmlist = NULL;
1514:     }
1515:   } else {
1516:     (*dm->ops->createfielddecomposition)(dm,len,namelist,islist,dmlist);
1517:   }
1518:   return(0);
1519: }

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

1527:   Not collective

1529:   Input Parameters:
1530: + dm - the DM object
1531: . numFields - number of fields in this subproblem
1532: - len       - The number of subproblems in the decomposition (or NULL if not requested)

1534:   Output Parameters:
1535: . is - The global indices for the subproblem
1536: - dm - The DM for the subproblem

1538:   Level: intermediate

1540: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMCreateFieldIS()
1541: @*/
1542: PetscErrorCode DMCreateSubDM(DM dm, PetscInt numFields, PetscInt fields[], IS *is, DM *subdm)
1543: {

1551:   if (dm->ops->createsubdm) {
1552:     (*dm->ops->createsubdm)(dm, numFields, fields, is, subdm);
1553:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "This type has no DMCreateSubDM implementation defined");
1554:   return(0);
1555: }


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

1567:   Not collective

1569:   Input Parameter:
1570: . dm - the DM object

1572:   Output Parameters:
1573: + len         - The number of subproblems in the domain decomposition (or NULL if not requested)
1574: . namelist    - The name for each subdomain (or NULL if not requested)
1575: . innerislist - The global indices for each inner subdomain (or NULL, if not requested)
1576: . outerislist - The global indices for each outer subdomain (or NULL, if not requested)
1577: - dmlist      - The DMs for each subdomain subproblem (or NULL, if not requested; if NULL is returned, no DMs are defined)

1579:   Level: intermediate

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

1586: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMCreateDomainDecompositionDM(), DMCreateFieldDecomposition()
1587: @*/
1588: PetscErrorCode DMCreateDomainDecomposition(DM dm, PetscInt *len, char ***namelist, IS **innerislist, IS **outerislist, DM **dmlist)
1589: {
1590:   PetscErrorCode      ierr;
1591:   DMSubDomainHookLink link;
1592:   PetscInt            i,l;

1601:   /*
1602:    Is it a good idea to apply the following check across all impls?
1603:    Perhaps some impls can have a well-defined decomposition before DMSetUp?
1604:    This, however, follows the general principle that accessors are not well-behaved until the object is set up.
1605:    */
1606:   if (!dm->setupcalled) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_WRONGSTATE, "Decomposition defined only after DMSetUp");
1607:   if (dm->ops->createdomaindecomposition) {
1608:     (*dm->ops->createdomaindecomposition)(dm,&l,namelist,innerislist,outerislist,dmlist);
1609:     /* copy subdomain hooks and context over to the subdomain DMs */
1610:     if (dmlist && *dmlist) {
1611:       for (i = 0; i < l; i++) {
1612:         for (link=dm->subdomainhook; link; link=link->next) {
1613:           if (link->ddhook) {(*link->ddhook)(dm,(*dmlist)[i],link->ctx);}
1614:         }
1615:         if (dm->ctx) (*dmlist)[i]->ctx = dm->ctx;
1616:       }
1617:     }
1618:     if (len) *len = l;
1619:   }
1620:   return(0);
1621: }


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

1629:   Not collective

1631:   Input Parameters:
1632: + dm - the DM object
1633: . n  - the number of subdomain scatters
1634: - subdms - the local subdomains

1636:   Output Parameters:
1637: + n     - the number of scatters returned
1638: . iscat - scatter from global vector to nonoverlapping global vector entries on subdomain
1639: . oscat - scatter from global vector to overlapping global vector entries on subdomain
1640: - gscat - scatter from global vector to local vector on subdomain (fills in ghosts)

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

1647:   Level: developer

1649: .seealso DMDestroy(), DMView(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMCreateFieldIS()
1650: @*/
1651: PetscErrorCode DMCreateDomainDecompositionScatters(DM dm,PetscInt n,DM *subdms,VecScatter **iscat,VecScatter **oscat,VecScatter **gscat)
1652: {

1658:   if (dm->ops->createddscatters) {
1659:     (*dm->ops->createddscatters)(dm,n,subdms,iscat,oscat,gscat);
1660:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "This type has no DMCreateDomainDecompositionScatter implementation defined");
1661:   return(0);
1662: }

1666: /*@
1667:   DMRefine - Refines a DM object

1669:   Collective on DM

1671:   Input Parameter:
1672: + dm   - the DM object
1673: - comm - the communicator to contain the new DM object (or MPI_COMM_NULL)

1675:   Output Parameter:
1676: . dmf - the refined DM, or NULL

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

1680:   Level: developer

1682: .seealso DMCoarsen(), DMDestroy(), DMView(), DMCreateGlobalVector(), DMCreateInterpolation()
1683: @*/
1684: PetscErrorCode  DMRefine(DM dm,MPI_Comm comm,DM *dmf)
1685: {
1686:   PetscErrorCode   ierr;
1687:   DMRefineHookLink link;

1691:   if (!dm->ops->refine) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"This DM cannot refine");
1692:   (*dm->ops->refine)(dm,comm,dmf);
1693:   if (*dmf) {
1694:     (*dmf)->ops->creatematrix = dm->ops->creatematrix;

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

1698:     (*dmf)->ctx       = dm->ctx;
1699:     (*dmf)->leveldown = dm->leveldown;
1700:     (*dmf)->levelup   = dm->levelup + 1;

1702:     DMSetMatType(*dmf,dm->mattype);
1703:     for (link=dm->refinehook; link; link=link->next) {
1704:       if (link->refinehook) {
1705:         (*link->refinehook)(dm,*dmf,link->ctx);
1706:       }
1707:     }
1708:   }
1709:   return(0);
1710: }

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

1717:    Logically Collective

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

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

1728: +  coarse - coarse level DM
1729: .  fine - fine level DM to interpolate problem to
1730: -  ctx - optional user-defined function context

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

1735: +  coarse - coarse level DM
1736: .  interp - matrix interpolating a coarse-level solution to the finer grid
1737: .  fine - fine level DM to update
1738: -  ctx - optional user-defined function context

1740:    Level: advanced

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

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

1747:    This function is currently not available from Fortran.

1749: .seealso: DMCoarsenHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
1750: @*/
1751: PetscErrorCode DMRefineHookAdd(DM coarse,PetscErrorCode (*refinehook)(DM,DM,void*),PetscErrorCode (*interphook)(DM,Mat,DM,void*),void *ctx)
1752: {
1753:   PetscErrorCode   ierr;
1754:   DMRefineHookLink link,*p;

1758:   for (p=&coarse->refinehook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
1759:   PetscNew(&link);
1760:   link->refinehook = refinehook;
1761:   link->interphook = interphook;
1762:   link->ctx        = ctx;
1763:   link->next       = NULL;
1764:   *p               = link;
1765:   return(0);
1766: }

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

1773:    Collective if any hooks are

1775:    Input Arguments:
1776: +  coarse - coarser DM to use as a base
1777: .  restrct - interpolation matrix, apply using MatInterpolate()
1778: -  fine - finer DM to update

1780:    Level: developer

1782: .seealso: DMRefineHookAdd(), MatInterpolate()
1783: @*/
1784: PetscErrorCode DMInterpolate(DM coarse,Mat interp,DM fine)
1785: {
1786:   PetscErrorCode   ierr;
1787:   DMRefineHookLink link;

1790:   for (link=fine->refinehook; link; link=link->next) {
1791:     if (link->interphook) {
1792:       (*link->interphook)(coarse,interp,fine,link->ctx);
1793:     }
1794:   }
1795:   return(0);
1796: }

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

1803:     Not Collective

1805:     Input Parameter:
1806: .   dm - the DM object

1808:     Output Parameter:
1809: .   level - number of refinements

1811:     Level: developer

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

1815: @*/
1816: PetscErrorCode  DMGetRefineLevel(DM dm,PetscInt *level)
1817: {
1820:   *level = dm->levelup;
1821:   return(0);
1822: }

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

1829:     Not Collective

1831:     Input Parameter:
1832: +   dm - the DM object
1833: -   level - number of refinements

1835:     Level: advanced

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

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

1841: @*/
1842: PetscErrorCode  DMSetRefineLevel(DM dm,PetscInt level)
1843: {
1846:   dm->levelup = level;
1847:   return(0);
1848: }

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

1855:    Logically Collective

1857:    Input Arguments:
1858: +  dm - the DM
1859: .  beginhook - function to run at the beginning of DMGlobalToLocalBegin()
1860: .  endhook - function to run after DMGlobalToLocalEnd() has completed
1861: -  ctx - [optional] user-defined context for provide data for the hooks (may be NULL)

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

1866: +  dm - global DM
1867: .  g - global vector
1868: .  mode - mode
1869: .  l - local vector
1870: -  ctx - optional user-defined function context


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

1876: +  global - global DM
1877: -  ctx - optional user-defined function context

1879:    Level: advanced

1881: .seealso: DMRefineHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
1882: @*/
1883: PetscErrorCode DMGlobalToLocalHookAdd(DM dm,PetscErrorCode (*beginhook)(DM,Vec,InsertMode,Vec,void*),PetscErrorCode (*endhook)(DM,Vec,InsertMode,Vec,void*),void *ctx)
1884: {
1885:   PetscErrorCode          ierr;
1886:   DMGlobalToLocalHookLink link,*p;

1890:   for (p=&dm->gtolhook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
1891:   PetscNew(&link);
1892:   link->beginhook = beginhook;
1893:   link->endhook   = endhook;
1894:   link->ctx       = ctx;
1895:   link->next      = NULL;
1896:   *p              = link;
1897:   return(0);
1898: }

1902: static PetscErrorCode DMGlobalToLocalHook_Constraints(DM dm, Vec g, InsertMode mode, Vec l, void *ctx)
1903: {
1904:   Mat cMat;
1905:   Vec cVec;
1906:   PetscSection section, cSec;
1907:   PetscInt pStart, pEnd, p, dof;

1912:   DMGetDefaultConstraints(dm,&cSec,&cMat);
1913:   if (cMat && (mode == INSERT_VALUES || mode == INSERT_ALL_VALUES || mode == INSERT_BC_VALUES)) {
1914:     PetscInt nRows;

1916:     MatGetSize(cMat,&nRows,NULL);
1917:     if (nRows <= 0) return(0);
1918:     DMGetDefaultSection(dm,&section);
1919:     MatCreateVecs(cMat,NULL,&cVec);
1920:     MatMult(cMat,l,cVec);
1921:     PetscSectionGetChart(cSec,&pStart,&pEnd);
1922:     for (p = pStart; p < pEnd; p++) {
1923:       PetscSectionGetDof(cSec,p,&dof);
1924:       if (dof) {
1925:         PetscScalar *vals;
1926:         VecGetValuesSection(cVec,cSec,p,&vals);
1927:         VecSetValuesSection(l,section,p,vals,INSERT_ALL_VALUES);
1928:       }
1929:     }
1930:     VecDestroy(&cVec);
1931:   }
1932:   return(0);
1933: }

1937: /*@
1938:     DMGlobalToLocalBegin - Begins updating local vectors from global vector

1940:     Neighbor-wise Collective on DM

1942:     Input Parameters:
1943: +   dm - the DM object
1944: .   g - the global vector
1945: .   mode - INSERT_VALUES or ADD_VALUES
1946: -   l - the local vector


1949:     Level: beginner

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

1953: @*/
1954: PetscErrorCode  DMGlobalToLocalBegin(DM dm,Vec g,InsertMode mode,Vec l)
1955: {
1956:   PetscSF                 sf;
1957:   PetscErrorCode          ierr;
1958:   DMGlobalToLocalHookLink link;

1962:   for (link=dm->gtolhook; link; link=link->next) {
1963:     if (link->beginhook) {
1964:       (*link->beginhook)(dm,g,mode,l,link->ctx);
1965:     }
1966:   }
1967:   DMGetDefaultSF(dm, &sf);
1968:   if (sf) {
1969:     const PetscScalar *gArray;
1970:     PetscScalar       *lArray;

1972:     if (mode == ADD_VALUES) SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %D", mode);
1973:     VecGetArray(l, &lArray);
1974:     VecGetArrayRead(g, &gArray);
1975:     PetscSFBcastBegin(sf, MPIU_SCALAR, gArray, lArray);
1976:     VecRestoreArray(l, &lArray);
1977:     VecRestoreArrayRead(g, &gArray);
1978:   } else {
1979:     (*dm->ops->globaltolocalbegin)(dm,g,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),l);
1980:   }
1981:   return(0);
1982: }

1986: /*@
1987:     DMGlobalToLocalEnd - Ends updating local vectors from global vector

1989:     Neighbor-wise Collective on DM

1991:     Input Parameters:
1992: +   dm - the DM object
1993: .   g - the global vector
1994: .   mode - INSERT_VALUES or ADD_VALUES
1995: -   l - the local vector


1998:     Level: beginner

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

2002: @*/
2003: PetscErrorCode  DMGlobalToLocalEnd(DM dm,Vec g,InsertMode mode,Vec l)
2004: {
2005:   PetscSF                 sf;
2006:   PetscErrorCode          ierr;
2007:   const PetscScalar      *gArray;
2008:   PetscScalar            *lArray;
2009:   DMGlobalToLocalHookLink link;

2013:   DMGetDefaultSF(dm, &sf);
2014:   if (sf) {
2015:     if (mode == ADD_VALUES) SETERRQ1(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %D", mode);

2017:     VecGetArray(l, &lArray);
2018:     VecGetArrayRead(g, &gArray);
2019:     PetscSFBcastEnd(sf, MPIU_SCALAR, gArray, lArray);
2020:     VecRestoreArray(l, &lArray);
2021:     VecRestoreArrayRead(g, &gArray);
2022:   } else {
2023:     (*dm->ops->globaltolocalend)(dm,g,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),l);
2024:   }
2025:   DMGlobalToLocalHook_Constraints(dm,g,mode,l,NULL);
2026:   for (link=dm->gtolhook; link; link=link->next) {
2027:     if (link->endhook) {(*link->endhook)(dm,g,mode,l,link->ctx);}
2028:   }
2029:   return(0);
2030: }

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

2037:    Logically Collective

2039:    Input Arguments:
2040: +  dm - the DM
2041: .  beginhook - function to run at the beginning of DMLocalToGlobalBegin()
2042: .  endhook - function to run after DMLocalToGlobalEnd() has completed
2043: -  ctx - [optional] user-defined context for provide data for the hooks (may be NULL)

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

2048: +  dm - global DM
2049: .  l - local vector
2050: .  mode - mode
2051: .  g - global vector
2052: -  ctx - optional user-defined function context


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

2058: +  global - global DM
2059: .  l - local vector
2060: .  mode - mode
2061: .  g - global vector
2062: -  ctx - optional user-defined function context

2064:    Level: advanced

2066: .seealso: DMRefineHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
2067: @*/
2068: PetscErrorCode DMLocalToGlobalHookAdd(DM dm,PetscErrorCode (*beginhook)(DM,Vec,InsertMode,Vec,void*),PetscErrorCode (*endhook)(DM,Vec,InsertMode,Vec,void*),void *ctx)
2069: {
2070:   PetscErrorCode          ierr;
2071:   DMLocalToGlobalHookLink link,*p;

2075:   for (p=&dm->ltoghook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
2076:   PetscNew(&link);
2077:   link->beginhook = beginhook;
2078:   link->endhook   = endhook;
2079:   link->ctx       = ctx;
2080:   link->next      = NULL;
2081:   *p              = link;
2082:   return(0);
2083: }

2087: static PetscErrorCode DMLocalToGlobalHook_Constraints(DM dm, Vec l, InsertMode mode, Vec g, void *ctx)
2088: {
2089:   Mat cMat;
2090:   Vec cVec;
2091:   PetscSection section, cSec;
2092:   PetscInt pStart, pEnd, p, dof;

2097:   DMGetDefaultConstraints(dm,&cSec,&cMat);
2098:   if (cMat && (mode == ADD_VALUES || mode == ADD_ALL_VALUES || mode == ADD_BC_VALUES)) {
2099:     PetscInt nRows;

2101:     MatGetSize(cMat,&nRows,NULL);
2102:     if (nRows <= 0) return(0);
2103:     DMGetDefaultSection(dm,&section);
2104:     MatCreateVecs(cMat,NULL,&cVec);
2105:     PetscSectionGetChart(cSec,&pStart,&pEnd);
2106:     for (p = pStart; p < pEnd; p++) {
2107:       PetscSectionGetDof(cSec,p,&dof);
2108:       if (dof) {
2109:         PetscInt d;
2110:         PetscScalar *vals;
2111:         VecGetValuesSection(l,section,p,&vals);
2112:         VecSetValuesSection(cVec,cSec,p,vals,mode);
2113:         /* for this to be the true transpose, we have to zero the values that
2114:          * we just extracted */
2115:         for (d = 0; d < dof; d++) {
2116:           vals[d] = 0.;
2117:         }
2118:       }
2119:     }
2120:     MatMultTransposeAdd(cMat,cVec,l,l);
2121:     VecDestroy(&cVec);
2122:   }
2123:   return(0);
2124: }

2128: /*@
2129:     DMLocalToGlobalBegin - updates global vectors from local vectors

2131:     Neighbor-wise Collective on DM

2133:     Input Parameters:
2134: +   dm - the DM object
2135: .   l - the local vector
2136: .   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.
2137: -   g - the global vector

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

2142:     Level: beginner

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

2146: @*/
2147: PetscErrorCode  DMLocalToGlobalBegin(DM dm,Vec l,InsertMode mode,Vec g)
2148: {
2149:   PetscSF                 sf;
2150:   PetscSection            s, gs;
2151:   DMLocalToGlobalHookLink link;
2152:   const PetscScalar      *lArray;
2153:   PetscScalar            *gArray;
2154:   PetscBool               isInsert;
2155:   PetscErrorCode          ierr;

2159:   for (link=dm->ltoghook; link; link=link->next) {
2160:     if (link->beginhook) {
2161:       (*link->beginhook)(dm,l,mode,g,link->ctx);
2162:     }
2163:   }
2164:   DMLocalToGlobalHook_Constraints(dm,l,mode,g,NULL);
2165:   DMGetDefaultSF(dm, &sf);
2166:   DMGetDefaultSection(dm, &s);
2167:   switch (mode) {
2168:   case INSERT_VALUES:
2169:   case INSERT_ALL_VALUES:
2170:   case INSERT_BC_VALUES:
2171:     isInsert = PETSC_TRUE; break;
2172:   case ADD_VALUES:
2173:   case ADD_ALL_VALUES:
2174:   case ADD_BC_VALUES:
2175:     isInsert = PETSC_FALSE; break;
2176:   default:
2177:     SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %D", mode);
2178:   }
2179:   if (sf && !isInsert) {
2180:     VecGetArrayRead(l, &lArray);
2181:     VecGetArray(g, &gArray);
2182:     PetscSFReduceBegin(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM);
2183:     VecRestoreArrayRead(l, &lArray);
2184:     VecRestoreArray(g, &gArray);
2185:   } else if (s && isInsert) {
2186:     PetscInt gStart, pStart, pEnd, p;

2188:     DMGetDefaultGlobalSection(dm, &gs);
2189:     PetscSectionGetChart(s, &pStart, &pEnd);
2190:     VecGetOwnershipRange(g, &gStart, NULL);
2191:     VecGetArrayRead(l, &lArray);
2192:     VecGetArray(g, &gArray);
2193:     for (p = pStart; p < pEnd; ++p) {
2194:       PetscInt dof, gdof, cdof, gcdof, off, goff, d, e;

2196:       PetscSectionGetDof(s, p, &dof);
2197:       PetscSectionGetDof(gs, p, &gdof);
2198:       PetscSectionGetConstraintDof(s, p, &cdof);
2199:       PetscSectionGetConstraintDof(gs, p, &gcdof);
2200:       PetscSectionGetOffset(s, p, &off);
2201:       PetscSectionGetOffset(gs, p, &goff);
2202:       /* Ignore off-process data and points with no global data */
2203:       if (!gdof || goff < 0) continue;
2204:       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);
2205:       /* If no constraints are enforced in the global vector */
2206:       if (!gcdof) {
2207:         for (d = 0; d < dof; ++d) gArray[goff-gStart+d] = lArray[off+d];
2208:       /* If constraints are enforced in the global vector */
2209:       } else if (cdof == gcdof) {
2210:         const PetscInt *cdofs;
2211:         PetscInt        cind = 0;

2213:         PetscSectionGetConstraintIndices(s, p, &cdofs);
2214:         for (d = 0, e = 0; d < dof; ++d) {
2215:           if ((cind < cdof) && (d == cdofs[cind])) {++cind; continue;}
2216:           gArray[goff-gStart+e++] = lArray[off+d];
2217:         }
2218:       } 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);
2219:     }
2220:     VecRestoreArrayRead(l, &lArray);
2221:     VecRestoreArray(g, &gArray);
2222:   } else {
2223:     (*dm->ops->localtoglobalbegin)(dm,l,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),g);
2224:   }
2225:   return(0);
2226: }

2230: /*@
2231:     DMLocalToGlobalEnd - updates global vectors from local vectors

2233:     Neighbor-wise Collective on DM

2235:     Input Parameters:
2236: +   dm - the DM object
2237: .   l - the local vector
2238: .   mode - INSERT_VALUES or ADD_VALUES
2239: -   g - the global vector


2242:     Level: beginner

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

2246: @*/
2247: PetscErrorCode  DMLocalToGlobalEnd(DM dm,Vec l,InsertMode mode,Vec g)
2248: {
2249:   PetscSF                 sf;
2250:   PetscSection            s;
2251:   DMLocalToGlobalHookLink link;
2252:   PetscBool               isInsert;
2253:   PetscErrorCode          ierr;

2257:   DMGetDefaultSF(dm, &sf);
2258:   DMGetDefaultSection(dm, &s);
2259:   switch (mode) {
2260:   case INSERT_VALUES:
2261:   case INSERT_ALL_VALUES:
2262:     isInsert = PETSC_TRUE; break;
2263:   case ADD_VALUES:
2264:   case ADD_ALL_VALUES:
2265:     isInsert = PETSC_FALSE; break;
2266:   default:
2267:     SETERRQ1(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid insertion mode %D", mode);
2268:   }
2269:   if (sf && !isInsert) {
2270:     const PetscScalar *lArray;
2271:     PetscScalar       *gArray;

2273:     VecGetArrayRead(l, &lArray);
2274:     VecGetArray(g, &gArray);
2275:     PetscSFReduceEnd(sf, MPIU_SCALAR, lArray, gArray, MPIU_SUM);
2276:     VecRestoreArrayRead(l, &lArray);
2277:     VecRestoreArray(g, &gArray);
2278:   } else if (s && isInsert) {
2279:   } else {
2280:     (*dm->ops->localtoglobalend)(dm,l,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),g);
2281:   }
2282:   for (link=dm->ltoghook; link; link=link->next) {
2283:     if (link->endhook) {(*link->endhook)(dm,g,mode,l,link->ctx);}
2284:   }
2285:   return(0);
2286: }

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

2295:    Neighbor-wise Collective on DM and Vec

2297:    Input Parameters:
2298: +  dm - the DM object
2299: .  g - the original local vector
2300: -  mode - one of INSERT_VALUES or ADD_VALUES

2302:    Output Parameter:
2303: .  l  - the local vector with correct ghost values

2305:    Level: intermediate

2307:    Notes:
2308:    The local vectors used here need not be the same as those
2309:    obtained from DMCreateLocalVector(), BUT they
2310:    must have the same parallel data layout; they could, for example, be
2311:    obtained with VecDuplicate() from the DM originating vectors.

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

2316: @*/
2317: PetscErrorCode  DMLocalToLocalBegin(DM dm,Vec g,InsertMode mode,Vec l)
2318: {
2319:   PetscErrorCode          ierr;

2323:   (*dm->ops->localtolocalbegin)(dm,g,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),l);
2324:   return(0);
2325: }

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

2334:    Neighbor-wise Collective on DM and Vec

2336:    Input Parameters:
2337: +  da - the DM object
2338: .  g - the original local vector
2339: -  mode - one of INSERT_VALUES or ADD_VALUES

2341:    Output Parameter:
2342: .  l  - the local vector with correct ghost values

2344:    Level: intermediate

2346:    Notes:
2347:    The local vectors used here need not be the same as those
2348:    obtained from DMCreateLocalVector(), BUT they
2349:    must have the same parallel data layout; they could, for example, be
2350:    obtained with VecDuplicate() from the DM originating vectors.

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

2355: @*/
2356: PetscErrorCode  DMLocalToLocalEnd(DM dm,Vec g,InsertMode mode,Vec l)
2357: {
2358:   PetscErrorCode          ierr;

2362:   (*dm->ops->localtolocalend)(dm,g,mode == INSERT_ALL_VALUES ? INSERT_VALUES : (mode == ADD_ALL_VALUES ? ADD_VALUES : mode),l);
2363:   return(0);
2364: }


2369: /*@
2370:     DMCoarsen - Coarsens a DM object

2372:     Collective on DM

2374:     Input Parameter:
2375: +   dm - the DM object
2376: -   comm - the communicator to contain the new DM object (or MPI_COMM_NULL)

2378:     Output Parameter:
2379: .   dmc - the coarsened DM

2381:     Level: developer

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

2385: @*/
2386: PetscErrorCode DMCoarsen(DM dm, MPI_Comm comm, DM *dmc)
2387: {
2388:   PetscErrorCode    ierr;
2389:   DMCoarsenHookLink link;

2393:   if (!dm->ops->coarsen) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"This DM cannot coarsen");
2394:   PetscLogEventBegin(DM_Coarsen,dm,0,0,0);
2395:   (*dm->ops->coarsen)(dm, comm, dmc);
2396:   if (!(*dmc)) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "NULL coarse mesh produced");
2397:   DMSetCoarseDM(dm,*dmc);
2398:   (*dmc)->ops->creatematrix = dm->ops->creatematrix;
2399:   PetscObjectCopyFortranFunctionPointers((PetscObject)dm,(PetscObject)*dmc);
2400:   (*dmc)->ctx               = dm->ctx;
2401:   (*dmc)->levelup           = dm->levelup;
2402:   (*dmc)->leveldown         = dm->leveldown + 1;
2403:   DMSetMatType(*dmc,dm->mattype);
2404:   for (link=dm->coarsenhook; link; link=link->next) {
2405:     if (link->coarsenhook) {(*link->coarsenhook)(dm,*dmc,link->ctx);}
2406:   }
2407:   PetscLogEventEnd(DM_Coarsen,dm,0,0,0);
2408:   return(0);
2409: }

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

2416:    Logically Collective

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

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

2427: +  fine - fine level DM
2428: .  coarse - coarse level DM to restrict problem to
2429: -  ctx - optional user-defined function context

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

2434: +  fine - fine level DM
2435: .  mrestrict - matrix restricting a fine-level solution to the coarse grid
2436: .  rscale - scaling vector for restriction
2437: .  inject - matrix restricting by injection
2438: .  coarse - coarse level DM to update
2439: -  ctx - optional user-defined function context

2441:    Level: advanced

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

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

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

2451:    This function is currently not available from Fortran.

2453: .seealso: DMRefineHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
2454: @*/
2455: PetscErrorCode DMCoarsenHookAdd(DM fine,PetscErrorCode (*coarsenhook)(DM,DM,void*),PetscErrorCode (*restricthook)(DM,Mat,Vec,Mat,DM,void*),void *ctx)
2456: {
2457:   PetscErrorCode    ierr;
2458:   DMCoarsenHookLink link,*p;

2462:   for (p=&fine->coarsenhook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
2463:   PetscNew(&link);
2464:   link->coarsenhook  = coarsenhook;
2465:   link->restricthook = restricthook;
2466:   link->ctx          = ctx;
2467:   link->next         = NULL;
2468:   *p                 = link;
2469:   return(0);
2470: }

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

2477:    Collective if any hooks are

2479:    Input Arguments:
2480: +  fine - finer DM to use as a base
2481: .  restrct - restriction matrix, apply using MatRestrict()
2482: .  inject - injection matrix, also use MatRestrict()
2483: -  coarse - coarer DM to update

2485:    Level: developer

2487: .seealso: DMCoarsenHookAdd(), MatRestrict()
2488: @*/
2489: PetscErrorCode DMRestrict(DM fine,Mat restrct,Vec rscale,Mat inject,DM coarse)
2490: {
2491:   PetscErrorCode    ierr;
2492:   DMCoarsenHookLink link;

2495:   for (link=fine->coarsenhook; link; link=link->next) {
2496:     if (link->restricthook) {
2497:       (*link->restricthook)(fine,restrct,rscale,inject,coarse,link->ctx);
2498:     }
2499:   }
2500:   return(0);
2501: }

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

2508:    Logically Collective

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


2517:    Calling sequence for ddhook:
2518: $    ddhook(DM global,DM block,void *ctx)

2520: +  global - global DM
2521: .  block  - block DM
2522: -  ctx - optional user-defined function context

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

2527: +  global - global DM
2528: .  out    - scatter to the outer (with ghost and overlap points) block vector
2529: .  in     - scatter to block vector values only owned locally
2530: .  block  - block DM
2531: -  ctx - optional user-defined function context

2533:    Level: advanced

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

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

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

2543:    This function is currently not available from Fortran.

2545: .seealso: DMRefineHookAdd(), SNESFASGetInterpolation(), SNESFASGetInjection(), PetscObjectCompose(), PetscContainerCreate()
2546: @*/
2547: PetscErrorCode DMSubDomainHookAdd(DM global,PetscErrorCode (*ddhook)(DM,DM,void*),PetscErrorCode (*restricthook)(DM,VecScatter,VecScatter,DM,void*),void *ctx)
2548: {
2549:   PetscErrorCode      ierr;
2550:   DMSubDomainHookLink link,*p;

2554:   for (p=&global->subdomainhook; *p; p=&(*p)->next) {} /* Scan to the end of the current list of hooks */
2555:   PetscNew(&link);
2556:   link->restricthook = restricthook;
2557:   link->ddhook       = ddhook;
2558:   link->ctx          = ctx;
2559:   link->next         = NULL;
2560:   *p                 = link;
2561:   return(0);
2562: }

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

2569:    Collective if any hooks are

2571:    Input Arguments:
2572: +  fine - finer DM to use as a base
2573: .  oscatter - scatter from domain global vector filling subdomain global vector with overlap
2574: .  gscatter - scatter from domain global vector filling subdomain local vector with ghosts
2575: -  coarse - coarer DM to update

2577:    Level: developer

2579: .seealso: DMCoarsenHookAdd(), MatRestrict()
2580: @*/
2581: PetscErrorCode DMSubDomainRestrict(DM global,VecScatter oscatter,VecScatter gscatter,DM subdm)
2582: {
2583:   PetscErrorCode      ierr;
2584:   DMSubDomainHookLink link;

2587:   for (link=global->subdomainhook; link; link=link->next) {
2588:     if (link->restricthook) {
2589:       (*link->restricthook)(global,oscatter,gscatter,subdm,link->ctx);
2590:     }
2591:   }
2592:   return(0);
2593: }

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

2600:     Not Collective

2602:     Input Parameter:
2603: .   dm - the DM object

2605:     Output Parameter:
2606: .   level - number of coarsenings

2608:     Level: developer

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

2612: @*/
2613: PetscErrorCode  DMGetCoarsenLevel(DM dm,PetscInt *level)
2614: {
2617:   *level = dm->leveldown;
2618:   return(0);
2619: }



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

2628:     Collective on DM

2630:     Input Parameter:
2631: +   dm - the DM object
2632: -   nlevels - the number of levels of refinement

2634:     Output Parameter:
2635: .   dmf - the refined DM hierarchy

2637:     Level: developer

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

2641: @*/
2642: PetscErrorCode  DMRefineHierarchy(DM dm,PetscInt nlevels,DM dmf[])
2643: {

2648:   if (nlevels < 0) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_OUTOFRANGE,"nlevels cannot be negative");
2649:   if (nlevels == 0) return(0);
2650:   if (dm->ops->refinehierarchy) {
2651:     (*dm->ops->refinehierarchy)(dm,nlevels,dmf);
2652:   } else if (dm->ops->refine) {
2653:     PetscInt i;

2655:     DMRefine(dm,PetscObjectComm((PetscObject)dm),&dmf[0]);
2656:     for (i=1; i<nlevels; i++) {
2657:       DMRefine(dmf[i-1],PetscObjectComm((PetscObject)dm),&dmf[i]);
2658:     }
2659:   } else SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"No RefineHierarchy for this DM yet");
2660:   return(0);
2661: }

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

2668:     Collective on DM

2670:     Input Parameter:
2671: +   dm - the DM object
2672: -   nlevels - the number of levels of coarsening

2674:     Output Parameter:
2675: .   dmc - the coarsened DM hierarchy

2677:     Level: developer

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

2681: @*/
2682: PetscErrorCode  DMCoarsenHierarchy(DM dm, PetscInt nlevels, DM dmc[])
2683: {

2688:   if (nlevels < 0) SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_ARG_OUTOFRANGE,"nlevels cannot be negative");
2689:   if (nlevels == 0) return(0);
2691:   if (dm->ops->coarsenhierarchy) {
2692:     (*dm->ops->coarsenhierarchy)(dm, nlevels, dmc);
2693:   } else if (dm->ops->coarsen) {
2694:     PetscInt i;

2696:     DMCoarsen(dm,PetscObjectComm((PetscObject)dm),&dmc[0]);
2697:     for (i=1; i<nlevels; i++) {
2698:       DMCoarsen(dmc[i-1],PetscObjectComm((PetscObject)dm),&dmc[i]);
2699:     }
2700:   } else SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"No CoarsenHierarchy for this DM yet");
2701:   return(0);
2702: }

2706: /*@
2707:    DMCreateAggregates - Gets the aggregates that map between
2708:    grids associated with two DMs.

2710:    Collective on DM

2712:    Input Parameters:
2713: +  dmc - the coarse grid DM
2714: -  dmf - the fine grid DM

2716:    Output Parameters:
2717: .  rest - the restriction matrix (transpose of the projection matrix)

2719:    Level: intermediate

2721: .keywords: interpolation, restriction, multigrid

2723: .seealso: DMRefine(), DMCreateInjection(), DMCreateInterpolation()
2724: @*/
2725: PetscErrorCode  DMCreateAggregates(DM dmc, DM dmf, Mat *rest)
2726: {

2732:   (*dmc->ops->getaggregates)(dmc, dmf, rest);
2733:   return(0);
2734: }

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

2741:     Not Collective

2743:     Input Parameters:
2744: +   dm - the DM object
2745: -   destroy - the destroy function

2747:     Level: intermediate

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

2751: @*/
2752: PetscErrorCode  DMSetApplicationContextDestroy(DM dm,PetscErrorCode (*destroy)(void**))
2753: {
2756:   dm->ctxdestroy = destroy;
2757:   return(0);
2758: }

2762: /*@
2763:     DMSetApplicationContext - Set a user context into a DM object

2765:     Not Collective

2767:     Input Parameters:
2768: +   dm - the DM object
2769: -   ctx - the user context

2771:     Level: intermediate

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

2775: @*/
2776: PetscErrorCode  DMSetApplicationContext(DM dm,void *ctx)
2777: {
2780:   dm->ctx = ctx;
2781:   return(0);
2782: }

2786: /*@
2787:     DMGetApplicationContext - Gets a user context from a DM object

2789:     Not Collective

2791:     Input Parameter:
2792: .   dm - the DM object

2794:     Output Parameter:
2795: .   ctx - the user context

2797:     Level: intermediate

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

2801: @*/
2802: PetscErrorCode  DMGetApplicationContext(DM dm,void *ctx)
2803: {
2806:   *(void**)ctx = dm->ctx;
2807:   return(0);
2808: }

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

2815:     Logically Collective on DM

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

2821:     Level: intermediate

2823: .seealso DMView(), DMCreateGlobalVector(), DMCreateInterpolation(), DMCreateColoring(), DMCreateMatrix(), DMGetApplicationContext(),
2824:          DMSetJacobian()

2826: @*/
2827: PetscErrorCode  DMSetVariableBounds(DM dm,PetscErrorCode (*f)(DM,Vec,Vec))
2828: {
2830:   dm->ops->computevariablebounds = f;
2831:   return(0);
2832: }

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

2839:     Not Collective

2841:     Input Parameter:
2842: .   dm - the DM object to destroy

2844:     Output Parameter:
2845: .   flg - PETSC_TRUE if the variable bounds function exists

2847:     Level: developer

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

2851: @*/
2852: PetscErrorCode  DMHasVariableBounds(DM dm,PetscBool  *flg)
2853: {
2855:   *flg =  (dm->ops->computevariablebounds) ? PETSC_TRUE : PETSC_FALSE;
2856:   return(0);
2857: }

2861: /*@C
2862:     DMComputeVariableBounds - compute variable bounds used by SNESVI.

2864:     Logically Collective on DM

2866:     Input Parameters:
2867: .   dm - the DM object

2869:     Output parameters:
2870: +   xl - lower bound
2871: -   xu - upper bound

2873:     Level: advanced

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

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

2879: @*/
2880: PetscErrorCode  DMComputeVariableBounds(DM dm, Vec xl, Vec xu)
2881: {

2887:   if (dm->ops->computevariablebounds) {
2888:     (*dm->ops->computevariablebounds)(dm, xl,xu);
2889:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "This DM is incapable of computing variable bounds.");
2890:   return(0);
2891: }

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

2898:     Not Collective

2900:     Input Parameter:
2901: .   dm - the DM object

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

2906:     Level: developer

2908: .seealso DMHasFunction(), DMCreateColoring()

2910: @*/
2911: PetscErrorCode  DMHasColoring(DM dm,PetscBool  *flg)
2912: {
2914:   *flg =  (dm->ops->getcoloring) ? PETSC_TRUE : PETSC_FALSE;
2915:   return(0);
2916: }

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

2923:     Not Collective

2925:     Input Parameter:
2926: .   dm - the DM object

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

2931:     Level: developer

2933: .seealso DMHasFunction(), DMCreateRestriction()

2935: @*/
2936: PetscErrorCode  DMHasCreateRestriction(DM dm,PetscBool  *flg)
2937: {
2939:   *flg =  (dm->ops->createrestriction) ? PETSC_TRUE : PETSC_FALSE;
2940:   return(0);
2941: }

2943: #undef  __FUNCT__
2945: /*@C
2946:     DMSetVec - set the vector at which to compute residual, Jacobian and VI bounds, if the problem is nonlinear.

2948:     Collective on DM

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

2954:     Level: developer

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

2958: @*/
2959: PetscErrorCode  DMSetVec(DM dm,Vec x)
2960: {

2964:   if (x) {
2965:     if (!dm->x) {
2966:       DMCreateGlobalVector(dm,&dm->x);
2967:     }
2968:     VecCopy(x,dm->x);
2969:   } else if (dm->x) {
2970:     VecDestroy(&dm->x);
2971:   }
2972:   return(0);
2973: }

2975: PetscFunctionList DMList              = NULL;
2976: PetscBool         DMRegisterAllCalled = PETSC_FALSE;

2980: /*@C
2981:   DMSetType - Builds a DM, for a particular DM implementation.

2983:   Collective on DM

2985:   Input Parameters:
2986: + dm     - The DM object
2987: - method - The name of the DM type

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

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

2995:   Level: intermediate

2997: .keywords: DM, set, type
2998: .seealso: DMGetType(), DMCreate()
2999: @*/
3000: PetscErrorCode  DMSetType(DM dm, DMType method)
3001: {
3002:   PetscErrorCode (*r)(DM);
3003:   PetscBool      match;

3008:   PetscObjectTypeCompare((PetscObject) dm, method, &match);
3009:   if (match) return(0);

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

3015:   if (dm->ops->destroy) {
3016:     (*dm->ops->destroy)(dm);
3017:     dm->ops->destroy = NULL;
3018:   }
3019:   (*r)(dm);
3020:   PetscObjectChangeTypeName((PetscObject)dm,method);
3021:   return(0);
3022: }

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

3029:   Not Collective

3031:   Input Parameter:
3032: . dm  - The DM

3034:   Output Parameter:
3035: . type - The DM type name

3037:   Level: intermediate

3039: .keywords: DM, get, type, name
3040: .seealso: DMSetType(), DMCreate()
3041: @*/
3042: PetscErrorCode  DMGetType(DM dm, DMType *type)
3043: {

3049:   DMRegisterAll();
3050:   *type = ((PetscObject)dm)->type_name;
3051:   return(0);
3052: }

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

3059:   Collective on DM

3061:   Input Parameters:
3062: + dm - the DM
3063: - newtype - new DM type (use "same" for the same type)

3065:   Output Parameter:
3066: . M - pointer to new DM

3068:   Notes:
3069:   Cannot be used to convert a sequential DM to parallel or parallel to sequential,
3070:   the MPI communicator of the generated DM is always the same as the communicator
3071:   of the input DM.

3073:   Level: intermediate

3075: .seealso: DMCreate()
3076: @*/
3077: PetscErrorCode DMConvert(DM dm, DMType newtype, DM *M)
3078: {
3079:   DM             B;
3080:   char           convname[256];
3081:   PetscBool      sametype/*, issame */;

3088:   PetscObjectTypeCompare((PetscObject) dm, newtype, &sametype);
3089:   /* PetscStrcmp(newtype, "same", &issame); */
3090:   if (sametype) {
3091:     *M   = dm;
3092:     PetscObjectReference((PetscObject) dm);
3093:     return(0);
3094:   } else {
3095:     PetscErrorCode (*conv)(DM, DMType, DM*) = NULL;

3097:     /*
3098:        Order of precedence:
3099:        1) See if a specialized converter is known to the current DM.
3100:        2) See if a specialized converter is known to the desired DM class.
3101:        3) See if a good general converter is registered for the desired class
3102:        4) See if a good general converter is known for the current matrix.
3103:        5) Use a really basic converter.
3104:     */

3106:     /* 1) See if a specialized converter is known to the current DM and the desired class */
3107:     PetscStrcpy(convname,"DMConvert_");
3108:     PetscStrcat(convname,((PetscObject) dm)->type_name);
3109:     PetscStrcat(convname,"_");
3110:     PetscStrcat(convname,newtype);
3111:     PetscStrcat(convname,"_C");
3112:     PetscObjectQueryFunction((PetscObject)dm,convname,&conv);
3113:     if (conv) goto foundconv;

3115:     /* 2)  See if a specialized converter is known to the desired DM class. */
3116:     DMCreate(PetscObjectComm((PetscObject)dm), &B);
3117:     DMSetType(B, newtype);
3118:     PetscStrcpy(convname,"DMConvert_");
3119:     PetscStrcat(convname,((PetscObject) dm)->type_name);
3120:     PetscStrcat(convname,"_");
3121:     PetscStrcat(convname,newtype);
3122:     PetscStrcat(convname,"_C");
3123:     PetscObjectQueryFunction((PetscObject)B,convname,&conv);
3124:     if (conv) {
3125:       DMDestroy(&B);
3126:       goto foundconv;
3127:     }

3129: #if 0
3130:     /* 3) See if a good general converter is registered for the desired class */
3131:     conv = B->ops->convertfrom;
3132:     DMDestroy(&B);
3133:     if (conv) goto foundconv;

3135:     /* 4) See if a good general converter is known for the current matrix */
3136:     if (dm->ops->convert) {
3137:       conv = dm->ops->convert;
3138:     }
3139:     if (conv) goto foundconv;
3140: #endif

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

3145: foundconv:
3146:     PetscLogEventBegin(DM_Convert,dm,0,0,0);
3147:     (*conv)(dm,newtype,M);
3148:     /* Things that are independent of DM type: We should consult DMClone() here */
3149:     if (dm->maxCell) {
3150:       const PetscReal *maxCell, *L;
3151:       const DMBoundaryType *bd;
3152:       DMGetPeriodicity(dm, &maxCell, &L, &bd);
3153:       DMSetPeriodicity(*M,  maxCell,  L,  bd);
3154:     }
3155:     PetscLogEventEnd(DM_Convert,dm,0,0,0);
3156:   }
3157:   PetscObjectStateIncrease((PetscObject) *M);
3158:   return(0);
3159: }

3161: /*--------------------------------------------------------------------------------------------------------------------*/

3165: /*@C
3166:   DMRegister -  Adds a new DM component implementation

3168:   Not Collective

3170:   Input Parameters:
3171: + name        - The name of a new user-defined creation routine
3172: - create_func - The creation routine itself

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


3178:   Sample usage:
3179: .vb
3180:     DMRegister("my_da", MyDMCreate);
3181: .ve

3183:   Then, your DM type can be chosen with the procedural interface via
3184: .vb
3185:     DMCreate(MPI_Comm, DM *);
3186:     DMSetType(DM,"my_da");
3187: .ve
3188:    or at runtime via the option
3189: .vb
3190:     -da_type my_da
3191: .ve

3193:   Level: advanced

3195: .keywords: DM, register
3196: .seealso: DMRegisterAll(), DMRegisterDestroy()

3198: @*/
3199: PetscErrorCode  DMRegister(const char sname[],PetscErrorCode (*function)(DM))
3200: {

3204:   PetscFunctionListAdd(&DMList,sname,function);
3205:   return(0);
3206: }

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

3213:   Collective on PetscViewer

3215:   Input Parameters:
3216: + newdm - the newly loaded DM, this needs to have been created with DMCreate() or
3217:            some related function before a call to DMLoad().
3218: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen() or
3219:            HDF5 file viewer, obtained from PetscViewerHDF5Open()

3221:    Level: intermediate

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

3226:   Notes for advanced users:
3227:   Most users should not need to know the details of the binary storage
3228:   format, since DMLoad() and DMView() completely hide these details.
3229:   But for anyone who's interested, the standard binary matrix storage
3230:   format is
3231: .vb
3232:      has not yet been determined
3233: .ve

3235: .seealso: PetscViewerBinaryOpen(), DMView(), MatLoad(), VecLoad()
3236: @*/
3237: PetscErrorCode  DMLoad(DM newdm, PetscViewer viewer)
3238: {
3239:   PetscBool      isbinary, ishdf5;

3245:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
3246:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERHDF5,&ishdf5);
3247:   if (isbinary) {
3248:     PetscInt classid;
3249:     char     type[256];

3251:     PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
3252:     if (classid != DM_FILE_CLASSID) SETERRQ1(PetscObjectComm((PetscObject)newdm),PETSC_ERR_ARG_WRONG,"Not DM next in file, classid found %d",(int)classid);
3253:     PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
3254:     DMSetType(newdm, type);
3255:     if (newdm->ops->load) {(*newdm->ops->load)(newdm,viewer);}
3256:   } else if (ishdf5) {
3257:     if (newdm->ops->load) {(*newdm->ops->load)(newdm,viewer);}
3258:   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen() or PetscViewerHDF5Open()");
3259:   return(0);
3260: }

3262: /******************************** FEM Support **********************************/

3266: PetscErrorCode DMPrintCellVector(PetscInt c, const char name[], PetscInt len, const PetscScalar x[])
3267: {
3268:   PetscInt       f;

3272:   PetscPrintf(PETSC_COMM_SELF, "Cell %D Element %s\n", c, name);
3273:   for (f = 0; f < len; ++f) {
3274:     PetscPrintf(PETSC_COMM_SELF, "  | %g |\n", (double)PetscRealPart(x[f]));
3275:   }
3276:   return(0);
3277: }

3281: PetscErrorCode DMPrintCellMatrix(PetscInt c, const char name[], PetscInt rows, PetscInt cols, const PetscScalar A[])
3282: {
3283:   PetscInt       f, g;

3287:   PetscPrintf(PETSC_COMM_SELF, "Cell %D Element %s\n", c, name);
3288:   for (f = 0; f < rows; ++f) {
3289:     PetscPrintf(PETSC_COMM_SELF, "  |");
3290:     for (g = 0; g < cols; ++g) {
3291:       PetscPrintf(PETSC_COMM_SELF, " % 9.5g", PetscRealPart(A[f*cols+g]));
3292:     }
3293:     PetscPrintf(PETSC_COMM_SELF, " |\n");
3294:   }
3295:   return(0);
3296: }

3300: PetscErrorCode DMPrintLocalVec(DM dm, const char name[], PetscReal tol, Vec X)
3301: {
3302:   PetscMPIInt    rank, numProcs;
3303:   PetscInt       p;

3307:   MPI_Comm_rank(PetscObjectComm((PetscObject) dm), &rank);
3308:   MPI_Comm_size(PetscObjectComm((PetscObject) dm), &numProcs);
3309:   PetscPrintf(PetscObjectComm((PetscObject) dm), "%s:\n", name);
3310:   for (p = 0; p < numProcs; ++p) {
3311:     if (p == rank) {
3312:       Vec x;

3314:       VecDuplicate(X, &x);
3315:       VecCopy(X, x);
3316:       VecChop(x, tol);
3317:       VecView(x, PETSC_VIEWER_STDOUT_SELF);
3318:       VecDestroy(&x);
3319:       PetscViewerFlush(PETSC_VIEWER_STDOUT_SELF);
3320:     }
3321:     PetscBarrier((PetscObject) dm);
3322:   }
3323:   return(0);
3324: }

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

3331:   Input Parameter:
3332: . dm - The DM

3334:   Output Parameter:
3335: . section - The PetscSection

3337:   Level: intermediate

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

3341: .seealso: DMSetDefaultSection(), DMGetDefaultGlobalSection()
3342: @*/
3343: PetscErrorCode DMGetDefaultSection(DM dm, PetscSection *section)
3344: {

3350:   if (!dm->defaultSection && dm->ops->createdefaultsection) {
3351:     (*dm->ops->createdefaultsection)(dm);
3352:     if (dm->defaultSection) {PetscObjectViewFromOptions((PetscObject) dm->defaultSection, NULL, "-dm_petscsection_view");}
3353:   }
3354:   *section = dm->defaultSection;
3355:   return(0);
3356: }

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

3363:   Input Parameters:
3364: + dm - The DM
3365: - section - The PetscSection

3367:   Level: intermediate

3369:   Note: Any existing Section will be destroyed

3371: .seealso: DMSetDefaultSection(), DMGetDefaultGlobalSection()
3372: @*/
3373: PetscErrorCode DMSetDefaultSection(DM dm, PetscSection section)
3374: {
3375:   PetscInt       numFields = 0;
3376:   PetscInt       f;

3381:   if (section) {
3383:     PetscObjectReference((PetscObject)section);
3384:   }
3385:   PetscSectionDestroy(&dm->defaultSection);
3386:   dm->defaultSection = section;
3387:   if (section) {PetscSectionGetNumFields(dm->defaultSection, &numFields);}
3388:   if (numFields) {
3389:     DMSetNumFields(dm, numFields);
3390:     for (f = 0; f < numFields; ++f) {
3391:       PetscObject disc;
3392:       const char *name;

3394:       PetscSectionGetFieldName(dm->defaultSection, f, &name);
3395:       DMGetField(dm, f, &disc);
3396:       PetscObjectSetName(disc, name);
3397:     }
3398:   }
3399:   /* The global section will be rebuilt in the next call to DMGetDefaultGlobalSection(). */
3400:   PetscSectionDestroy(&dm->defaultGlobalSection);
3401:   return(0);
3402: }

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

3409:   not collective

3411:   Input Parameter:
3412: . dm - The DM

3414:   Output Parameter:
3415: + 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.
3416: - 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.

3418:   Level: advanced

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

3422: .seealso: DMSetDefaultConstraints()
3423: @*/
3424: PetscErrorCode DMGetDefaultConstraints(DM dm, PetscSection *section, Mat *mat)
3425: {

3430:   if (!dm->defaultConstraintSection && !dm->defaultConstraintMat && dm->ops->createdefaultconstraints) {(*dm->ops->createdefaultconstraints)(dm);}
3431:   if (section) {*section = dm->defaultConstraintSection;}
3432:   if (mat) {*mat = dm->defaultConstraintMat;}
3433:   return(0);
3434: }

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

3441:   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().

3443:   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.

3445:   collective on dm

3447:   Input Parameters:
3448: + dm - The DM
3449: + 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).
3450: - 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).

3452:   Level: advanced

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

3456: .seealso: DMGetDefaultConstraints()
3457: @*/
3458: PetscErrorCode DMSetDefaultConstraints(DM dm, PetscSection section, Mat mat)
3459: {
3460:   PetscMPIInt result;

3465:   if (section) {
3467:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)section),&result);
3468:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"constraint section must have local communicator");
3469:   }
3470:   if (mat) {
3472:     MPI_Comm_compare(PETSC_COMM_SELF,PetscObjectComm((PetscObject)mat),&result);
3473:     if (result != MPI_CONGRUENT && result != MPI_IDENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NOTSAMECOMM,"constraint matrix must have local communicator");
3474:   }
3475:   PetscObjectReference((PetscObject)section);
3476:   PetscSectionDestroy(&dm->defaultConstraintSection);
3477:   dm->defaultConstraintSection = section;
3478:   PetscObjectReference((PetscObject)mat);
3479:   MatDestroy(&dm->defaultConstraintMat);
3480:   dm->defaultConstraintMat = mat;
3481:   return(0);
3482: }

3484: #ifdef PETSC_USE_DEBUG
3487: /*
3488:   DMDefaultSectionCheckConsistency - Check the consistentcy of the global and local sections.

3490:   Input Parameters:
3491: + dm - The DM
3492: . localSection - PetscSection describing the local data layout
3493: - globalSection - PetscSection describing the global data layout

3495:   Level: intermediate

3497: .seealso: DMGetDefaultSF(), DMSetDefaultSF()
3498: */
3499: static PetscErrorCode DMDefaultSectionCheckConsistency_Internal(DM dm, PetscSection localSection, PetscSection globalSection)
3500: {
3501:   MPI_Comm        comm;
3502:   PetscLayout     layout;
3503:   const PetscInt *ranges;
3504:   PetscInt        pStart, pEnd, p, nroots;
3505:   PetscMPIInt     size, rank;
3506:   PetscBool       valid = PETSC_TRUE, gvalid;
3507:   PetscErrorCode  ierr;

3510:   PetscObjectGetComm((PetscObject)dm,&comm);
3512:   MPI_Comm_size(comm, &size);
3513:   MPI_Comm_rank(comm, &rank);
3514:   PetscSectionGetChart(globalSection, &pStart, &pEnd);
3515:   PetscSectionGetConstrainedStorageSize(globalSection, &nroots);
3516:   PetscLayoutCreate(comm, &layout);
3517:   PetscLayoutSetBlockSize(layout, 1);
3518:   PetscLayoutSetLocalSize(layout, nroots);
3519:   PetscLayoutSetUp(layout);
3520:   PetscLayoutGetRanges(layout, &ranges);
3521:   for (p = pStart; p < pEnd; ++p) {
3522:     PetscInt       dof, cdof, off, gdof, gcdof, goff, gsize, d;

3524:     PetscSectionGetDof(localSection, p, &dof);
3525:     PetscSectionGetOffset(localSection, p, &off);
3526:     PetscSectionGetConstraintDof(localSection, p, &cdof);
3527:     PetscSectionGetDof(globalSection, p, &gdof);
3528:     PetscSectionGetConstraintDof(globalSection, p, &gcdof);
3529:     PetscSectionGetOffset(globalSection, p, &goff);
3530:     if (!gdof) continue; /* Censored point */
3531:     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;}
3532:     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;}
3533:     if (gdof < 0) {
3534:       gsize = gdof < 0 ? -(gdof+1)-gcdof : gdof-gcdof;
3535:       for (d = 0; d < gsize; ++d) {
3536:         PetscInt offset = -(goff+1) + d, r;

3538:         PetscFindInt(offset,size+1,ranges,&r);
3539:         if (r < 0) r = -(r+2);
3540:         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;}
3541:       }
3542:     }
3543:   }
3544:   PetscLayoutDestroy(&layout);
3545:   PetscSynchronizedFlush(comm, NULL);
3546:   MPIU_Allreduce(&valid, &gvalid, 1, MPIU_BOOL, MPI_LAND, comm);
3547:   if (!gvalid) {
3548:     DMView(dm, NULL);
3549:     SETERRQ(comm, PETSC_ERR_ARG_WRONG, "Inconsistent local and global sections");
3550:   }
3551:   return(0);
3552: }
3553: #endif

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

3560:   Collective on DM

3562:   Input Parameter:
3563: . dm - The DM

3565:   Output Parameter:
3566: . section - The PetscSection

3568:   Level: intermediate

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

3572: .seealso: DMSetDefaultSection(), DMGetDefaultSection()
3573: @*/
3574: PetscErrorCode DMGetDefaultGlobalSection(DM dm, PetscSection *section)
3575: {

3581:   if (!dm->defaultGlobalSection) {
3582:     PetscSection s;

3584:     DMGetDefaultSection(dm, &s);
3585:     if (!s)  SETERRQ(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSection in order to create a global PetscSection");
3586:     if (!dm->sf) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONGSTATE, "DM must have a default PetscSF in order to create a global PetscSection");
3587:     PetscSectionCreateGlobalSection(s, dm->sf, PETSC_FALSE, PETSC_FALSE, &dm->defaultGlobalSection);
3588:     PetscLayoutDestroy(&dm->map);
3589:     PetscSectionGetValueLayout(PetscObjectComm((PetscObject)dm), dm->defaultGlobalSection, &dm->map);
3590:     PetscSectionViewFromOptions(dm->defaultGlobalSection, NULL, "-global_section_view");
3591:   }
3592:   *section = dm->defaultGlobalSection;
3593:   return(0);
3594: }

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

3601:   Input Parameters:
3602: + dm - The DM
3603: - section - The PetscSection, or NULL

3605:   Level: intermediate

3607:   Note: Any existing Section will be destroyed

3609: .seealso: DMGetDefaultGlobalSection(), DMSetDefaultSection()
3610: @*/
3611: PetscErrorCode DMSetDefaultGlobalSection(DM dm, PetscSection section)
3612: {

3618:   PetscObjectReference((PetscObject)section);
3619:   PetscSectionDestroy(&dm->defaultGlobalSection);
3620:   dm->defaultGlobalSection = section;
3621: #ifdef PETSC_USE_DEBUG
3622:   if (section) {DMDefaultSectionCheckConsistency_Internal(dm, dm->defaultSection, section);}
3623: #endif
3624:   return(0);
3625: }

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

3633:   Input Parameter:
3634: . dm - The DM

3636:   Output Parameter:
3637: . sf - The PetscSF

3639:   Level: intermediate

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

3643: .seealso: DMSetDefaultSF(), DMCreateDefaultSF()
3644: @*/
3645: PetscErrorCode DMGetDefaultSF(DM dm, PetscSF *sf)
3646: {
3647:   PetscInt       nroots;

3653:   PetscSFGetGraph(dm->defaultSF, &nroots, NULL, NULL, NULL);
3654:   if (nroots < 0) {
3655:     PetscSection section, gSection;

3657:     DMGetDefaultSection(dm, &section);
3658:     if (section) {
3659:       DMGetDefaultGlobalSection(dm, &gSection);
3660:       DMCreateDefaultSF(dm, section, gSection);
3661:     } else {
3662:       *sf = NULL;
3663:       return(0);
3664:     }
3665:   }
3666:   *sf = dm->defaultSF;
3667:   return(0);
3668: }

3672: /*@
3673:   DMSetDefaultSF - Set the PetscSF encoding the parallel dof overlap for the DM

3675:   Input Parameters:
3676: + dm - The DM
3677: - sf - The PetscSF

3679:   Level: intermediate

3681:   Note: Any previous SF is destroyed

3683: .seealso: DMGetDefaultSF(), DMCreateDefaultSF()
3684: @*/
3685: PetscErrorCode DMSetDefaultSF(DM dm, PetscSF sf)
3686: {

3692:   PetscSFDestroy(&dm->defaultSF);
3693:   dm->defaultSF = sf;
3694:   return(0);
3695: }

3699: /*@C
3700:   DMCreateDefaultSF - Create the PetscSF encoding the parallel dof overlap for the DM based upon the PetscSections
3701:   describing the data layout.

3703:   Input Parameters:
3704: + dm - The DM
3705: . localSection - PetscSection describing the local data layout
3706: - globalSection - PetscSection describing the global data layout

3708:   Level: intermediate

3710: .seealso: DMGetDefaultSF(), DMSetDefaultSF()
3711: @*/
3712: PetscErrorCode DMCreateDefaultSF(DM dm, PetscSection localSection, PetscSection globalSection)
3713: {
3714:   MPI_Comm       comm;
3715:   PetscLayout    layout;
3716:   const PetscInt *ranges;
3717:   PetscInt       *local;
3718:   PetscSFNode    *remote;
3719:   PetscInt       pStart, pEnd, p, nroots, nleaves = 0, l;
3720:   PetscMPIInt    size, rank;

3724:   PetscObjectGetComm((PetscObject)dm,&comm);
3726:   MPI_Comm_size(comm, &size);
3727:   MPI_Comm_rank(comm, &rank);
3728:   PetscSectionGetChart(globalSection, &pStart, &pEnd);
3729:   PetscSectionGetConstrainedStorageSize(globalSection, &nroots);
3730:   PetscLayoutCreate(comm, &layout);
3731:   PetscLayoutSetBlockSize(layout, 1);
3732:   PetscLayoutSetLocalSize(layout, nroots);
3733:   PetscLayoutSetUp(layout);
3734:   PetscLayoutGetRanges(layout, &ranges);
3735:   for (p = pStart; p < pEnd; ++p) {
3736:     PetscInt gdof, gcdof;

3738:     PetscSectionGetDof(globalSection, p, &gdof);
3739:     PetscSectionGetConstraintDof(globalSection, p, &gcdof);
3740:     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));
3741:     nleaves += gdof < 0 ? -(gdof+1)-gcdof : gdof-gcdof;
3742:   }
3743:   PetscMalloc1(nleaves, &local);
3744:   PetscMalloc1(nleaves, &remote);
3745:   for (p = pStart, l = 0; p < pEnd; ++p) {
3746:     const PetscInt *cind;
3747:     PetscInt       dof, cdof, off, gdof, gcdof, goff, gsize, d, c;

3749:     PetscSectionGetDof(localSection, p, &dof);
3750:     PetscSectionGetOffset(localSection, p, &off);
3751:     PetscSectionGetConstraintDof(localSection, p, &cdof);
3752:     PetscSectionGetConstraintIndices(localSection, p, &cind);
3753:     PetscSectionGetDof(globalSection, p, &gdof);
3754:     PetscSectionGetConstraintDof(globalSection, p, &gcdof);
3755:     PetscSectionGetOffset(globalSection, p, &goff);
3756:     if (!gdof) continue; /* Censored point */
3757:     gsize = gdof < 0 ? -(gdof+1)-gcdof : gdof-gcdof;
3758:     if (gsize != dof-cdof) {
3759:       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);
3760:       cdof = 0; /* Ignore constraints */
3761:     }
3762:     for (d = 0, c = 0; d < dof; ++d) {
3763:       if ((c < cdof) && (cind[c] == d)) {++c; continue;}
3764:       local[l+d-c] = off+d;
3765:     }
3766:     if (gdof < 0) {
3767:       for (d = 0; d < gsize; ++d, ++l) {
3768:         PetscInt offset = -(goff+1) + d, r;

3770:         PetscFindInt(offset,size+1,ranges,&r);
3771:         if (r < 0) r = -(r+2);
3772:         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);
3773:         remote[l].rank  = r;
3774:         remote[l].index = offset - ranges[r];
3775:       }
3776:     } else {
3777:       for (d = 0; d < gsize; ++d, ++l) {
3778:         remote[l].rank  = rank;
3779:         remote[l].index = goff+d - ranges[rank];
3780:       }
3781:     }
3782:   }
3783:   if (l != nleaves) SETERRQ2(comm, PETSC_ERR_PLIB, "Iteration error, l %d != nleaves %d", l, nleaves);
3784:   PetscLayoutDestroy(&layout);
3785:   PetscSFSetGraph(dm->defaultSF, nroots, nleaves, local, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER);
3786:   return(0);
3787: }

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

3794:   Input Parameter:
3795: . dm - The DM

3797:   Output Parameter:
3798: . sf - The PetscSF

3800:   Level: intermediate

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

3804: .seealso: DMSetPointSF(), DMGetDefaultSF(), DMSetDefaultSF(), DMCreateDefaultSF()
3805: @*/
3806: PetscErrorCode DMGetPointSF(DM dm, PetscSF *sf)
3807: {
3811:   *sf = dm->sf;
3812:   return(0);
3813: }

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

3820:   Input Parameters:
3821: + dm - The DM
3822: - sf - The PetscSF

3824:   Level: intermediate

3826: .seealso: DMGetPointSF(), DMGetDefaultSF(), DMSetDefaultSF(), DMCreateDefaultSF()
3827: @*/
3828: PetscErrorCode DMSetPointSF(DM dm, PetscSF sf)
3829: {

3835:   PetscSFDestroy(&dm->sf);
3836:   PetscObjectReference((PetscObject) sf);
3837:   dm->sf = sf;
3838:   return(0);
3839: }

3843: /*@
3844:   DMGetDS - Get the PetscDS

3846:   Input Parameter:
3847: . dm - The DM

3849:   Output Parameter:
3850: . prob - The PetscDS

3852:   Level: developer

3854: .seealso: DMSetDS()
3855: @*/
3856: PetscErrorCode DMGetDS(DM dm, PetscDS *prob)
3857: {
3861:   *prob = dm->prob;
3862:   return(0);
3863: }

3867: /*@
3868:   DMSetDS - Set the PetscDS

3870:   Input Parameters:
3871: + dm - The DM
3872: - prob - The PetscDS

3874:   Level: developer

3876: .seealso: DMGetDS()
3877: @*/
3878: PetscErrorCode DMSetDS(DM dm, PetscDS prob)
3879: {

3885:   PetscObjectReference((PetscObject) prob);
3886:   PetscDSDestroy(&dm->prob);
3887:   dm->prob = prob;
3888:   return(0);
3889: }

3893: PetscErrorCode DMGetNumFields(DM dm, PetscInt *numFields)
3894: {

3899:   PetscDSGetNumFields(dm->prob, numFields);
3900:   return(0);
3901: }

3905: PetscErrorCode DMSetNumFields(DM dm, PetscInt numFields)
3906: {
3907:   PetscInt       Nf, f;

3912:   PetscDSGetNumFields(dm->prob, &Nf);
3913:   for (f = Nf; f < numFields; ++f) {
3914:     PetscContainer obj;

3916:     PetscContainerCreate(PetscObjectComm((PetscObject) dm), &obj);
3917:     PetscDSSetDiscretization(dm->prob, f, (PetscObject) obj);
3918:     PetscContainerDestroy(&obj);
3919:   }
3920:   return(0);
3921: }

3925: /*@
3926:   DMGetField - Return the discretization object for a given DM field

3928:   Not collective

3930:   Input Parameters:
3931: + dm - The DM
3932: - f  - The field number

3934:   Output Parameter:
3935: . field - The discretization object

3937:   Level: developer

3939: .seealso: DMSetField()
3940: @*/
3941: PetscErrorCode DMGetField(DM dm, PetscInt f, PetscObject *field)
3942: {

3947:   PetscDSGetDiscretization(dm->prob, f, field);
3948:   return(0);
3949: }

3953: /*@
3954:   DMSetField - Set the discretization object for a given DM field

3956:   Logically collective on DM

3958:   Input Parameters:
3959: + dm - The DM
3960: . f  - The field number
3961: - field - The discretization object

3963:   Level: developer

3965: .seealso: DMGetField()
3966: @*/
3967: PetscErrorCode DMSetField(DM dm, PetscInt f, PetscObject field)
3968: {

3973:   PetscDSSetDiscretization(dm->prob, f, field);
3974:   return(0);
3975: }

3979: PetscErrorCode DMRestrictHook_Coordinates(DM dm,DM dmc,void *ctx)
3980: {
3981:   DM dm_coord,dmc_coord;
3983:   Vec coords,ccoords;
3984:   Mat inject;
3986:   DMGetCoordinateDM(dm,&dm_coord);
3987:   DMGetCoordinateDM(dmc,&dmc_coord);
3988:   DMGetCoordinates(dm,&coords);
3989:   DMGetCoordinates(dmc,&ccoords);
3990:   if (coords && !ccoords) {
3991:     DMCreateGlobalVector(dmc_coord,&ccoords);
3992:     PetscObjectSetName((PetscObject)ccoords,"coordinates");
3993:     DMCreateInjection(dmc_coord,dm_coord,&inject);
3994:     MatRestrict(inject,coords,ccoords);
3995:     MatDestroy(&inject);
3996:     DMSetCoordinates(dmc,ccoords);
3997:     VecDestroy(&ccoords);
3998:   }
3999:   return(0);
4000: }

4004: static PetscErrorCode DMSubDomainHook_Coordinates(DM dm,DM subdm,void *ctx)
4005: {
4006:   DM dm_coord,subdm_coord;
4008:   Vec coords,ccoords,clcoords;
4009:   VecScatter *scat_i,*scat_g;
4011:   DMGetCoordinateDM(dm,&dm_coord);
4012:   DMGetCoordinateDM(subdm,&subdm_coord);
4013:   DMGetCoordinates(dm,&coords);
4014:   DMGetCoordinates(subdm,&ccoords);
4015:   if (coords && !ccoords) {
4016:     DMCreateGlobalVector(subdm_coord,&ccoords);
4017:     PetscObjectSetName((PetscObject)ccoords,"coordinates");
4018:     DMCreateLocalVector(subdm_coord,&clcoords);
4019:     PetscObjectSetName((PetscObject)clcoords,"coordinates");
4020:     DMCreateDomainDecompositionScatters(dm_coord,1,&subdm_coord,NULL,&scat_i,&scat_g);
4021:     VecScatterBegin(scat_i[0],coords,ccoords,INSERT_VALUES,SCATTER_FORWARD);
4022:     VecScatterBegin(scat_g[0],coords,clcoords,INSERT_VALUES,SCATTER_FORWARD);
4023:     VecScatterEnd(scat_i[0],coords,ccoords,INSERT_VALUES,SCATTER_FORWARD);
4024:     VecScatterEnd(scat_g[0],coords,clcoords,INSERT_VALUES,SCATTER_FORWARD);
4025:     DMSetCoordinates(subdm,ccoords);
4026:     DMSetCoordinatesLocal(subdm,clcoords);
4027:     VecScatterDestroy(&scat_i[0]);
4028:     VecScatterDestroy(&scat_g[0]);
4029:     VecDestroy(&ccoords);
4030:     VecDestroy(&clcoords);
4031:     PetscFree(scat_i);
4032:     PetscFree(scat_g);
4033:   }
4034:   return(0);
4035: }

4039: /*@
4040:   DMGetDimension - Return the topological dimension of the DM

4042:   Not collective

4044:   Input Parameter:
4045: . dm - The DM

4047:   Output Parameter:
4048: . dim - The topological dimension

4050:   Level: beginner

4052: .seealso: DMSetDimension(), DMCreate()
4053: @*/
4054: PetscErrorCode DMGetDimension(DM dm, PetscInt *dim)
4055: {
4059:   *dim = dm->dim;
4060:   return(0);
4061: }

4065: /*@
4066:   DMSetDimension - Set the topological dimension of the DM

4068:   Collective on dm

4070:   Input Parameters:
4071: + dm - The DM
4072: - dim - The topological dimension

4074:   Level: beginner

4076: .seealso: DMGetDimension(), DMCreate()
4077: @*/
4078: PetscErrorCode DMSetDimension(DM dm, PetscInt dim)
4079: {
4083:   dm->dim = dim;
4084:   return(0);
4085: }

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

4092:   Collective on DM

4094:   Input Parameters:
4095: + dm - the DM
4096: - dim - the dimension

4098:   Output Parameters:
4099: + pStart - The first point of the given dimension
4100: . pEnd - The first point following points of the given dimension

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

4107:   Level: intermediate

4109: .keywords: point, Hasse Diagram, dimension
4110: .seealso: DMPLEX, DMPlexGetDepthStratum(), DMPlexGetHeightStratum()
4111: @*/
4112: PetscErrorCode DMGetDimPoints(DM dm, PetscInt dim, PetscInt *pStart, PetscInt *pEnd)
4113: {
4114:   PetscInt       d;

4119:   DMGetDimension(dm, &d);
4120:   if ((dim < 0) || (dim > d)) SETERRQ2(PetscObjectComm((PetscObject) dm), PETSC_ERR_ARG_OUTOFRANGE, "Invalid dimension %d 1", dim, d);
4121:   (*dm->ops->getdimpoints)(dm, dim, pStart, pEnd);
4122:   return(0);
4123: }

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

4130:   Collective on DM

4132:   Input Parameters:
4133: + dm - the DM
4134: - c - coordinate vector

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

4139:   Level: intermediate

4141: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4142: .seealso: DMSetCoordinatesLocal(), DMGetCoordinates(), DMGetCoordinatesLoca(), DMGetCoordinateDM()
4143: @*/
4144: PetscErrorCode DMSetCoordinates(DM dm, Vec c)
4145: {

4151:   PetscObjectReference((PetscObject) c);
4152:   VecDestroy(&dm->coordinates);
4153:   dm->coordinates = c;
4154:   VecDestroy(&dm->coordinatesLocal);
4155:   DMCoarsenHookAdd(dm,DMRestrictHook_Coordinates,NULL,NULL);
4156:   DMSubDomainHookAdd(dm,DMSubDomainHook_Coordinates,NULL,NULL);
4157:   return(0);
4158: }

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

4165:   Collective on DM

4167:    Input Parameters:
4168: +  dm - the DM
4169: -  c - coordinate vector

4171:   Note:
4172:   The coordinates of ghost points can be set using DMSetCoordinates()
4173:   followed by DMGetCoordinatesLocal(). This is intended to enable the
4174:   setting of ghost coordinates outside of the domain.

4176:   Level: intermediate

4178: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4179: .seealso: DMGetCoordinatesLocal(), DMSetCoordinates(), DMGetCoordinates(), DMGetCoordinateDM()
4180: @*/
4181: PetscErrorCode DMSetCoordinatesLocal(DM dm, Vec c)
4182: {

4188:   PetscObjectReference((PetscObject) c);
4189:   VecDestroy(&dm->coordinatesLocal);

4191:   dm->coordinatesLocal = c;

4193:   VecDestroy(&dm->coordinates);
4194:   return(0);
4195: }

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

4202:   Not Collective

4204:   Input Parameter:
4205: . dm - the DM

4207:   Output Parameter:
4208: . c - global coordinate vector

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

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

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

4218:   Level: intermediate

4220: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4221: .seealso: DMSetCoordinates(), DMGetCoordinatesLocal(), DMGetCoordinateDM()
4222: @*/
4223: PetscErrorCode DMGetCoordinates(DM dm, Vec *c)
4224: {

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

4233:     DMGetCoordinateDM(dm, &cdm);
4234:     DMCreateGlobalVector(cdm, &dm->coordinates);
4235:     PetscObjectSetName((PetscObject) dm->coordinates, "coordinates");
4236:     DMLocalToGlobalBegin(cdm, dm->coordinatesLocal, INSERT_VALUES, dm->coordinates);
4237:     DMLocalToGlobalEnd(cdm, dm->coordinatesLocal, INSERT_VALUES, dm->coordinates);
4238:   }
4239:   *c = dm->coordinates;
4240:   return(0);
4241: }

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

4248:   Collective on DM

4250:   Input Parameter:
4251: . dm - the DM

4253:   Output Parameter:
4254: . c - coordinate vector

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

4259:   Each process has the local and ghost coordinates

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

4264:   Level: intermediate

4266: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4267: .seealso: DMSetCoordinatesLocal(), DMGetCoordinates(), DMSetCoordinates(), DMGetCoordinateDM()
4268: @*/
4269: PetscErrorCode DMGetCoordinatesLocal(DM dm, Vec *c)
4270: {

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

4279:     DMGetCoordinateDM(dm, &cdm);
4280:     DMCreateLocalVector(cdm, &dm->coordinatesLocal);
4281:     PetscObjectSetName((PetscObject) dm->coordinatesLocal, "coordinates");
4282:     DMGlobalToLocalBegin(cdm, dm->coordinates, INSERT_VALUES, dm->coordinatesLocal);
4283:     DMGlobalToLocalEnd(cdm, dm->coordinates, INSERT_VALUES, dm->coordinatesLocal);
4284:   }
4285:   *c = dm->coordinatesLocal;
4286:   return(0);
4287: }

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

4294:   Collective on DM

4296:   Input Parameter:
4297: . dm - the DM

4299:   Output Parameter:
4300: . cdm - coordinate DM

4302:   Level: intermediate

4304: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4305: .seealso: DMSetCoordinateDM(), DMSetCoordinates(), DMSetCoordinatesLocal(), DMGetCoordinates(), DMGetCoordinatesLocal()
4306: @*/
4307: PetscErrorCode DMGetCoordinateDM(DM dm, DM *cdm)
4308: {

4314:   if (!dm->coordinateDM) {
4315:     if (!dm->ops->createcoordinatedm) SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Unable to create coordinates for this DM");
4316:     (*dm->ops->createcoordinatedm)(dm, &dm->coordinateDM);
4317:   }
4318:   *cdm = dm->coordinateDM;
4319:   return(0);
4320: }

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

4327:   Logically Collective on DM

4329:   Input Parameters:
4330: + dm - the DM
4331: - cdm - coordinate DM

4333:   Level: intermediate

4335: .keywords: distributed array, get, corners, nodes, local indices, coordinates
4336: .seealso: DMGetCoordinateDM(), DMSetCoordinates(), DMSetCoordinatesLocal(), DMGetCoordinates(), DMGetCoordinatesLocal()
4337: @*/
4338: PetscErrorCode DMSetCoordinateDM(DM dm, DM cdm)
4339: {

4345:   DMDestroy(&dm->coordinateDM);
4346:   dm->coordinateDM = cdm;
4347:   PetscObjectReference((PetscObject) dm->coordinateDM);
4348:   return(0);
4349: }

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

4356:   Not Collective

4358:   Input Parameter:
4359: . dm - The DM object

4361:   Output Parameter:
4362: . dim - The embedding dimension

4364:   Level: intermediate

4366: .keywords: mesh, coordinates
4367: .seealso: DMSetCoordinateDim(), DMGetCoordinateSection(), DMGetCoordinateDM(), DMGetDefaultSection(), DMSetDefaultSection()
4368: @*/
4369: PetscErrorCode DMGetCoordinateDim(DM dm, PetscInt *dim)
4370: {
4374:   if (dm->dimEmbed == PETSC_DEFAULT) {
4375:     dm->dimEmbed = dm->dim;
4376:   }
4377:   *dim = dm->dimEmbed;
4378:   return(0);
4379: }

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

4386:   Not Collective

4388:   Input Parameters:
4389: + dm  - The DM object
4390: - dim - The embedding dimension

4392:   Level: intermediate

4394: .keywords: mesh, coordinates
4395: .seealso: DMGetCoordinateDim(), DMSetCoordinateSection(), DMGetCoordinateSection(), DMGetDefaultSection(), DMSetDefaultSection()
4396: @*/
4397: PetscErrorCode DMSetCoordinateDim(DM dm, PetscInt dim)
4398: {
4401:   dm->dimEmbed = dim;
4402:   return(0);
4403: }

4407: /*@
4408:   DMGetCoordinateSection - Retrieve the layout of coordinate values over the mesh.

4410:   Not Collective

4412:   Input Parameter:
4413: . dm - The DM object

4415:   Output Parameter:
4416: . section - The PetscSection object

4418:   Level: intermediate

4420: .keywords: mesh, coordinates
4421: .seealso: DMGetCoordinateDM(), DMGetDefaultSection(), DMSetDefaultSection()
4422: @*/
4423: PetscErrorCode DMGetCoordinateSection(DM dm, PetscSection *section)
4424: {
4425:   DM             cdm;

4431:   DMGetCoordinateDM(dm, &cdm);
4432:   DMGetDefaultSection(cdm, section);
4433:   return(0);
4434: }

4438: /*@
4439:   DMSetCoordinateSection - Set the layout of coordinate values over the mesh.

4441:   Not Collective

4443:   Input Parameters:
4444: + dm      - The DM object
4445: . dim     - The embedding dimension, or PETSC_DETERMINE
4446: - section - The PetscSection object

4448:   Level: intermediate

4450: .keywords: mesh, coordinates
4451: .seealso: DMGetCoordinateSection(), DMGetDefaultSection(), DMSetDefaultSection()
4452: @*/
4453: PetscErrorCode DMSetCoordinateSection(DM dm, PetscInt dim, PetscSection section)
4454: {
4455:   DM             cdm;

4461:   DMGetCoordinateDM(dm, &cdm);
4462:   DMSetDefaultSection(cdm, section);
4463:   if (dim == PETSC_DETERMINE) {
4464:     PetscInt d = dim;
4465:     PetscInt pStart, pEnd, vStart, vEnd, v, dd;

4467:     PetscSectionGetChart(section, &pStart, &pEnd);
4468:     DMGetDimPoints(dm, 0, &vStart, &vEnd);
4469:     pStart = PetscMax(vStart, pStart);
4470:     pEnd   = PetscMin(vEnd, pEnd);
4471:     for (v = pStart; v < pEnd; ++v) {
4472:       PetscSectionGetDof(section, v, &dd);
4473:       if (dd) {d = dd; break;}
4474:     }
4475:     if (d < 0) d = PETSC_DEFAULT;
4476:     DMSetCoordinateDim(dm, d);
4477:   }
4478:   return(0);
4479: }

4483: /*@C
4484:   DMSetPeriodicity - Set the description of mesh periodicity

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

4492:   Level: developer

4494: .seealso: DMGetPeriodicity()
4495: @*/
4496: PetscErrorCode DMGetPeriodicity(DM dm, const PetscReal **maxCell, const PetscReal **L, const DMBoundaryType **bd)
4497: {
4500:   if (L)       *L       = dm->L;
4501:   if (maxCell) *maxCell = dm->maxCell;
4502:   if (bd)      *bd      = dm->bdtype;
4503:   return(0);
4504: }

4508: /*@C
4509:   DMSetPeriodicity - Set the description of mesh periodicity

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

4517:   Level: developer

4519: .seealso: DMGetPeriodicity()
4520: @*/
4521: PetscErrorCode DMSetPeriodicity(DM dm, const PetscReal maxCell[], const PetscReal L[], const DMBoundaryType bd[])
4522: {
4523:   PetscInt       dim, d;

4529:   PetscFree3(dm->L,dm->maxCell,dm->bdtype);
4530:   DMGetDimension(dm, &dim);
4531:   PetscMalloc3(dim,&dm->L,dim,&dm->maxCell,dim,&dm->bdtype);
4532:   for (d = 0; d < dim; ++d) {dm->L[d] = L[d]; dm->maxCell[d] = maxCell[d]; dm->bdtype[d] = bd[d];}
4533:   return(0);
4534: }

4538: /*@
4539:   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.

4541:   Input Parameters:
4542: + dm     - The DM
4543: - in     - The input coordinate point (dim numbers)

4545:   Output Parameter:
4546: . out - The localized coordinate point

4548:   Level: developer

4550: .seealso: DMLocalizeCoordinates(), DMLocalizeAddCoordinate()
4551: @*/
4552: PetscErrorCode DMLocalizeCoordinate(DM dm, const PetscScalar in[], PetscScalar out[])
4553: {
4554:   PetscInt       dim, d;

4558:   DMGetCoordinateDim(dm, &dim);
4559:   if (!dm->maxCell) {
4560:     for (d = 0; d < dim; ++d) out[d] = in[d];
4561:   } else {
4562:     for (d = 0; d < dim; ++d) {
4563:       out[d] = in[d] - dm->L[d]*floor(PetscRealPart(in[d])/dm->L[d]);
4564:     }
4565:   }
4566:   return(0);
4567: }

4571: /*
4572:   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.

4574:   Input Parameters:
4575: + dm     - The DM
4576: . dim    - The spatial dimension
4577: . anchor - The anchor point, the input point can be no more than maxCell away from it
4578: - in     - The input coordinate point (dim numbers)

4580:   Output Parameter:
4581: . out - The localized coordinate point

4583:   Level: developer

4585:   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

4587: .seealso: DMLocalizeCoordinates(), DMLocalizeAddCoordinate()
4588: */
4589: PetscErrorCode DMLocalizeCoordinate_Internal(DM dm, PetscInt dim, const PetscScalar anchor[], const PetscScalar in[], PetscScalar out[])
4590: {
4591:   PetscInt d;

4594:   if (!dm->maxCell) {
4595:     for (d = 0; d < dim; ++d) out[d] = in[d];
4596:   } else {
4597:     for (d = 0; d < dim; ++d) {
4598:       if (PetscAbsScalar(anchor[d] - in[d]) > dm->maxCell[d]) {
4599:         out[d] = PetscRealPart(anchor[d]) > PetscRealPart(in[d]) ? dm->L[d] + in[d] : in[d] - dm->L[d];
4600:       } else {
4601:         out[d] = in[d];
4602:       }
4603:     }
4604:   }
4605:   return(0);
4606: }
4609: PetscErrorCode DMLocalizeCoordinateReal_Internal(DM dm, PetscInt dim, const PetscReal anchor[], const PetscReal in[], PetscReal out[])
4610: {
4611:   PetscInt d;

4614:   if (!dm->maxCell) {
4615:     for (d = 0; d < dim; ++d) out[d] = in[d];
4616:   } else {
4617:     for (d = 0; d < dim; ++d) {
4618:       if (PetscAbsReal(anchor[d] - in[d]) > dm->maxCell[d]) {
4619:         out[d] = anchor[d] > in[d] ? dm->L[d] + in[d] : in[d] - dm->L[d];
4620:       } else {
4621:         out[d] = in[d];
4622:       }
4623:     }
4624:   }
4625:   return(0);
4626: }

4630: /*
4631:   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.

4633:   Input Parameters:
4634: + dm     - The DM
4635: . dim    - The spatial dimension
4636: . anchor - The anchor point, the input point can be no more than maxCell away from it
4637: . in     - The input coordinate delta (dim numbers)
4638: - out    - The input coordinate point (dim numbers)

4640:   Output Parameter:
4641: . out    - The localized coordinate in + out

4643:   Level: developer

4645:   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

4647: .seealso: DMLocalizeCoordinates(), DMLocalizeCoordinate()
4648: */
4649: PetscErrorCode DMLocalizeAddCoordinate_Internal(DM dm, PetscInt dim, const PetscScalar anchor[], const PetscScalar in[], PetscScalar out[])
4650: {
4651:   PetscInt d;

4654:   if (!dm->maxCell) {
4655:     for (d = 0; d < dim; ++d) out[d] += in[d];
4656:   } else {
4657:     for (d = 0; d < dim; ++d) {
4658:       if (PetscAbsScalar(anchor[d] - in[d]) > dm->maxCell[d]) {
4659:         out[d] += PetscRealPart(anchor[d]) > PetscRealPart(in[d]) ? dm->L[d] + in[d] : in[d] - dm->L[d];
4660:       } else {
4661:         out[d] += in[d];
4662:       }
4663:     }
4664:   }
4665:   return(0);
4666: }

4668: PETSC_EXTERN PetscErrorCode DMPlexGetDepthStratum(DM, PetscInt, PetscInt *, PetscInt *);
4669: PETSC_EXTERN PetscErrorCode DMPlexGetHeightStratum(DM, PetscInt, PetscInt *, PetscInt *);
4670: PETSC_EXTERN PetscErrorCode DMPlexVecGetClosure(DM, PetscSection, Vec, PetscInt, PetscInt *, PetscScalar *[]);
4671: PETSC_EXTERN PetscErrorCode DMPlexVecRestoreClosure(DM, PetscSection, Vec, PetscInt, PetscInt *, PetscScalar *[]);

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

4678:   Input Parameter:
4679: . dm - The DM

4681:   Output Parameter:
4682:   areLocalized - True if localized

4684:   Level: developer

4686: .seealso: DMLocalizeCoordinates()
4687: @*/
4688: PetscErrorCode DMGetCoordinatesLocalized(DM dm,PetscBool *areLocalized)
4689: {
4690:   DM             cdm;
4691:   PetscSection   coordSection;
4692:   PetscInt       cStart, cEnd, c, sStart, sEnd, dof;
4693:   PetscBool      alreadyLocalized, alreadyLocalizedGlobal;

4698:   if (!dm->maxCell) {
4699:     *areLocalized = PETSC_FALSE;
4700:     return(0);
4701:   }
4702:   /* We need some generic way of refering to cells/vertices */
4703:   DMGetCoordinateDM(dm, &cdm);
4704:   {
4705:     PetscBool isplex;

4707:     PetscObjectTypeCompare((PetscObject) cdm, DMPLEX, &isplex);
4708:     if (isplex) {
4709:       DMPlexGetHeightStratum(cdm, 0, &cStart, &cEnd);
4710:     } else SETERRQ(PetscObjectComm((PetscObject) cdm), PETSC_ERR_ARG_WRONG, "Coordinate localization requires a DMPLEX coordinate DM");
4711:   }
4712:   DMGetCoordinateSection(dm, &coordSection);
4713:   PetscSectionGetChart(coordSection,&sStart,&sEnd);
4714:   alreadyLocalized = alreadyLocalizedGlobal = PETSC_TRUE;
4715:   for (c = cStart; c < cEnd; ++c) {
4716:     if (c < sStart || c >= sEnd) {
4717:       alreadyLocalized = PETSC_FALSE;
4718:       break;
4719:     }
4720:     PetscSectionGetDof(coordSection, c, &dof);
4721:     if (!dof) {
4722:       alreadyLocalized = PETSC_FALSE;
4723:       break;
4724:     }
4725:   }
4726:   MPI_Allreduce(&alreadyLocalized,&alreadyLocalizedGlobal,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)dm));
4727:   *areLocalized = alreadyLocalizedGlobal;
4728:   return(0);
4729: }


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

4737:   Input Parameter:
4738: . dm - The DM

4740:   Level: developer

4742: .seealso: DMLocalizeCoordinate(), DMLocalizeAddCoordinate()
4743: @*/
4744: PetscErrorCode DMLocalizeCoordinates(DM dm)
4745: {
4746:   DM             cdm;
4747:   PetscSection   coordSection, cSection;
4748:   Vec            coordinates,  cVec;
4749:   PetscScalar   *coords, *coords2, *anchor, *localized;
4750:   PetscInt       Nc, vStart, vEnd, v, sStart, sEnd, newStart = PETSC_MAX_INT, newEnd = PETSC_MIN_INT, dof, d, off, off2, bs, coordSize;
4751:   PetscBool      alreadyLocalized, alreadyLocalizedGlobal;
4752:   PetscInt       maxHeight = 0, h;
4753:   PetscInt       *pStart = NULL, *pEnd = NULL;

4758:   if (!dm->maxCell) return(0);
4759:   /* We need some generic way of refering to cells/vertices */
4760:   DMGetCoordinateDM(dm, &cdm);
4761:   {
4762:     PetscBool isplex;

4764:     PetscObjectTypeCompare((PetscObject) cdm, DMPLEX, &isplex);
4765:     if (isplex) {
4766:       DMPlexGetDepthStratum(cdm, 0, &vStart, &vEnd);
4767:       DMPlexGetMaxProjectionHeight(cdm,&maxHeight);
4768:       DMGetWorkArray(dm,2*(maxHeight + 1),PETSC_INT,&pStart);
4769:       pEnd = &pStart[maxHeight + 1];
4770:       newStart = vStart;
4771:       newEnd   = vEnd;
4772:       for (h = 0; h <= maxHeight; h++) {
4773:         DMPlexGetHeightStratum(cdm, h, &pStart[h], &pEnd[h]);
4774:         newStart = PetscMin(newStart,pStart[h]);
4775:         newEnd   = PetscMax(newEnd,pEnd[h]);
4776:       }
4777:     } else SETERRQ(PetscObjectComm((PetscObject) cdm), PETSC_ERR_ARG_WRONG, "Coordinate localization requires a DMPLEX coordinate DM");
4778:   }
4779:   DMGetCoordinatesLocal(dm, &coordinates);
4780:   DMGetCoordinateSection(dm, &coordSection);
4781:   VecGetBlockSize(coordinates, &bs);
4782:   PetscSectionGetChart(coordSection,&sStart,&sEnd);

4784:   PetscSectionCreate(PetscObjectComm((PetscObject) dm), &cSection);
4785:   PetscSectionSetNumFields(cSection, 1);
4786:   PetscSectionGetFieldComponents(coordSection, 0, &Nc);
4787:   PetscSectionSetFieldComponents(cSection, 0, Nc);
4788:   PetscSectionSetChart(cSection, newStart, newEnd);

4790:   DMGetWorkArray(dm, 2 * bs, PETSC_SCALAR, &anchor);
4791:   localized = &anchor[bs];
4792:   alreadyLocalized = alreadyLocalizedGlobal = PETSC_TRUE;
4793:   for (h = 0; h <= maxHeight; h++) {
4794:     PetscInt cStart = pStart[h], cEnd = pEnd[h], c;

4796:     for (c = cStart; c < cEnd; ++c) {
4797:       PetscScalar *cellCoords = NULL;
4798:       PetscInt     b;

4800:       if (c < sStart || c >= sEnd) alreadyLocalized = PETSC_FALSE;
4801:       DMPlexVecGetClosure(cdm, coordSection, coordinates, c, &dof, &cellCoords);
4802:       for (b = 0; b < bs; ++b) anchor[b] = cellCoords[b];
4803:       for (d = 0; d < dof/bs; ++d) {
4804:         DMLocalizeCoordinate_Internal(dm, bs, anchor, &cellCoords[d*bs], localized);
4805:         for (b = 0; b < bs; b++) {
4806:           if (cellCoords[d*bs + b] != localized[b]) break;
4807:         }
4808:         if (b < bs) break;
4809:       }
4810:       if (d < dof/bs) {
4811:         if (c >= sStart && c < sEnd) {
4812:           PetscInt cdof;

4814:           PetscSectionGetDof(coordSection, c, &cdof);
4815:           if (cdof != dof) alreadyLocalized = PETSC_FALSE;
4816:         }
4817:         PetscSectionSetDof(cSection, c, dof);
4818:         PetscSectionSetFieldDof(cSection, c, 0, dof);
4819:       }
4820:       DMPlexVecRestoreClosure(cdm, coordSection, coordinates, c, &dof, &cellCoords);
4821:     }
4822:   }
4823:   MPI_Allreduce(&alreadyLocalized,&alreadyLocalizedGlobal,1,MPIU_BOOL,MPI_LAND,PetscObjectComm((PetscObject)dm));
4824:   if (alreadyLocalizedGlobal) {
4825:     DMRestoreWorkArray(dm, 2 * bs, PETSC_SCALAR, &anchor);
4826:     PetscSectionDestroy(&cSection);
4827:     DMRestoreWorkArray(dm,2*(maxHeight + 1),PETSC_INT,&pStart);
4828:     return(0);
4829:   }
4830:   for (v = vStart; v < vEnd; ++v) {
4831:     PetscSectionGetDof(coordSection, v, &dof);
4832:     PetscSectionSetDof(cSection,     v,  dof);
4833:     PetscSectionSetFieldDof(cSection, v, 0, dof);
4834:   }
4835:   PetscSectionSetUp(cSection);
4836:   PetscSectionGetStorageSize(cSection, &coordSize);
4837:   VecCreate(PetscObjectComm((PetscObject) dm), &cVec);
4838:   PetscObjectSetName((PetscObject)cVec,"coordinates");
4839:   VecSetBlockSize(cVec,         bs);
4840:   VecSetSizes(cVec, coordSize, PETSC_DETERMINE);
4841:   VecSetType(cVec,VECSTANDARD);
4842:   VecGetArray(coordinates, &coords);
4843:   VecGetArray(cVec,        &coords2);
4844:   for (v = vStart; v < vEnd; ++v) {
4845:     PetscSectionGetDof(coordSection, v, &dof);
4846:     PetscSectionGetOffset(coordSection, v, &off);
4847:     PetscSectionGetOffset(cSection,     v, &off2);
4848:     for (d = 0; d < dof; ++d) coords2[off2+d] = coords[off+d];
4849:   }
4850:   for (h = 0; h <= maxHeight; h++) {
4851:     PetscInt cStart = pStart[h], cEnd = pEnd[h], c;

4853:     for (c = cStart; c < cEnd; ++c) {
4854:       PetscScalar *cellCoords = NULL;
4855:       PetscInt     b, cdof;

4857:       PetscSectionGetDof(cSection,c,&cdof);
4858:       if (!cdof) continue;
4859:       DMPlexVecGetClosure(cdm, coordSection, coordinates, c, &dof, &cellCoords);
4860:       PetscSectionGetOffset(cSection, c, &off2);
4861:       for (b = 0; b < bs; ++b) anchor[b] = cellCoords[b];
4862:       for (d = 0; d < dof/bs; ++d) {DMLocalizeCoordinate_Internal(dm, bs, anchor, &cellCoords[d*bs], &coords2[off2+d*bs]);}
4863:       DMPlexVecRestoreClosure(cdm, coordSection, coordinates, c, &dof, &cellCoords);
4864:     }
4865:   }
4866:   DMRestoreWorkArray(dm, 2 * bs, PETSC_SCALAR, &anchor);
4867:   DMRestoreWorkArray(dm,2*(maxHeight + 1),PETSC_INT,&pStart);
4868:   VecRestoreArray(coordinates, &coords);
4869:   VecRestoreArray(cVec,        &coords2);
4870:   DMSetCoordinateSection(dm, PETSC_DETERMINE, cSection);
4871:   DMSetCoordinatesLocal(dm, cVec);
4872:   VecDestroy(&cVec);
4873:   PetscSectionDestroy(&cSection);
4874:   return(0);
4875: }

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

4882:   Collective on Vec v (see explanation below)

4884:   Input Parameters:
4885: + dm - The DM
4886: . v - The Vec of points
4887: . ltype - The type of point location, e.g. DM_POINTLOCATION_NONE or DM_POINTLOCATION_NEAREST
4888: - cells - Points to either NULL, or a PetscSF with guesses for which cells contain each point.

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


4895:   Level: developer

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

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

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

4906: $    const PetscSFNode *cells;
4907: $    PetscInt           nFound;
4908: $    const PetscSFNode *found;
4909: $
4910: $    PetscSFGetGraph(cells,NULL,&nFound,&found,&cells);

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

4915: .keywords: point location, mesh
4916: .seealso: DMSetCoordinates(), DMSetCoordinatesLocal(), DMGetCoordinates(), DMGetCoordinatesLocal(), DMPointLocationType
4917: @*/
4918: PetscErrorCode DMLocatePoints(DM dm, Vec v, DMPointLocationType ltype, PetscSF *cellSF)
4919: {

4926:   if (*cellSF) {
4927:     PetscMPIInt result;

4930:     MPI_Comm_compare(PetscObjectComm((PetscObject)v),PetscObjectComm((PetscObject)cellSF),&result);
4931:     if (result != MPI_IDENT && result != MPI_CONGRUENT) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP,"cellSF must have a communicator congruent to v's");
4932:   } else {
4933:     PetscSFCreate(PetscObjectComm((PetscObject)v),cellSF);
4934:   }
4935:   PetscLogEventBegin(DM_LocatePoints,dm,0,0,0);
4936:   if (dm->ops->locatepoints) {
4937:     (*dm->ops->locatepoints)(dm,v,ltype,*cellSF);
4938:   } else SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Point location not available for this DM");
4939:   PetscLogEventEnd(DM_LocatePoints,dm,0,0,0);
4940:   return(0);
4941: }

4945: /*@
4946:   DMGetOutputDM - Retrieve the DM associated with the layout for output

4948:   Input Parameter:
4949: . dm - The original DM

4951:   Output Parameter:
4952: . odm - The DM which provides the layout for output

4954:   Level: intermediate

4956: .seealso: VecView(), DMGetDefaultGlobalSection()
4957: @*/
4958: PetscErrorCode DMGetOutputDM(DM dm, DM *odm)
4959: {
4960:   PetscSection   section;
4961:   PetscBool      hasConstraints, ghasConstraints;

4967:   DMGetDefaultSection(dm, &section);
4968:   PetscSectionHasConstraints(section, &hasConstraints);
4969:   MPI_Allreduce(&hasConstraints, &ghasConstraints, 1, MPIU_BOOL, MPI_LOR, PetscObjectComm((PetscObject) dm));
4970:   if (!ghasConstraints) {
4971:     *odm = dm;
4972:     return(0);
4973:   }
4974:   if (!dm->dmBC) {
4975:     PetscDS      ds;
4976:     PetscSection newSection, gsection;
4977:     PetscSF      sf;

4979:     DMClone(dm, &dm->dmBC);
4980:     DMGetDS(dm, &ds);
4981:     DMSetDS(dm->dmBC, ds);
4982:     PetscSectionClone(section, &newSection);
4983:     DMSetDefaultSection(dm->dmBC, newSection);
4984:     PetscSectionDestroy(&newSection);
4985:     DMGetPointSF(dm->dmBC, &sf);
4986:     PetscSectionCreateGlobalSection(section, sf, PETSC_TRUE, PETSC_FALSE, &gsection);
4987:     DMSetDefaultGlobalSection(dm->dmBC, gsection);
4988:     PetscSectionDestroy(&gsection);
4989:   }
4990:   *odm = dm->dmBC;
4991:   return(0);
4992: }

4996: /*@
4997:   DMGetOutputSequenceNumber - Retrieve the sequence number/value for output

4999:   Input Parameter:
5000: . dm - The original DM

5002:   Output Parameters:
5003: + num - The output sequence number
5004: - val - The output sequence value

5006:   Level: intermediate

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

5011: .seealso: VecView()
5012: @*/
5013: PetscErrorCode DMGetOutputSequenceNumber(DM dm, PetscInt *num, PetscReal *val)
5014: {
5019:   return(0);
5020: }

5024: /*@
5025:   DMSetOutputSequenceNumber - Set the sequence number/value for output

5027:   Input Parameters:
5028: + dm - The original DM
5029: . num - The output sequence number
5030: - val - The output sequence value

5032:   Level: intermediate

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

5037: .seealso: VecView()
5038: @*/
5039: PetscErrorCode DMSetOutputSequenceNumber(DM dm, PetscInt num, PetscReal val)
5040: {
5043:   dm->outputSequenceNum = num;
5044:   dm->outputSequenceVal = val;
5045:   return(0);
5046: }

5050: /*@C
5051:   DMOutputSequenceLoad - Retrieve the sequence value from a Viewer

5053:   Input Parameters:
5054: + dm   - The original DM
5055: . name - The sequence name
5056: - num  - The output sequence number

5058:   Output Parameter:
5059: . val  - The output sequence value

5061:   Level: intermediate

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

5066: .seealso: DMGetOutputSequenceNumber(), DMSetOutputSequenceNumber(), VecView()
5067: @*/
5068: PetscErrorCode DMOutputSequenceLoad(DM dm, PetscViewer viewer, const char *name, PetscInt num, PetscReal *val)
5069: {
5070:   PetscBool      ishdf5;

5077:   PetscObjectTypeCompare((PetscObject) viewer, PETSCVIEWERHDF5, &ishdf5);
5078:   if (ishdf5) {
5079: #if defined(PETSC_HAVE_HDF5)
5080:     PetscScalar value;

5082:     DMSequenceLoad_HDF5(dm, name, num, &value, viewer);
5083:     *val = PetscRealPart(value);
5084: #endif
5085:   } else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerHDF5Open()");
5086:   return(0);
5087: }

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

5094:   Not collective

5096:   Input Parameter:
5097: . dm - The DM

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

5102:   Level: beginner

5104: .seealso: DMSetUseNatural(), DMCreate()
5105: @*/
5106: PetscErrorCode DMGetUseNatural(DM dm, PetscBool *useNatural)
5107: {
5111:   *useNatural = dm->useNatural;
5112:   return(0);
5113: }

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

5120:   Collective on dm

5122:   Input Parameters:
5123: + dm - The DM
5124: - useNatural - The flag to build the mapping to a natural order during distribution

5126:   Level: beginner

5128: .seealso: DMGetUseNatural(), DMCreate()
5129: @*/
5130: PetscErrorCode DMSetUseNatural(DM dm, PetscBool useNatural)
5131: {
5135:   dm->useNatural = useNatural;
5136:   return(0);
5137: }


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

5147:   Not Collective

5149:   Input Parameters:
5150: + dm   - The DM object
5151: - name - The label name

5153:   Level: intermediate

5155: .keywords: mesh
5156: .seealso: DMLabelCreate(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5157: @*/
5158: PetscErrorCode DMCreateLabel(DM dm, const char name[])
5159: {
5160:   DMLabelLink    next  = dm->labels->next;
5161:   PetscBool      flg   = PETSC_FALSE;

5167:   while (next) {
5168:     PetscStrcmp(name, next->label->name, &flg);
5169:     if (flg) break;
5170:     next = next->next;
5171:   }
5172:   if (!flg) {
5173:     DMLabelLink tmpLabel;

5175:     PetscCalloc1(1, &tmpLabel);
5176:     DMLabelCreate(name, &tmpLabel->label);
5177:     tmpLabel->output = PETSC_TRUE;
5178:     tmpLabel->next   = dm->labels->next;
5179:     dm->labels->next = tmpLabel;
5180:   }
5181:   return(0);
5182: }

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

5189:   Not Collective

5191:   Input Parameters:
5192: + dm   - The DM object
5193: . name - The label name
5194: - point - The mesh point

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

5199:   Level: beginner

5201: .keywords: mesh
5202: .seealso: DMLabelGetValue(), DMSetLabelValue(), DMGetStratumIS()
5203: @*/
5204: PetscErrorCode DMGetLabelValue(DM dm, const char name[], PetscInt point, PetscInt *value)
5205: {
5206:   DMLabel        label;

5212:   DMGetLabel(dm, name, &label);
5213:   if (!label) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No label named %s was found", name);
5214:   DMLabelGetValue(label, point, value);
5215:   return(0);
5216: }

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

5223:   Not Collective

5225:   Input Parameters:
5226: + dm   - The DM object
5227: . name - The label name
5228: . point - The mesh point
5229: - value - The label value for this point

5231:   Output Parameter:

5233:   Level: beginner

5235: .keywords: mesh
5236: .seealso: DMLabelSetValue(), DMGetStratumIS(), DMClearLabelValue()
5237: @*/
5238: PetscErrorCode DMSetLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
5239: {
5240:   DMLabel        label;

5246:   DMGetLabel(dm, name, &label);
5247:   if (!label) {
5248:     DMCreateLabel(dm, name);
5249:     DMGetLabel(dm, name, &label);
5250:   }
5251:   DMLabelSetValue(label, point, value);
5252:   return(0);
5253: }

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

5260:   Not Collective

5262:   Input Parameters:
5263: + dm   - The DM object
5264: . name - The label name
5265: . point - The mesh point
5266: - value - The label value for this point

5268:   Output Parameter:

5270:   Level: beginner

5272: .keywords: mesh
5273: .seealso: DMLabelClearValue(), DMSetLabelValue(), DMGetStratumIS()
5274: @*/
5275: PetscErrorCode DMClearLabelValue(DM dm, const char name[], PetscInt point, PetscInt value)
5276: {
5277:   DMLabel        label;

5283:   DMGetLabel(dm, name, &label);
5284:   if (!label) return(0);
5285:   DMLabelClearValue(label, point, value);
5286:   return(0);
5287: }

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

5294:   Not Collective

5296:   Input Parameters:
5297: + dm   - The DM object
5298: - name - The label name

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

5303:   Level: beginner

5305: .keywords: mesh
5306: .seealso: DMLabeGetNumValues(), DMSetLabelValue()
5307: @*/
5308: PetscErrorCode DMGetLabelSize(DM dm, const char name[], PetscInt *size)
5309: {
5310:   DMLabel        label;

5317:   DMGetLabel(dm, name, &label);
5318:   *size = 0;
5319:   if (!label) return(0);
5320:   DMLabelGetNumValues(label, size);
5321:   return(0);
5322: }

5326: /*@C
5327:   DMGetLabelIdIS - Get the integer ids in a label

5329:   Not Collective

5331:   Input Parameters:
5332: + mesh - The DM object
5333: - name - The label name

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

5338:   Level: beginner

5340: .keywords: mesh
5341: .seealso: DMLabelGetValueIS(), DMGetLabelSize()
5342: @*/
5343: PetscErrorCode DMGetLabelIdIS(DM dm, const char name[], IS *ids)
5344: {
5345:   DMLabel        label;

5352:   DMGetLabel(dm, name, &label);
5353:   *ids = NULL;
5354:   if (!label) return(0);
5355:   DMLabelGetValueIS(label, ids);
5356:   return(0);
5357: }

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

5364:   Not Collective

5366:   Input Parameters:
5367: + dm - The DM object
5368: . name - The label name
5369: - value - The stratum value

5371:   Output Parameter:
5372: . size - The stratum size

5374:   Level: beginner

5376: .keywords: mesh
5377: .seealso: DMLabelGetStratumSize(), DMGetLabelSize(), DMGetLabelIds()
5378: @*/
5379: PetscErrorCode DMGetStratumSize(DM dm, const char name[], PetscInt value, PetscInt *size)
5380: {
5381:   DMLabel        label;

5388:   DMGetLabel(dm, name, &label);
5389:   *size = 0;
5390:   if (!label) return(0);
5391:   DMLabelGetStratumSize(label, value, size);
5392:   return(0);
5393: }

5397: /*@C
5398:   DMGetStratumIS - Get the points in a label stratum

5400:   Not Collective

5402:   Input Parameters:
5403: + dm - The DM object
5404: . name - The label name
5405: - value - The stratum value

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

5410:   Level: beginner

5412: .keywords: mesh
5413: .seealso: DMLabelGetStratumIS(), DMGetStratumSize()
5414: @*/
5415: PetscErrorCode DMGetStratumIS(DM dm, const char name[], PetscInt value, IS *points)
5416: {
5417:   DMLabel        label;

5424:   DMGetLabel(dm, name, &label);
5425:   *points = NULL;
5426:   if (!label) return(0);
5427:   DMLabelGetStratumIS(label, value, points);
5428:   return(0);
5429: }

5433: /*@C
5434:   DMGetStratumIS - Set the points in a label stratum

5436:   Not Collective

5438:   Input Parameters:
5439: + dm - The DM object
5440: . name - The label name
5441: . value - The stratum value
5442: - points - The stratum points

5444:   Level: beginner

5446: .keywords: mesh
5447: .seealso: DMLabelSetStratumIS(), DMGetStratumSize()
5448: @*/
5449: PetscErrorCode DMSetStratumIS(DM dm, const char name[], PetscInt value, IS points)
5450: {
5451:   DMLabel        label;

5458:   DMGetLabel(dm, name, &label);
5459:   if (!label) return(0);
5460:   DMLabelSetStratumIS(label, value, points);
5461:   return(0);
5462: }

5466: /*@C
5467:   DMClearLabelStratum - Remove all points from a stratum from a Sieve Label

5469:   Not Collective

5471:   Input Parameters:
5472: + dm   - The DM object
5473: . name - The label name
5474: - value - The label value for this point

5476:   Output Parameter:

5478:   Level: beginner

5480: .keywords: mesh
5481: .seealso: DMLabelClearStratum(), DMSetLabelValue(), DMGetStratumIS(), DMClearLabelValue()
5482: @*/
5483: PetscErrorCode DMClearLabelStratum(DM dm, const char name[], PetscInt value)
5484: {
5485:   DMLabel        label;

5491:   DMGetLabel(dm, name, &label);
5492:   if (!label) return(0);
5493:   DMLabelClearStratum(label, value);
5494:   return(0);
5495: }

5499: /*@
5500:   DMGetNumLabels - Return the number of labels defined by the mesh

5502:   Not Collective

5504:   Input Parameter:
5505: . dm   - The DM object

5507:   Output Parameter:
5508: . numLabels - the number of Labels

5510:   Level: intermediate

5512: .keywords: mesh
5513: .seealso: DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5514: @*/
5515: PetscErrorCode DMGetNumLabels(DM dm, PetscInt *numLabels)
5516: {
5517:   DMLabelLink next = dm->labels->next;
5518:   PetscInt  n    = 0;

5523:   while (next) {++n; next = next->next;}
5524:   *numLabels = n;
5525:   return(0);
5526: }

5530: /*@C
5531:   DMGetLabelName - Return the name of nth label

5533:   Not Collective

5535:   Input Parameters:
5536: + dm - The DM object
5537: - n  - the label number

5539:   Output Parameter:
5540: . name - the label name

5542:   Level: intermediate

5544: .keywords: mesh
5545: .seealso: DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5546: @*/
5547: PetscErrorCode DMGetLabelName(DM dm, PetscInt n, const char **name)
5548: {
5549:   DMLabelLink next = dm->labels->next;
5550:   PetscInt  l    = 0;

5555:   while (next) {
5556:     if (l == n) {
5557:       *name = next->label->name;
5558:       return(0);
5559:     }
5560:     ++l;
5561:     next = next->next;
5562:   }
5563:   SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %D does not exist in this DM", n);
5564: }

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

5571:   Not Collective

5573:   Input Parameters:
5574: + dm   - The DM object
5575: - name - The label name

5577:   Output Parameter:
5578: . hasLabel - PETSC_TRUE if the label is present

5580:   Level: intermediate

5582: .keywords: mesh
5583: .seealso: DMCreateLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5584: @*/
5585: PetscErrorCode DMHasLabel(DM dm, const char name[], PetscBool *hasLabel)
5586: {
5587:   DMLabelLink    next = dm->labels->next;

5594:   *hasLabel = PETSC_FALSE;
5595:   while (next) {
5596:     PetscStrcmp(name, next->label->name, hasLabel);
5597:     if (*hasLabel) break;
5598:     next = next->next;
5599:   }
5600:   return(0);
5601: }

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

5608:   Not Collective

5610:   Input Parameters:
5611: + dm   - The DM object
5612: - name - The label name

5614:   Output Parameter:
5615: . label - The DMLabel, or NULL if the label is absent

5617:   Level: intermediate

5619: .keywords: mesh
5620: .seealso: DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5621: @*/
5622: PetscErrorCode DMGetLabel(DM dm, const char name[], DMLabel *label)
5623: {
5624:   DMLabelLink    next = dm->labels->next;
5625:   PetscBool      hasLabel;

5632:   *label = NULL;
5633:   while (next) {
5634:     PetscStrcmp(name, next->label->name, &hasLabel);
5635:     if (hasLabel) {
5636:       *label = next->label;
5637:       break;
5638:     }
5639:     next = next->next;
5640:   }
5641:   return(0);
5642: }

5646: /*@C
5647:   DMGetLabelByNum - Return the nth label

5649:   Not Collective

5651:   Input Parameters:
5652: + dm - The DM object
5653: - n  - the label number

5655:   Output Parameter:
5656: . label - the label

5658:   Level: intermediate

5660: .keywords: mesh
5661: .seealso: DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5662: @*/
5663: PetscErrorCode DMGetLabelByNum(DM dm, PetscInt n, DMLabel *label)
5664: {
5665:   DMLabelLink next = dm->labels->next;
5666:   PetscInt    l    = 0;

5671:   while (next) {
5672:     if (l == n) {
5673:       *label = next->label;
5674:       return(0);
5675:     }
5676:     ++l;
5677:     next = next->next;
5678:   }
5679:   SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %D does not exist in this DM", n);
5680: }

5684: /*@C
5685:   DMAddLabel - Add the label to this mesh

5687:   Not Collective

5689:   Input Parameters:
5690: + dm   - The DM object
5691: - label - The DMLabel

5693:   Level: developer

5695: .keywords: mesh
5696: .seealso: DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5697: @*/
5698: PetscErrorCode DMAddLabel(DM dm, DMLabel label)
5699: {
5700:   DMLabelLink    tmpLabel;
5701:   PetscBool      hasLabel;

5706:   DMHasLabel(dm, label->name, &hasLabel);
5707:   if (hasLabel) SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Label %s already exists in this DM", label->name);
5708:   PetscCalloc1(1, &tmpLabel);
5709:   tmpLabel->label  = label;
5710:   tmpLabel->output = PETSC_TRUE;
5711:   tmpLabel->next   = dm->labels->next;
5712:   dm->labels->next = tmpLabel;
5713:   return(0);
5714: }

5718: /*@C
5719:   DMRemoveLabel - Remove the label from this mesh

5721:   Not Collective

5723:   Input Parameters:
5724: + dm   - The DM object
5725: - name - The label name

5727:   Output Parameter:
5728: . label - The DMLabel, or NULL if the label is absent

5730:   Level: developer

5732: .keywords: mesh
5733: .seealso: DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5734: @*/
5735: PetscErrorCode DMRemoveLabel(DM dm, const char name[], DMLabel *label)
5736: {
5737:   DMLabelLink    next = dm->labels->next;
5738:   DMLabelLink    last = NULL;
5739:   PetscBool      hasLabel;

5744:   DMHasLabel(dm, name, &hasLabel);
5745:   *label = NULL;
5746:   if (!hasLabel) return(0);
5747:   while (next) {
5748:     PetscStrcmp(name, next->label->name, &hasLabel);
5749:     if (hasLabel) {
5750:       if (last) last->next       = next->next;
5751:       else      dm->labels->next = next->next;
5752:       next->next = NULL;
5753:       *label     = next->label;
5754:       PetscStrcmp(name, "depth", &hasLabel);
5755:       if (hasLabel) {
5756:         dm->depthLabel = NULL;
5757:       }
5758:       PetscFree(next);
5759:       break;
5760:     }
5761:     last = next;
5762:     next = next->next;
5763:   }
5764:   return(0);
5765: }

5769: /*@C
5770:   DMGetLabelOutput - Get the output flag for a given label

5772:   Not Collective

5774:   Input Parameters:
5775: + dm   - The DM object
5776: - name - The label name

5778:   Output Parameter:
5779: . output - The flag for output

5781:   Level: developer

5783: .keywords: mesh
5784: .seealso: DMSetLabelOutput(), DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5785: @*/
5786: PetscErrorCode DMGetLabelOutput(DM dm, const char name[], PetscBool *output)
5787: {
5788:   DMLabelLink    next = dm->labels->next;

5795:   while (next) {
5796:     PetscBool flg;

5798:     PetscStrcmp(name, next->label->name, &flg);
5799:     if (flg) {*output = next->output; return(0);}
5800:     next = next->next;
5801:   }
5802:   SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
5803: }

5807: /*@C
5808:   DMSetLabelOutput - Set the output flag for a given label

5810:   Not Collective

5812:   Input Parameters:
5813: + dm     - The DM object
5814: . name   - The label name
5815: - output - The flag for output

5817:   Level: developer

5819: .keywords: mesh
5820: .seealso: DMGetLabelOutput(), DMCreateLabel(), DMHasLabel(), DMGetLabelValue(), DMSetLabelValue(), DMGetStratumIS()
5821: @*/
5822: PetscErrorCode DMSetLabelOutput(DM dm, const char name[], PetscBool output)
5823: {
5824:   DMLabelLink    next = dm->labels->next;

5830:   while (next) {
5831:     PetscBool flg;

5833:     PetscStrcmp(name, next->label->name, &flg);
5834:     if (flg) {next->output = output; return(0);}
5835:     next = next->next;
5836:   }
5837:   SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "No label named %s was present in this dm", name);
5838: }


5843: /*@
5844:   DMCopyLabels - Copy labels from one mesh to another with a superset of the points

5846:   Collective on DM

5848:   Input Parameter:
5849: . dmA - The DM object with initial labels

5851:   Output Parameter:
5852: . dmB - The DM object with copied labels

5854:   Level: intermediate

5856:   Note: This is typically used when interpolating or otherwise adding to a mesh

5858: .keywords: mesh
5859: .seealso: DMCopyCoordinates(), DMGetCoordinates(), DMGetCoordinatesLocal(), DMGetCoordinateDM(), DMGetCoordinateSection()
5860: @*/
5861: PetscErrorCode DMCopyLabels(DM dmA, DM dmB)
5862: {
5863:   PetscInt       numLabels, l;

5867:   if (dmA == dmB) return(0);
5868:   DMGetNumLabels(dmA, &numLabels);
5869:   for (l = 0; l < numLabels; ++l) {
5870:     DMLabel     label, labelNew;
5871:     const char *name;
5872:     PetscBool   flg;

5874:     DMGetLabelName(dmA, l, &name);
5875:     PetscStrcmp(name, "depth", &flg);
5876:     if (flg) continue;
5877:     DMGetLabel(dmA, name, &label);
5878:     DMLabelDuplicate(label, &labelNew);
5879:     DMAddLabel(dmB, labelNew);
5880:   }
5881:   return(0);
5882: }

5886: /*@
5887:   DMGetCoarseDM - Get the coarse mesh from which this was obtained by refinement

5889:   Input Parameter:
5890: . dm - The DM object

5892:   Output Parameter:
5893: . cdm - The coarse DM

5895:   Level: intermediate

5897: .seealso: DMSetCoarseDM()
5898: @*/
5899: PetscErrorCode DMGetCoarseDM(DM dm, DM *cdm)
5900: {
5904:   *cdm = dm->coarseMesh;
5905:   return(0);
5906: }

5910: /*@
5911:   DMSetCoarseDM - Set the coarse mesh from which this was obtained by refinement

5913:   Input Parameters:
5914: + dm - The DM object
5915: - cdm - The coarse DM

5917:   Level: intermediate

5919: .seealso: DMGetCoarseDM()
5920: @*/
5921: PetscErrorCode DMSetCoarseDM(DM dm, DM cdm)
5922: {

5928:   PetscObjectReference((PetscObject)cdm);
5929:   DMDestroy(&dm->coarseMesh);
5930:   dm->coarseMesh = cdm;
5931:   return(0);
5932: }

5936: /*@
5937:   DMGetFineDM - Get the fine mesh from which this was obtained by refinement

5939:   Input Parameter:
5940: . dm - The DM object

5942:   Output Parameter:
5943: . fdm - The fine DM

5945:   Level: intermediate

5947: .seealso: DMSetFineDM()
5948: @*/
5949: PetscErrorCode DMGetFineDM(DM dm, DM *fdm)
5950: {
5954:   *fdm = dm->fineMesh;
5955:   return(0);
5956: }

5960: /*@
5961:   DMSetFineDM - Set the fine mesh from which this was obtained by refinement

5963:   Input Parameters:
5964: + dm - The DM object
5965: - fdm - The fine DM

5967:   Level: intermediate

5969: .seealso: DMGetFineDM()
5970: @*/
5971: PetscErrorCode DMSetFineDM(DM dm, DM fdm)
5972: {

5978:   PetscObjectReference((PetscObject)fdm);
5979:   DMDestroy(&dm->fineMesh);
5980:   dm->fineMesh = fdm;
5981:   return(0);
5982: }

5984: /*=== DMBoundary code ===*/

5988: PetscErrorCode DMCopyBoundary(DM dm, DM dmNew)
5989: {

5993:   PetscDSCopyBoundary(dm->prob,dmNew->prob);
5994:   return(0);
5995: }

5999: /*@C
6000:   DMAddBoundary - Add a boundary condition to the model

6002:   Input Parameters:
6003: + dm          - The DM, with a PetscDS that matches the problem being constrained
6004: . isEssential - Flag for an essential (Dirichlet) condition, as opposed to a natural (Neumann) condition
6005: . name        - The BC name
6006: . labelname   - The label defining constrained points
6007: . field       - The field to constrain
6008: . numcomps    - The number of constrained field components
6009: . comps       - An array of constrained component numbers
6010: . bcFunc      - A pointwise function giving boundary values
6011: . numids      - The number of DMLabel ids for constrained points
6012: . ids         - An array of ids for constrained points
6013: - ctx         - An optional user context for bcFunc

6015:   Options Database Keys:
6016: + -bc_<boundary name> <num> - Overrides the boundary ids
6017: - -bc_<boundary name>_comp <num> - Overrides the boundary components

6019:   Level: developer

6021: .seealso: DMGetBoundary()
6022: @*/
6023: PetscErrorCode DMAddBoundary(DM dm, PetscBool isEssential, const char name[], const char labelname[], PetscInt field, PetscInt numcomps, const PetscInt *comps, void (*bcFunc)(), PetscInt numids, const PetscInt *ids, void *ctx)
6024: {

6029:   PetscDSAddBoundary(dm->prob,isEssential,name,labelname,field,numcomps,comps,bcFunc,numids,ids,ctx);
6030:   return(0);
6031: }

6035: /*@
6036:   DMGetNumBoundary - Get the number of registered BC

6038:   Input Parameters:
6039: . dm - The mesh object

6041:   Output Parameters:
6042: . numBd - The number of BC

6044:   Level: intermediate

6046: .seealso: DMAddBoundary(), DMGetBoundary()
6047: @*/
6048: PetscErrorCode DMGetNumBoundary(DM dm, PetscInt *numBd)
6049: {

6054:   PetscDSGetNumBoundary(dm->prob,numBd);
6055:   return(0);
6056: }

6060: /*@C
6061:   DMGetBoundary - Add a boundary condition to the model

6063:   Input Parameters:
6064: + dm          - The mesh object
6065: - bd          - The BC number

6067:   Output Parameters:
6068: + isEssential - Flag for an essential (Dirichlet) condition, as opposed to a natural (Neumann) condition
6069: . name        - The BC name
6070: . labelname   - The label defining constrained points
6071: . field       - The field to constrain
6072: . numcomps    - The number of constrained field components
6073: . comps       - An array of constrained component numbers
6074: . bcFunc      - A pointwise function giving boundary values
6075: . numids      - The number of DMLabel ids for constrained points
6076: . ids         - An array of ids for constrained points
6077: - ctx         - An optional user context for bcFunc

6079:   Options Database Keys:
6080: + -bc_<boundary name> <num> - Overrides the boundary ids
6081: - -bc_<boundary name>_comp <num> - Overrides the boundary components

6083:   Level: developer

6085: .seealso: DMAddBoundary()
6086: @*/
6087: PetscErrorCode DMGetBoundary(DM dm, PetscInt bd, PetscBool *isEssential, const char **name, const char **labelname, PetscInt *field, PetscInt *numcomps, const PetscInt **comps, void (**func)(), PetscInt *numids, const PetscInt **ids, void **ctx)
6088: {

6093:   PetscDSGetBoundary(dm->prob,bd,isEssential,name,labelname,field,numcomps,comps,func,numids,ids,ctx);
6094:   return(0);
6095: }

6099: static PetscErrorCode DMPopulateBoundary(DM dm)
6100: {
6101:   DMBoundary *lastnext;
6102:   DSBoundary dsbound;

6106:   dsbound = dm->prob->boundary;
6107:   if (dm->boundary) {
6108:     DMBoundary next = dm->boundary;

6110:     /* quick check to see if the PetscDS has changed */
6111:     if (next->dsboundary == dsbound) return(0);
6112:     /* the PetscDS has changed: tear down and rebuild */
6113:     while (next) {
6114:       DMBoundary b = next;

6116:       next = b->next;
6117:       PetscFree(b);
6118:     }
6119:     dm->boundary = NULL;
6120:   }

6122:   lastnext = &(dm->boundary);
6123:   while (dsbound) {
6124:     DMBoundary dmbound;

6126:     PetscNew(&dmbound);
6127:     dmbound->dsboundary = dsbound;
6128:     DMGetLabel(dm, dsbound->labelname, &(dmbound->label));
6129:     if (!dmbound->label) PetscInfo2(dm, "DSBoundary %s wants label %s, which is not in this dm.\n",dsbound->name,dsbound->labelname);
6130:     /* push on the back instead of the front so that it is in the same order as in the PetscDS */
6131:     *lastnext = dmbound;
6132:     lastnext = &(dmbound->next);
6133:     dsbound = dsbound->next;
6134:   }
6135:   return(0);
6136: }

6140: PetscErrorCode DMIsBoundaryPoint(DM dm, PetscInt point, PetscBool *isBd)
6141: {
6142:   DMBoundary     b;

6148:   *isBd = PETSC_FALSE;
6149:   DMPopulateBoundary(dm);
6150:   b = dm->boundary;
6151:   while (b && !(*isBd)) {
6152:     DMLabel    label = b->label;
6153:     DSBoundary dsb = b->dsboundary;

6155:     if (label) {
6156:       PetscInt i;

6158:       for (i = 0; i < dsb->numids && !(*isBd); ++i) {
6159:         DMLabelStratumHasPoint(label, dsb->ids[i], point, isBd);
6160:       }
6161:     }
6162:     b = b->next;
6163:   }
6164:   return(0);
6165: }

6169: /*@C
6170:   DMProjectFunction - This projects the given function into the function space provided.

6172:   Input Parameters:
6173: + dm      - The DM
6174: . time    - The time
6175: . funcs   - The coordinate functions to evaluate, one per field
6176: . ctxs    - Optional array of contexts to pass to each coordinate function.  ctxs itself may be null.
6177: - mode    - The insertion mode for values

6179:   Output Parameter:
6180: . X - vector

6182:    Calling sequence of func:
6183: $    func(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar u[], void *ctx);

6185: +  dim - The spatial dimension
6186: .  x   - The coordinates
6187: .  Nf  - The number of fields
6188: .  u   - The output field values
6189: -  ctx - optional user-defined function context

6191:   Level: developer

6193: .seealso: DMComputeL2Diff()
6194: @*/
6195: PetscErrorCode DMProjectFunction(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec X)
6196: {
6197:   Vec            localX;

6202:   DMGetLocalVector(dm, &localX);
6203:   DMProjectFunctionLocal(dm, time, funcs, ctxs, mode, localX);
6204:   DMLocalToGlobalBegin(dm, localX, mode, X);
6205:   DMLocalToGlobalEnd(dm, localX, mode, X);
6206:   DMRestoreLocalVector(dm, &localX);
6207:   return(0);
6208: }

6212: PetscErrorCode DMProjectFunctionLocal(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, InsertMode mode, Vec localX)
6213: {

6219:   if (!dm->ops->projectfunctionlocal) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMProjectFunctionLocal",((PetscObject)dm)->type_name);
6220:   (dm->ops->projectfunctionlocal) (dm, time, funcs, ctxs, mode, localX);
6221:   return(0);
6222: }

6226: PetscErrorCode DMProjectFieldLocal(DM dm, Vec localU,
6227:                                    void (**funcs)(PetscInt, PetscInt, PetscInt,
6228:                                                   const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[],
6229:                                                   const PetscInt[], const PetscInt[], const PetscScalar[], const PetscScalar[], const PetscScalar[],
6230:                                                   PetscReal, const PetscReal[], PetscScalar[]),
6231:                                    InsertMode mode, Vec localX)
6232: {

6239:   if (!dm->ops->projectfieldlocal) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMProjectFieldLocal",((PetscObject)dm)->type_name);
6240:   (dm->ops->projectfieldlocal) (dm, localU, funcs, mode, localX);
6241:   return(0);
6242: }

6246: 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)
6247: {

6253:   if (!dm->ops->projectfunctionlabellocal) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMProjectFunctionLabelLocal",((PetscObject)dm)->type_name);
6254:   (dm->ops->projectfunctionlabellocal) (dm, time, label, numIds, ids, funcs, ctxs, mode, localX);
6255:   return(0);
6256: }

6260: /*@C
6261:   DMComputeL2Diff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h.

6263:   Input Parameters:
6264: + dm    - The DM
6265: . time  - The time
6266: . funcs - The functions to evaluate for each field component
6267: . ctxs  - Optional array of contexts to pass to each function, or NULL.
6268: - X     - The coefficient vector u_h

6270:   Output Parameter:
6271: . diff - The diff ||u - u_h||_2

6273:   Level: developer

6275: .seealso: DMProjectFunction(), DMComputeL2FieldDiff(), DMComputeL2GradientDiff()
6276: @*/
6277: PetscErrorCode DMComputeL2Diff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal *diff)
6278: {

6284:   if (!dm->ops->computel2diff) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMComputeL2Diff",((PetscObject)dm)->type_name);
6285:   (dm->ops->computel2diff)(dm,time,funcs,ctxs,X,diff);
6286:   return(0);
6287: }

6291: /*@C
6292:   DMComputeL2GradientDiff - This function computes the L_2 difference between the gradient of a function u and an FEM interpolant solution grad u_h.

6294:   Input Parameters:
6295: + dm    - The DM
6296: , time  - The time
6297: . funcs - The gradient functions to evaluate for each field component
6298: . ctxs  - Optional array of contexts to pass to each function, or NULL.
6299: . X     - The coefficient vector u_h
6300: - n     - The vector to project along

6302:   Output Parameter:
6303: . diff - The diff ||(grad u - grad u_h) . n||_2

6305:   Level: developer

6307: .seealso: DMProjectFunction(), DMComputeL2Diff()
6308: @*/
6309: 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)
6310: {

6316:   if (!dm->ops->computel2gradientdiff) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implement DMComputeL2GradientDiff",((PetscObject)dm)->type_name);
6317:   (dm->ops->computel2gradientdiff)(dm,time,funcs,ctxs,X,n,diff);
6318:   return(0);
6319: }

6323: /*@C
6324:   DMComputeL2FieldDiff - This function computes the L_2 difference between a function u and an FEM interpolant solution u_h, separated into field components.

6326:   Input Parameters:
6327: + dm    - The DM
6328: . time  - The time
6329: . funcs - The functions to evaluate for each field component
6330: . ctxs  - Optional array of contexts to pass to each function, or NULL.
6331: - X     - The coefficient vector u_h

6333:   Output Parameter:
6334: . diff - The array of differences, ||u^f - u^f_h||_2

6336:   Level: developer

6338: .seealso: DMProjectFunction(), DMComputeL2FieldDiff(), DMComputeL2GradientDiff()
6339: @*/
6340: PetscErrorCode DMComputeL2FieldDiff(DM dm, PetscReal time, PetscErrorCode (**funcs)(PetscInt, PetscReal, const PetscReal [], PetscInt, PetscScalar *, void *), void **ctxs, Vec X, PetscReal diff[])
6341: {

6347:   if (!dm->ops->computel2fielddiff) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMComputeL2FieldDiff",((PetscObject)dm)->type_name);
6348:   (dm->ops->computel2fielddiff)(dm,time,funcs,ctxs,X,diff);
6349:   return(0);
6350: }

6354: /*@C
6355:   DMAdaptLabel - Adapt a dm based on a label with values interpreted as coarsening and refining flags.  Specific implementations of DM maybe have
6356:                  specialized flags, but all implementations should accept flag values DM_ADAPT_DETERMINE, DM_ADAPT_KEEP, DM_ADAPT_REFINE, and DM_ADAPT_COARSEN.

6358:   Collective on dm

6360:   Input parameters:
6361: + dm - the pre-adaptation DM object
6362: - label - label with the flags

6364:   Output parameters:
6365: . adaptedDM - the adapted DM object: may be NULL if an adapted DM could not be produced.

6367:   Level: intermediate
6368: @*/
6369: PetscErrorCode DMAdaptLabel(DM dm, DMLabel label, DM *adaptedDM)
6370: {

6377:   *adaptedDM = NULL;
6378:   PetscTryMethod((PetscObject)dm,"DMAdaptLabel_C",(DM,DMLabel, DM*),(dm,label,adaptedDM));
6379:   return(0);
6380: }

6384: /*@C
6385:  DMGetNeighbors - Gets an array containing the MPI rank of all the processes neighbors

6387:  Not Collective

6389:  Input Parameter:
6390:  . dm    - The DM

6392:  Output Parameter:
6393:  . nranks - the number of neighbours
6394:  . ranks - the neighbors ranks

6396:  Notes:
6397:  Do not free the array, it is freed when the DM is destroyed.

6399:  Level: beginner

6401:  .seealso: DMDAGetNeighbors(), PetscSFGetRanks()
6402: @*/
6403: PetscErrorCode DMGetNeighbors(DM dm,PetscInt *nranks,const PetscMPIInt *ranks[])
6404: {

6409:   if (!dm->ops->getneighbors) SETERRQ1(PetscObjectComm((PetscObject)dm),PETSC_ERR_SUP,"DM type %s does not implemnt DMGetNeighbors",((PetscObject)dm)->type_name);
6410:   (dm->ops->getneighbors)(dm,nranks,ranks);
6411:   return(0);
6412: }

6414: #include <petsc/private/matimpl.h> /* Needed because of coloring->ctype below */

6418: /*
6419:     Converts the input vector to a ghosted vector and then calls the standard coloring code.
6420:     This has be a different function because it requires DM which is not defined in the Mat library
6421: */
6422: PetscErrorCode  MatFDColoringApply_AIJDM(Mat J,MatFDColoring coloring,Vec x1,void *sctx)
6423: {

6427:   if (coloring->ctype == IS_COLORING_LOCAL) {
6428:     Vec x1local;
6429:     DM  dm;
6430:     MatGetDM(J,&dm);
6431:     if (!dm) SETERRQ(PetscObjectComm((PetscObject)J),PETSC_ERR_ARG_INCOMP,"IS_COLORING_LOCAL requires a DM");
6432:     DMGetLocalVector(dm,&x1local);
6433:     DMGlobalToLocalBegin(dm,x1,INSERT_VALUES,x1local);
6434:     DMGlobalToLocalEnd(dm,x1,INSERT_VALUES,x1local);
6435:     x1   = x1local;
6436:   }
6437:   MatFDColoringApply_AIJ(J,coloring,x1,sctx);
6438:   if (coloring->ctype == IS_COLORING_LOCAL) {
6439:     DM  dm;
6440:     MatGetDM(J,&dm);
6441:     DMRestoreLocalVector(dm,&x1);
6442:   }
6443:   return(0);
6444: }

6448: /*@
6449:     MatFDColoringUseDM - allows a MatFDColoring object to use the DM associated with the matrix to use a IS_COLORING_LOCAL coloring

6451:     Input Parameter:
6452: .    coloring - the MatFDColoring object

6454:     Developer Notes: this routine exists because the PETSc Mat library does not know about the DM objects

6456: .seealso: MatFDColoring, MatFDColoringCreate(), ISColoringType
6457: @*/
6458: PetscErrorCode  MatFDColoringUseDM(Mat coloring,MatFDColoring fdcoloring)
6459: {
6461:   coloring->ops->fdcoloringapply = MatFDColoringApply_AIJDM;
6462:   return(0);
6463: }