Actual source code: ex31.c
1: /*$Id: ex31.c,v 1.27 2001/08/07 03:03:07 balay Exp $*/
3: static char help[] = "Tests binary I/O of matrices and illustrates user-defined event logging.\n\n";
5: #include petscmat.h
7: /* Note: Most applications would not read and write the same matrix within
8: the same program. This example is intended only to demonstrate
9: both input and output. */
13: int main(int argc,char **args)
14: {
15: Mat C;
16: PetscScalar v;
17: int i,j,I,J,ierr,Istart,Iend,N,m = 4,n = 4,rank,size;
18: PetscViewer viewer;
19: int MATRIX_GENERATE,MATRIX_READ;
21: PetscInitialize(&argc,&args,(char *)0,help);
22: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
23: MPI_Comm_size(PETSC_COMM_WORLD,&size);
24: PetscOptionsGetInt(PETSC_NULL,"-m",&m,PETSC_NULL);
25: PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);
26: N = m*n;
28: /* PART 1: Generate matrix, then write it in binary format */
30: PetscLogEventRegister(&MATRIX_GENERATE,"Generate Matrix",0);
31: PetscLogEventBegin(MATRIX_GENERATE,0,0,0,0);
33: /* Generate matrix */
34: MatCreate(PETSC_COMM_WORLD,PETSC_DECIDE,PETSC_DECIDE,N,N,&C);
35: MatSetFromOptions(C);
36: MatGetOwnershipRange(C,&Istart,&Iend);
37: for (I=Istart; I<Iend; I++) {
38: v = -1.0; i = I/n; j = I - i*n;
39: if (i>0) {J = I - n; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
40: if (i<m-1) {J = I + n; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
41: if (j>0) {J = I - 1; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
42: if (j<n-1) {J = I + 1; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
43: v = 4.0; MatSetValues(C,1,&I,1,&I,&v,ADD_VALUES);
44: }
45: MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
46: MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
47: MatView(C,PETSC_VIEWER_STDOUT_WORLD);
49: PetscPrintf(PETSC_COMM_WORLD,"writing matrix in binary to matrix.dat ...\n");
50: PetscViewerBinaryOpen(PETSC_COMM_WORLD,"matrix.dat",PETSC_FILE_CREATE,&viewer);
51: MatView(C,viewer);
52: PetscViewerDestroy(viewer);
53: MatDestroy(C);
54: PetscLogEventEnd(MATRIX_GENERATE,0,0,0,0);
56: /* PART 2: Read in matrix in binary format */
58: /* All processors wait until test matrix has been dumped */
59: MPI_Barrier(PETSC_COMM_WORLD);
61: PetscLogEventRegister(&MATRIX_READ,"Read Matrix",0);
62: PetscLogEventBegin(MATRIX_READ,0,0,0,0);
63: PetscPrintf(PETSC_COMM_WORLD,"reading matrix in binary from matrix.dat ...\n");
64: PetscViewerBinaryOpen(PETSC_COMM_WORLD,"matrix.dat",PETSC_FILE_RDONLY,&viewer);
65: MatLoad(viewer,MATAIJ,&C);
66: PetscViewerDestroy(viewer);
67: PetscLogEventEnd(MATRIX_READ,0,0,0,0);
68: MatView(C,PETSC_VIEWER_STDOUT_WORLD);
70: /* Free data structures */
71: MatDestroy(C);
73: PetscFinalize();
74: return 0;
75: }