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. */
10: int main(int argc, char **args)
11: {
12: Mat C;
13: PetscScalar v;
14: PetscInt i, j, Ii, J, Istart, Iend, N, m = 4, n = 4;
15: PetscMPIInt rank, size;
16: PetscViewer viewer;
17: #if defined(PETSC_USE_LOG)
18: PetscLogEvent MATRIX_GENERATE, MATRIX_READ;
19: #endif
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(NULL, NULL, "-m", &m, NULL);
26: PetscOptionsGetInt(NULL, NULL, "-n", &n, NULL);
27: N = m * n;
29: /* PART 1: Generate matrix, then write it in binary format */
31: PetscLogEventRegister("Generate Matrix", 0, &MATRIX_GENERATE);
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: MatSetUp(C);
39: MatGetOwnershipRange(C, &Istart, &Iend);
40: for (Ii = Istart; Ii < Iend; Ii++) {
41: v = -1.0;
42: i = Ii / n;
43: j = Ii - i * n;
44: if (i > 0) {
45: J = Ii - n;
46: MatSetValues(C, 1, &Ii, 1, &J, &v, ADD_VALUES);
47: }
48: if (i < m - 1) {
49: J = Ii + n;
50: MatSetValues(C, 1, &Ii, 1, &J, &v, ADD_VALUES);
51: }
52: if (j > 0) {
53: J = Ii - 1;
54: MatSetValues(C, 1, &Ii, 1, &J, &v, ADD_VALUES);
55: }
56: if (j < n - 1) {
57: J = Ii + 1;
58: MatSetValues(C, 1, &Ii, 1, &J, &v, ADD_VALUES);
59: }
60: v = 4.0;
61: MatSetValues(C, 1, &Ii, 1, &Ii, &v, ADD_VALUES);
62: }
63: MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY);
64: MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY);
65: MatView(C, PETSC_VIEWER_STDOUT_WORLD);
67: PetscPrintf(PETSC_COMM_WORLD, "writing matrix in binary to matrix.dat ...\n");
68: PetscViewerBinaryOpen(PETSC_COMM_WORLD, "matrix.dat", FILE_MODE_WRITE, &viewer);
69: MatView(C, viewer);
70: PetscViewerDestroy(&viewer);
71: MatDestroy(&C);
72: PetscLogEventEnd(MATRIX_GENERATE, 0, 0, 0, 0);
74: /* PART 2: Read in matrix in binary format */
76: /* All processors wait until test matrix has been dumped */
77: MPI_Barrier(PETSC_COMM_WORLD);
79: PetscLogEventRegister("Read Matrix", 0, &MATRIX_READ);
80: PetscLogEventBegin(MATRIX_READ, 0, 0, 0, 0);
81: PetscPrintf(PETSC_COMM_WORLD, "reading matrix in binary from matrix.dat ...\n");
82: PetscViewerBinaryOpen(PETSC_COMM_WORLD, "matrix.dat", FILE_MODE_READ, &viewer);
83: MatCreate(PETSC_COMM_WORLD, &C);
84: MatLoad(C, viewer);
85: PetscViewerDestroy(&viewer);
86: PetscLogEventEnd(MATRIX_READ, 0, 0, 0, 0);
87: MatView(C, PETSC_VIEWER_STDOUT_WORLD);
89: /* Free data structures */
90: MatDestroy(&C);
92: PetscFinalize();
93: return 0;
94: }
96: /*TEST
98: test:
99: filter: grep -v " MPI process"
101: TEST*/