Actual source code: ex4.c
1: /*
2: *
3: * Created on: Sep 25, 2017
4: * Author: Fande Kong
5: */
7: static char help[] = "Illustrate the use of MatResetPreallocation.\n";
9: #include "petscmat.h"
11: int main(int argc, char **argv)
12: {
13: Mat A;
14: MPI_Comm comm;
15: PetscInt n = 5, m = 5, *dnnz, *onnz, i, rstart, rend, M, N;
17: PetscFunctionBeginUser;
18: PetscCall(PetscInitialize(&argc, &argv, 0, help));
19: comm = MPI_COMM_WORLD;
20: PetscCall(PetscMalloc2(m, &dnnz, m, &onnz));
21: for (i = 0; i < m; i++) {
22: dnnz[i] = 1;
23: onnz[i] = 1;
24: }
25: PetscCall(MatCreateAIJ(comm, m, n, PETSC_DETERMINE, PETSC_DETERMINE, PETSC_DECIDE, dnnz, PETSC_DECIDE, onnz, &A));
26: PetscCall(MatSetFromOptions(A));
27: PetscCall(MatSetUp(A));
28: PetscCall(PetscFree2(dnnz, onnz));
30: /* since the matrix has never been assembled this reset should do nothing */
31: PetscCall(MatResetPreallocation(A));
33: /* This assembly shrinks memory because we do not insert enough number of values */
34: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
35: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
37: /* MatResetPreallocation() restores the memory required by users */
38: PetscCall(MatResetPreallocation(A));
39: PetscCall(MatSetOption(A, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
40: PetscCall(MatGetOwnershipRange(A, &rstart, &rend));
41: PetscCall(MatGetSize(A, &M, &N));
42: for (i = rstart; i < rend; i++) {
43: PetscCall(MatSetValue(A, i, i, 2.0, INSERT_VALUES));
44: if (rend < N) PetscCall(MatSetValue(A, i, rend, 1.0, INSERT_VALUES));
45: }
46: PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
47: PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
48: PetscCall(MatView(A, PETSC_VIEWER_STDOUT_WORLD));
49: PetscCall(MatDestroy(&A));
50: PetscCall(PetscFinalize());
51: return 0;
52: }
54: /*TEST
56: test:
57: suffix: 1
59: test:
60: suffix: 2
61: nsize: 2
63: TEST*/