Conversion from array to PETSc and from PETSc to array

I would strongly suggest making a minimal code example, as described in Read before posting: How do I get my question answered?
as your question is only about converting a numpy array <-> PETScMatrix, which does not have to include an eigenvalue problem.

In general, you can convert it using the dense array:


from petsc4py import PETSc

def petsc2array(v):
    s=v.getValues(range(0, v.getSize()[0]), range(0,  v.getSize()[1]))
    return s


print(X)
Xpetsc = PETSc.Mat().createDense(X.shape, array=X)

X_back = petsc2array(Xpetsc)
assert(np.allclose(X_back, X))
1 Like