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.
The function csr_matrix() is used to create a sparse matrix of compressed sparse row format whereas csc_matrix() is used to create a sparse matrix of compressed sparse column format.
The compressed sparse row (CSR) or compressed row storage (CRS) or Yale format represents a matrix M by three (one-dimensional) arrays, that respectively contain nonzero values, the extents of rows, and column indices. It is similar to COO, but compresses the row indices, hence the name.
1 Answer. You can use either todense() or toarray() function to convert a CSR matrix to a dense matrix.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With