Actual source code: ex2.c

petsc-master 2016-12-07
Report Typos and Errors

  2: static char help[] = "Tests DMDAGlobalToNaturalAllCreate() using contour plotting for 2d DMDAs.\n\n";

  4:  #include <petscdm.h>
  5:  #include <petscdmda.h>
  6:  #include <petscdraw.h>

 10: int main(int argc,char **argv)
 11: {
 12:   PetscInt         i,j,M = 10,N = 8,m = PETSC_DECIDE,n = PETSC_DECIDE;
 13:   PetscMPIInt      rank;
 14:   PetscErrorCode   ierr;
 15:   PetscBool        flg = PETSC_FALSE;
 16:   DM               da;
 17:   PetscViewer      viewer;
 18:   Vec              localall,global;
 19:   PetscScalar      value,*vlocal;
 20:   DMBoundaryType   bx    = DM_BOUNDARY_NONE,by = DM_BOUNDARY_NONE;
 21:   DMDAStencilType  stype = DMDA_STENCIL_BOX;
 22:   VecScatter       tolocalall,fromlocalall;
 23:   PetscInt         start,end;

 25:   PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr;
 26:   PetscViewerDrawOpen(PETSC_COMM_WORLD,0,"",300,0,300,300,&viewer);

 28:   /* Read options */
 29:   PetscOptionsGetInt(NULL,NULL,"-M",&M,NULL);
 30:   PetscOptionsGetInt(NULL,NULL,"-N",&N,NULL);
 31:   PetscOptionsGetInt(NULL,NULL,"-m",&m,NULL);
 32:   PetscOptionsGetInt(NULL,NULL,"-n",&n,NULL);
 33:   PetscOptionsGetBool(NULL,NULL,"-star_stencil",&flg,NULL);
 34:   if (flg) stype = DMDA_STENCIL_STAR;

 36:   /* Create distributed array and get vectors */
 37:   DMDACreate2d(PETSC_COMM_WORLD,bx,by,stype,M,N,m,n,1,1,NULL,NULL,&da);
 38:   DMSetFromOptions(da);
 39:   DMSetUp(da);
 40: 
 41:   DMCreateGlobalVector(da,&global);
 42:   VecCreateSeq(PETSC_COMM_SELF,M*N,&localall);

 44:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
 45:   VecGetOwnershipRange(global,&start,&end);
 46:   for (i=start; i<end; i++) {
 47:     value = 5.0*rank;
 48:     VecSetValues(global,1,&i,&value,INSERT_VALUES);
 49:   }
 50:   VecView(global,viewer);

 52:   /*
 53:      Create Scatter from global DMDA parallel vector to local vector that
 54:    contains all entries
 55:   */
 56:   DMDAGlobalToNaturalAllCreate(da,&tolocalall);
 57:   DMDANaturalAllToGlobalCreate(da,&fromlocalall);

 59:   VecScatterBegin(tolocalall,global,localall,INSERT_VALUES,SCATTER_FORWARD);
 60:   VecScatterEnd(tolocalall,global,localall,INSERT_VALUES,SCATTER_FORWARD);

 62:   VecGetArray(localall,&vlocal);
 63:   for (j=0; j<N; j++) {
 64:     for (i=0; i<M; i++) {
 65:       *vlocal++ += i + j*M;
 66:     }
 67:   }
 68:   VecRestoreArray(localall,&vlocal);

 70:   /* scatter back to global vector */
 71:   VecScatterBegin(fromlocalall,localall,global,INSERT_VALUES,SCATTER_FORWARD);
 72:   VecScatterEnd(fromlocalall,localall,global,INSERT_VALUES,SCATTER_FORWARD);

 74:   VecView(global,viewer);

 76:   /* Free memory */
 77:   VecScatterDestroy(&tolocalall);
 78:   VecScatterDestroy(&fromlocalall);
 79:   PetscViewerDestroy(&viewer);
 80:   VecDestroy(&localall);
 81:   VecDestroy(&global);
 82:   DMDestroy(&da);
 83:   PetscFinalize();
 84:   return ierr;
 85: }