Actual source code: ex5.c

petsc-3.4.5 2014-06-29
  2: static char help[] = "Tests binary I/O of vectors and illustrates the use of user-defined event logging.\n\n";

  4: #include <petscvec.h>

  6: /* Note:  Most applications would not read and write a vector within
  7:   the same program.  This example is intended only to demonstrate
  8:   both input and output. */

 12: int main(int argc,char **args)
 13: {
 15:   PetscMPIInt    rank,size;
 16:   PetscInt       i,m = 10,low,high,ldim,iglobal;
 17:   PetscScalar    v;
 18:   Vec            u;
 19:   PetscViewer    viewer;
 20: #if defined(PETSC_USE_LOG)
 21:   PetscLogEvent  VECTOR_GENERATE,VECTOR_READ;
 22: #endif

 24:   PetscInitialize(&argc,&args,(char*)0,help);
 25:   MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
 26:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
 27:   PetscOptionsGetInt(NULL,"-m",&m,NULL);

 29:   /* PART 1:  Generate vector, then write it in binary format */

 31:   PetscLogEventRegister("Generate Vector",VEC_CLASSID,&VECTOR_GENERATE);
 32:   PetscLogEventBegin(VECTOR_GENERATE,0,0,0,0);
 33:   /* Generate vector */
 34:   VecCreate(PETSC_COMM_WORLD,&u);
 35:   VecSetSizes(u,PETSC_DECIDE,m);
 36:   VecSetFromOptions(u);
 37:   VecGetOwnershipRange(u,&low,&high);
 38:   VecGetLocalSize(u,&ldim);
 39:   for (i=0; i<ldim; i++) {
 40:     iglobal = i + low;
 41:     v       = (PetscScalar)(i + 100*rank);
 42:     VecSetValues(u,1,&iglobal,&v,INSERT_VALUES);
 43:   }
 44:   VecAssemblyBegin(u);
 45:   VecAssemblyEnd(u);
 46:   VecView(u,PETSC_VIEWER_STDOUT_WORLD);

 48:   PetscPrintf(PETSC_COMM_WORLD,"writing vector in binary to vector.dat ...\n");
 49:   PetscViewerBinaryOpen(PETSC_COMM_WORLD,"vector.dat",FILE_MODE_WRITE,&viewer);
 50:   VecView(u,viewer);
 51:   PetscViewerDestroy(&viewer);
 52:   VecDestroy(&u);
 53:   /*  PetscOptionsClear();*/
 54:   PetscOptionsSetValue("-viewer_binary_mpiio","");

 56:   PetscLogEventEnd(VECTOR_GENERATE,0,0,0,0);

 58:   /* PART 2:  Read in vector in binary format */

 60:   /* Read new vector in binary format */
 61:   PetscLogEventRegister("Read Vector",VEC_CLASSID,&VECTOR_READ);
 62:   PetscLogEventBegin(VECTOR_READ,0,0,0,0);
 63:   PetscPrintf(PETSC_COMM_WORLD,"reading vector in binary from vector.dat ...\n");
 64:   PetscViewerBinaryOpen(PETSC_COMM_WORLD,"vector.dat",FILE_MODE_READ,&viewer);
 65:   VecCreate(PETSC_COMM_WORLD,&u);
 66:   VecLoad(u,viewer);
 67:   PetscViewerDestroy(&viewer);
 68:   PetscLogEventEnd(VECTOR_READ,0,0,0,0);
 69:   VecView(u,PETSC_VIEWER_STDOUT_WORLD);

 71:   /* Free data structures */
 72:   VecDestroy(&u);
 73:   PetscFinalize();
 74:   return 0;
 75: }