I'm trying to create and print MATDENSE matrix in PETSc. My MWE looks like this:
static char help[] = "";
#include <petscmat.h>
#include <petscviewer.h>
int main(int argc,char **args)
{
Mat A;
PetscInt Istart,Iend,m = 2,n = 2;
PetscErrorCode ierr;
PetscMPIInt rank,size;
PetscViewer viewer;
ierr = PetscInitialize(&argc,&args,(char*)0,help);if (ierr) return ierr;
ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr);
ierr = PetscOptionsGetInt(NULL,NULL,"-m",&m,NULL);CHKERRQ(ierr);
ierr = PetscOptionsGetInt(NULL,NULL,"-n",&n,NULL);CHKERRQ(ierr);
ierr = MatCreateDense(PETSC_COMM_WORLD, PETSC_DECIDE, PETSC_DECIDE, m, n, NULL, &A); CHKERRQ(ierr);
ierr = MatSetUp(A);CHKERRQ(ierr);
ierr = MatGetOwnershipRange(A,&Istart,&Iend);CHKERRQ(ierr);
MatZeroEntries(A);
printf("rank: %d, istart: %d, iend: %d\n", rank, Istart, Iend);
ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatSetOption(A,MAT_SYMMETRIC,PETSC_TRUE);CHKERRQ(ierr);
ierr = PetscViewerCreate(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr);
ierr = PetscViewerASCIIOpen(PETSC_COMM_WORLD, "out.txt", &viewer);
ierr = MatView(A, viewer); CHKERRQ(ierr);
ierr = MatDestroy(&A);CHKERRQ(ierr);
ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
ierr = PetscFinalize();
return ierr;
}
The problem is, that when running on more that one process, program suddenly hangs on MatView() function instead of writing into out.txt
file. What am I doing wrong here?
This was was caused, strangely enough, by some bug in MPI packages of Lubuntu 18.10. As soon as I updated to Lubuntu 19.04, the problem vanished.
TIP: Always try to run make check
in such case. Set of test will be built and run automatically and you can observe the PETSc behavior without extensive manual trial-and-error.