Actual source code: ex10.c

petsc-3.5.4 2015-05-23
Report Typos and Errors
  1: /*
  2:    Demonstrates using the HDF5 viewer with a DMDA Vec
  3:  - create a global vector containing a gauss profile (exp(-x^2-y^2))
  4:  - write the global vector in a hdf5 file

  6:    The resulting file gauss.h5 can be viewed with Visit (an open source visualization package)
  7:    Or with some versions of MATLAB with data=hdfread('gauss.h5','pressure'); mesh(data);

  9:    The file storage of the vector is independent of the number of processes used.
 10:  */

 12: #include <petscdm.h>
 13: #include <petscdmda.h>
 14: #include <petscsys.h>
 15: #include <petscviewerhdf5.h>

 17: static char help[] = "Test to write HDF5 file from PETSc DMDA Vec.\n\n";

 19: int main(int argc,char **argv)
 20: {
 22:   DM             da2D;
 23:   PetscInt       i,j,ixs, ixm, iys, iym;;
 24:   PetscViewer    H5viewer;
 25:   PetscScalar    xm    = -1.0, xp=1.0;
 26:   PetscScalar    ym    = -1.0, yp=1.0;
 27:   PetscScalar    value = 1.0,dx,dy;
 28:   PetscInt       Nx    = 40, Ny=40;
 29:   Vec            gauss;
 30:   PetscScalar    **gauss_ptr;

 32:   dx=(xp-xm)/(Nx-1);
 33:   dy=(yp-ym)/(Ny-1);

 35:   /* Initialize the Petsc context */
 36:   PetscInitialize(&argc,&argv,(char*)0,help);

 38:   /* Build of the DMDA */
 39:   DMDACreate2d(PETSC_COMM_WORLD, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE,DMDA_STENCIL_STAR,Nx,Ny,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da2D);

 41:   /* Set the coordinates */
 42:   DMDASetUniformCoordinates(da2D, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0);

 44:   /* Declare gauss as a DMDA component */
 45:   DMCreateGlobalVector(da2D,&gauss);
 46:   PetscObjectSetName((PetscObject) gauss, "pressure");

 48:   /* Initialize vector gauss with a constant value (=1) */
 49:   VecSet(gauss,value);

 51:   /* Get the coordinates of the corners for each process */
 52:   DMDAGetCorners(da2D, &ixs, &iys, 0, &ixm, &iym, 0);

 54:   /* Build the gaussian profile (exp(-x^2-y^2)) */
 55:   DMDAVecGetArray(da2D,gauss,&gauss_ptr);
 56:   for (j=iys; j<iys+iym; j++) {
 57:     for (i=ixs; i<ixs+ixm; i++) {
 58:       gauss_ptr[j][i]=PetscExpScalar(-(xm+i*dx)*(xm+i*dx)-(ym+j*dy)*(ym+j*dy));
 59:     }
 60:   }
 61:   DMDAVecRestoreArray(da2D,gauss,&gauss_ptr);

 63:   /* Create the HDF5 viewer */
 64:   PetscViewerHDF5Open(PETSC_COMM_WORLD,"gauss.h5",FILE_MODE_WRITE,&H5viewer);

 66:   /* Write the H5 file */
 67:   VecView(gauss,H5viewer);

 69:   /* Cleaning stage */
 70:   PetscViewerDestroy(&H5viewer);
 71:   VecDestroy(&gauss);
 72:   DMDestroy(&da2D);
 73:   PetscFinalize();
 74:   return 0;
 75: }