Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing numpy array to Cython

I am learning Cython. I have problem with passing numpy arrays to Cython and don't really understand what is going on. Could you help me?

I have two simple arrays:

a = np.array([1,2])
b = np.array([[1,4],[3,4]])

I want to compute a dot product of them. In python/numpy everything works fine:

>>> np.dot(a,b)
array([ 7, 12])

I translated the code to Cython (as here: http://docs.cython.org/src/tutorial/numpy.html):

import numpy as np
cimport numpy as np

DTYPE = np.int
ctypedef np.int_t DTYPE_t

def dot(np.ndarray a, np.ndarray b):
    cdef int d = np.dot(a, b)
    return d

It compiled with no problems but returns an error:

>>> dot(a,b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.pyx", line 8, in test.dot (test.c:1262)
    cdef int d = np.dot(a, b)
TypeError: only length-1 arrays can be converted to Python scalars

Could you tell me why and how to do it correctly? Unfortunately Google was not helpful...

Thanks!

like image 744
Tim Avatar asked Nov 20 '13 18:11

Tim


1 Answers

Your result is np.ndarray, not int. It fails trying to convert first one to latter. Do instead

def dot(np.ndarray a, np.ndarray b):
    cdef np.ndarray d = np.dot(a, b)
    return d
like image 169
alko Avatar answered Nov 16 '22 23:11

alko