Actual source code: ex31.c

  2: static char help[] = "Tests binary I/O of matrices and illustrates user-defined event logging.\n\n";

 4:  #include petscmat.h

  6: /* Note:  Most applications would not read and write the same matrix 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: {
 14:   Mat            C;
 15:   PetscScalar    v;
 16:   PetscInt       i,j,I,J,Istart,Iend,N,m = 4,n = 4;
 17:   PetscMPIInt    rank,size;
 19:   PetscViewer    viewer;
 20:   PetscEvent     MATRIX_GENERATE,MATRIX_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);
 26:   PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);
 27:   N = m*n;

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

 31:   PetscLogEventRegister(&MATRIX_GENERATE,"Generate Matrix",0);
 32:   PetscLogEventBegin(MATRIX_GENERATE,0,0,0,0);

 34:   /* Generate matrix */
 35:   MatCreate(PETSC_COMM_WORLD,PETSC_DECIDE,PETSC_DECIDE,N,N,&C);
 36:   MatSetFromOptions(C);
 37:   MatGetOwnershipRange(C,&Istart,&Iend);
 38:   for (I=Istart; I<Iend; I++) {
 39:     v = -1.0; i = I/n; j = I - i*n;
 40:     if (i>0)   {J = I - n; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
 41:     if (i<m-1) {J = I + n; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
 42:     if (j>0)   {J = I - 1; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
 43:     if (j<n-1) {J = I + 1; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
 44:     v = 4.0; MatSetValues(C,1,&I,1,&I,&v,ADD_VALUES);
 45:   }
 46:   MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
 47:   MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
 48:   MatView(C,PETSC_VIEWER_STDOUT_WORLD);

 50:   PetscPrintf(PETSC_COMM_WORLD,"writing matrix in binary to matrix.dat ...\n");
 51:   PetscViewerBinaryOpen(PETSC_COMM_WORLD,"matrix.dat",PETSC_FILE_CREATE,&viewer);
 52:   MatView(C,viewer);
 53:   PetscViewerDestroy(viewer);
 54:   MatDestroy(C);
 55:   PetscLogEventEnd(MATRIX_GENERATE,0,0,0,0);

 57:   /* PART 2:  Read in matrix in binary format */

 59:   /* All processors wait until test matrix has been dumped */
 60:   MPI_Barrier(PETSC_COMM_WORLD);

 62:   PetscLogEventRegister(&MATRIX_READ,"Read Matrix",0);
 63:   PetscLogEventBegin(MATRIX_READ,0,0,0,0);
 64:   PetscPrintf(PETSC_COMM_WORLD,"reading matrix in binary from matrix.dat ...\n");
 65:   PetscViewerBinaryOpen(PETSC_COMM_WORLD,"matrix.dat",PETSC_FILE_RDONLY,&viewer);
 66:   MatLoad(viewer,MATAIJ,&C);
 67:   PetscViewerDestroy(viewer);
 68:   PetscLogEventEnd(MATRIX_READ,0,0,0,0);
 69:   MatView(C,PETSC_VIEWER_STDOUT_WORLD);

 71:   /* Free data structures */
 72:   MatDestroy(C);

 74:   PetscFinalize();
 75:   return 0;
 76: }