Question

I can't seem to find a way how to efficiently load scipy sparse matrices, e.g. csr_matrix, into a petsc4py matrix, e.g. PETSc.Mat().createAIJ. I found this thread, but I'm not able to apply it.

I would also appreciate a pointer where this stuff is actually documented. The examples in the demo directory only explain a part, and I can't see any docstrings.

Was it helpful?

Solution

Your link says that to create a sparse matrix in PETSc, you should use a command like this:

PETSc.Mat().createAIJ(size=(nrows,ncols), csr=(ai,aj,aa))

According to this, the ai, aj and aa are, in PETSc-speak:

> i - row indices
> j - column indices
> a - matrix values

These are equivalent, respectively, to the .indptr, .indices and .data attributes of a scypy.sparse.csr_matrix, see the docs for details.

So, if your link is right, the following should work:

>>> from petsc4py import PETSc
>>> import scipy.sparse
>>> csr_mat = scipy.sparse.rand(1000, 1000, density=0.001, format='csr')
>>> petsc_mat = PETSc.Mat().createAIJ(size=csr_mat.shape,
...                                   csr=(csr_mat.indptr, csr_mat.indices,
...                                        csr_mat.data))

Unfortunately, I cannot test it myself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top