xref: /petsc/src/mat/tests/ex124.c (revision 58d68138c660dfb4e9f5b03334792cd4f2ffd7cc)
1 static char help[] = "Check the difference of the two matrices \n\
2 Reads PETSc matrix A and B, then check B=A-B \n\
3 Input parameters include\n\
4   -fA <input_file> -fB <input_file> \n\n";
5 
6 #include <petscmat.h>
7 
8 int main(int argc, char **args) {
9   Mat         A, B;
10   PetscViewer fd;
11   char        file[2][PETSC_MAX_PATH_LEN];
12   PetscBool   flg;
13   PetscMPIInt size;
14   PetscInt    ma, na, mb, nb;
15 
16   PetscFunctionBeginUser;
17   PetscCall(PetscInitialize(&argc, &args, (char *)0, help));
18   PetscCallMPI(MPI_Comm_size(PETSC_COMM_WORLD, &size));
19   PetscCheck(size == 1, PETSC_COMM_WORLD, PETSC_ERR_WRONG_MPI_SIZE, "This is a uniprocessor example only!");
20 
21   /* read the two matrices, A and B */
22   PetscCall(PetscOptionsGetString(NULL, NULL, "-fA", file[0], sizeof(file[0]), &flg));
23   PetscCheck(flg, PETSC_COMM_WORLD, PETSC_ERR_USER, "Must indicate binary file with the -fA options");
24   PetscCall(PetscOptionsGetString(NULL, NULL, "-fB", file[1], sizeof(file[1]), &flg));
25   PetscCheck(flg, PETSC_COMM_WORLD, PETSC_ERR_USER, "Must indicate binary file with the -fP options");
26 
27   /* Load matrices */
28   PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, file[0], FILE_MODE_READ, &fd));
29   PetscCall(MatCreate(PETSC_COMM_WORLD, &A));
30   PetscCall(MatLoad(A, fd));
31   PetscCall(PetscViewerDestroy(&fd));
32   printf("\n A:\n");
33   printf("----------------------\n");
34   PetscCall(MatView(A, PETSC_VIEWER_STDOUT_WORLD));
35   PetscCall(MatGetSize(A, &ma, &na));
36 
37   PetscCall(PetscViewerBinaryOpen(PETSC_COMM_WORLD, file[1], FILE_MODE_READ, &fd));
38   PetscCall(MatCreate(PETSC_COMM_WORLD, &B));
39   PetscCall(MatLoad(B, fd));
40   PetscCall(PetscViewerDestroy(&fd));
41   printf("\n B:\n");
42   printf("----------------------\n");
43   PetscCall(MatView(B, PETSC_VIEWER_STDOUT_WORLD));
44   PetscCall(MatGetSize(B, &mb, &nb));
45 
46   /* Compute B = -A + B */
47   PetscCheck(ma == mb && na == nb, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "nonconforming matrix size");
48   PetscCall(MatAXPY(B, -1.0, A, DIFFERENT_NONZERO_PATTERN));
49   printf("\n B - A:\n");
50   printf("----------------------\n");
51   PetscCall(MatView(B, PETSC_VIEWER_STDOUT_WORLD));
52 
53   PetscCall(MatDestroy(&B));
54   PetscCall(MatDestroy(&A));
55   PetscCall(PetscFinalize());
56   return 0;
57 }
58