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,&C);
36: MatSetSizes(C,PETSC_DECIDE,PETSC_DECIDE,N,N);
37: MatSetFromOptions(C);
38: MatGetOwnershipRange(C,&Istart,&Iend);
39: for (I=Istart; I<Iend; I++) {
40: v = -1.0; i = I/n; j = I - i*n;
41: if (i>0) {J = I - n; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
42: if (i<m-1) {J = I + n; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
43: if (j>0) {J = I - 1; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
44: if (j<n-1) {J = I + 1; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
45: v = 4.0; MatSetValues(C,1,&I,1,&I,&v,ADD_VALUES);
46: }
47: MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
48: MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
49: MatView(C,PETSC_VIEWER_STDOUT_WORLD);
51: PetscPrintf(PETSC_COMM_WORLD,"writing matrix in binary to matrix.dat ...\n");
52: PetscViewerBinaryOpen(PETSC_COMM_WORLD,"matrix.dat",FILE_MODE_WRITE,&viewer);
53: MatView(C,viewer);
54: PetscViewerDestroy(viewer);
55: MatDestroy(C);
56: PetscLogEventEnd(MATRIX_GENERATE,0,0,0,0);
58: /* PART 2: Read in matrix in binary format */
60: /* All processors wait until test matrix has been dumped */
61: MPI_Barrier(PETSC_COMM_WORLD);
63: PetscLogEventRegister(&MATRIX_READ,"Read Matrix",0);
64: PetscLogEventBegin(MATRIX_READ,0,0,0,0);
65: PetscPrintf(PETSC_COMM_WORLD,"reading matrix in binary from matrix.dat ...\n");
66: PetscViewerBinaryOpen(PETSC_COMM_WORLD,"matrix.dat",FILE_MODE_READ,&viewer);
67: MatLoad(viewer,MATAIJ,&C);
68: PetscViewerDestroy(viewer);
69: PetscLogEventEnd(MATRIX_READ,0,0,0,0);
70: MatView(C,PETSC_VIEWER_STDOUT_WORLD);
72: /* Free data structures */
73: MatDestroy(C);
75: PetscFinalize();
76: return 0;
77: }