Actual source code: ex5.c

      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:   PetscEvent     VECTOR_GENERATE,VECTOR_READ;

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

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

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

     46:   PetscPrintf(PETSC_COMM_WORLD,"writing vector in binary to vector.dat ...\n");

     48:   PetscViewerBinaryOpen(PETSC_COMM_WORLD,"vector.dat",PETSC_FILE_CREATE,&viewer);
     49:   VecView(u,viewer);
     50:   PetscViewerDestroy(viewer);
     51:   VecDestroy(u);
     52:   PetscLogEventEnd(VECTOR_GENERATE,0,0,0,0);

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

     56:   /* All processors wait until test vector has been dumped */
     57:   MPI_Barrier(PETSC_COMM_WORLD);
     58:   PetscSleep(10);

     60:   /* Read new vector in binary format */
     61:   PetscLogEventRegister(&VECTOR_READ,"Read Vector",VEC_COOKIE);
     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",PETSC_FILE_RDONLY,&viewer);
     65:   VecLoad(viewer,PETSC_NULL,&u);
     66:   PetscViewerDestroy(viewer);
     67:   PetscLogEventEnd(VECTOR_READ,0,0,0,0);
     68:   VecView(u,PETSC_VIEWER_STDOUT_WORLD);

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