Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scipy sparse matrices as an input for petsc4py

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.

like image 664
zonksoft Avatar asked Mar 15 '13 21:03

zonksoft


People also ask

How do you create a CSR matrix in python?

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.

What is a CSR sparse matrix?

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.

How do you convert a sparse matrix to dense?

1 Answer. You can use either todense() or toarray() function to convert a CSR matrix to a dense matrix.


1 Answers

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.

like image 189
Jaime Avatar answered Nov 15 '22 13:11

Jaime