How to pass scipy.sparse CSR matrix to cython function correctly?

I need to pass the scipy.sparse CSR matrix to a cython function. How to specify type, as for numpy array?

+4
source share
3 answers

The following is an example of quick access to data from coo_matrixusing properties row, coland data. The purpose of the example is simply to show how to declare data types and create buffers (also adding compiler directives that usually give you a significant boost) ...

#cython: boundscheck=False
#cython: wraparound=False
#cython: cdivision=True
#cython: nonecheck=False

import numpy as np
from scipy.sparse import coo_matrix
cimport numpy as np

ctypedef np.int32_t cINT32
ctypedef np.double_t cDOUBLE

def print_sparse(m):
    cdef np.ndarray[cINT, ndim=1] row, col
    cdef np.ndarray[cDOUBLE, ndim=1] data
    cdef int i
    if not isinstance(m, coo_matrix):
        m = coo_matrix(m)
    row = m.row.astype(np.int32)
    col = m.col.astype(np.int32)
    data = m.data.astype(np.float64)
    for i in range(np.shape(data)[0]):
        print row[i], col[i], data[i]
+5
source

@SaulloCastro, .pyx, csr:

def print_csr(m):
    cdef np.ndarray[cINT32, ndim=1] indices, indptr
    cdef np.ndarray[cDOUBLE, ndim=1] data
    cdef int i
    if not isinstance(m, csr_matrix):
        m = csr_matrix(m)
    indices = m.indices.astype(np.int32)
    indptr = m.indptr.astype(np.int32)
    data = m.data.astype(np.float64)
    print indptr
    for i in range(np.shape(data)[0]):
        print indices[i], data[i]

indptr , data, .

csr, coo, :

    for i in range(np.shape(indptr)[0]-1):
        for j in range(indptr[i], indptr[i+1]):
            print i, indices[j], data[j]

, , pyx.

, cython ? csr? coo?

cython numpy? . : x.toarray() ( x.A ).

+2

If you want to access data directly (without copying), you need to specify the type of function argument:

import numpy as np
cimport numpy as np

#cython: boundscheck=False
#cython: wraparound=False
def some_cython_func(np.ndarray[np.double_t] data, np.ndarray[int] indices, np.ndarray[int] indptr):
    #body of of the function

Then you can call this function using

some_cython_func(M.data, M.indices, M.indptr)

where Mis your function CSRor CSC.

See this page for an explanation of passing an argument without casting.

+2
source

All Articles