# How to convert MPIAIJ to SEQAIJ matrix in petsc/petsc4py?

I am curious, if there is a function to convert MPIAIJ (distributed matrices in AIJ format) to a SEQAIJ matrix that lie on a single processor. It is possible to do such an operation for PETSc vectors with VecScatterCreateToAll or VecScatterCreateToZero, but I couldn't find a similar function for matrices. It is not a scalable operation obviously, but can be helpful for debugging easily.

Naively, I thought the following will work, but the problem with this code is that every process generate a different SEQAIJ matrix. Interestingly, petsc4py doesn't generate an error, but simply leaves the matrix with all zeros.

#Input A is an MPIAIJ matrix
def getSEQAIJ(A):
N=A.getSize()[0]
B=PETSc.Mat().create(comm=PETSc.COMM_SELF)
B.setType(PETSc.Mat.Type.SEQAIJ)
B.setSizes(N)
B.setUp()
rstart, rend = A.getOwnershipRange()
for i in xrange(rstart,rend):
cols,vals = A.getRow(i) #maybe restore later

I haven't used PETSc via Python, but I suppose you can use all the functions provided by PETSc. Then you can use MatGetSubmatrices() on your processor 0 to obtain all rows and columns, thus obtaining a local copy.