xref: /petsc/src/mat/tests/ex194.c (revision 66af8762ec03dbef0e079729eb2a1734a35ed7ff)
1 static char help[] = "Tests MatCreateSubmatrix() with certain entire rows of matrix, modified from ex181.c.";
2 
3 #include <petscmat.h>
4 
5 int main(int argc, char **args)
6 {
7   Mat         C, A;
8   PetscInt    i, j, m = 3, n = 2, rstart, rend, cstart, cend;
9   PetscMPIInt size, rank;
10   PetscScalar v;
11   IS          isrow, iscol;
12 
13   PetscFunctionBeginUser;
14   PetscCall(PetscInitialize(&argc, &args, (char *)0, help));
15   PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
16   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
17   n = 2 * size;
18 
19   PetscCall(MatCreate(PETSC_COMM_WORLD, &C));
20   PetscCall(MatSetSizes(C, PETSC_DECIDE, PETSC_DECIDE, m * n, m * n));
21   PetscCall(MatSetFromOptions(C));
22   PetscCall(MatSetUp(C));
23 
24   /*
25         This is JUST to generate a nice test matrix, all processors fill up
26     the entire matrix. This is not something one would ever do in practice.
27   */
28   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
29   for (i = rstart; i < rend; i++) {
30     for (j = 0; j < m * n; j++) {
31       v = i + j + 1;
32       PetscCall(MatSetValues(C, 1, &i, 1, &j, &v, INSERT_VALUES));
33     }
34   }
35   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
36   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
37   PetscCall(PetscViewerPushFormat(PETSC_VIEWER_STDOUT_WORLD, PETSC_VIEWER_ASCII_COMMON));
38   PetscCall(MatView(C, PETSC_VIEWER_STDOUT_WORLD));
39   PetscCall(PetscViewerPopFormat(PETSC_VIEWER_STDOUT_WORLD));
40 
41   /*
42      Generate a new matrix consisting every column of the original matrix
43   */
44   PetscCall(MatGetOwnershipRange(C, &rstart, &rend));
45   PetscCall(MatGetOwnershipRangeColumn(C, &cstart, &cend));
46 
47   PetscCall(ISCreateStride(PETSC_COMM_WORLD, rend - rstart > 0 ? rend - rstart - 1 : 0, rstart, 1, &isrow));
48   PetscCall(ISCreateStride(PETSC_COMM_WORLD, cend - cstart, cstart, 1, &iscol));
49   PetscCall(MatCreateSubMatrix(C, isrow, NULL, MAT_INITIAL_MATRIX, &A));
50 
51   /* Change C to test the case MAT_REUSE_MATRIX */
52   if (rank == 0) {
53     i = 0;
54     j = 0;
55     v = 100;
56     PetscCall(MatSetValues(C, 1, &i, 1, &j, &v, INSERT_VALUES));
57   }
58   PetscCall(MatAssemblyBegin(C, MAT_FINAL_ASSEMBLY));
59   PetscCall(MatAssemblyEnd(C, MAT_FINAL_ASSEMBLY));
60 
61   PetscCall(MatCreateSubMatrix(C, isrow, NULL, MAT_REUSE_MATRIX, &A));
62   PetscCall(PetscViewerPushFormat(PETSC_VIEWER_STDOUT_WORLD, PETSC_VIEWER_ASCII_COMMON));
63   PetscCall(MatView(A, PETSC_VIEWER_STDOUT_WORLD));
64   PetscCall(PetscViewerPopFormat(PETSC_VIEWER_STDOUT_WORLD));
65 
66   PetscCall(ISDestroy(&isrow));
67   PetscCall(ISDestroy(&iscol));
68   PetscCall(MatDestroy(&A));
69   PetscCall(MatDestroy(&C));
70   PetscCall(PetscFinalize());
71   return 0;
72 }
73 
74 /*TEST
75 
76    test:
77       nsize: 2
78 
79 TEST*/
80