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.nn";
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. */
11: int main(int argc,char **args)
12: {
13: Mat C;
14: PetscScalar v;
15: int i,j,I,J,ierr,Istart,Iend,N,m = 4,n = 4,rank,size;
16: PetscViewer viewer;
17: int MATRIX_GENERATE,MATRIX_READ;
19: PetscInitialize(&argc,&args,(char *)0,help);
20: MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
21: MPI_Comm_size(PETSC_COMM_WORLD,&size);
22: PetscOptionsGetInt(PETSC_NULL,"-m",&m,PETSC_NULL);
23: PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);
24: N = m*n;
26: /* PART 1: Generate matrix, then write it in binary format */
28: PetscLogEventRegister(&MATRIX_GENERATE,"Generate Matrix",0);
29: PetscLogEventBegin(MATRIX_GENERATE,0,0,0,0);
31: /* Generate matrix */
32: MatCreate(PETSC_COMM_WORLD,PETSC_DECIDE,PETSC_DECIDE,N,N,&C);
33: MatSetFromOptions(C);
34: MatGetOwnershipRange(C,&Istart,&Iend);
35: for (I=Istart; I<Iend; I++) {
36: v = -1.0; i = I/n; j = I - i*n;
37: if (i>0) {J = I - n; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
38: if (i<m-1) {J = I + n; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
39: if (j>0) {J = I - 1; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
40: if (j<n-1) {J = I + 1; MatSetValues(C,1,&I,1,&J,&v,ADD_VALUES);}
41: v = 4.0; MatSetValues(C,1,&I,1,&I,&v,ADD_VALUES);
42: }
43: MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);
44: MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);
45: MatView(C,PETSC_VIEWER_STDOUT_WORLD);
47: PetscPrintf(PETSC_COMM_WORLD,"writing matrix in binary to matrix.dat ...n");
48: PetscViewerBinaryOpen(PETSC_COMM_WORLD,"matrix.dat",PETSC_BINARY_CREATE,&viewer);
49: MatView(C,viewer);
50: PetscViewerDestroy(viewer);
51: MatDestroy(C);
52: PetscLogEventEnd(MATRIX_GENERATE,0,0,0,0);
54: /* PART 2: Read in matrix in binary format */
56: /* All processors wait until test matrix has been dumped */
57: MPI_Barrier(PETSC_COMM_WORLD);
59: PetscLogEventRegister(&MATRIX_READ,"Read Matrix",0);
60: PetscLogEventBegin(MATRIX_READ,0,0,0,0);
61: PetscPrintf(PETSC_COMM_WORLD,"reading matrix in binary from matrix.dat ...n");
62: PetscViewerBinaryOpen(PETSC_COMM_WORLD,"matrix.dat",PETSC_BINARY_RDONLY,&viewer);
63: MatLoad(viewer,MATMPIAIJ,&C);
64: PetscViewerDestroy(viewer);
65: PetscLogEventEnd(MATRIX_READ,0,0,0,0);
66: MatView(C,PETSC_VIEWER_STDOUT_WORLD);
68: /* Free data structures */
69: MatDestroy(C);
71: PetscFinalize();
72: return 0;
73: }