0
votes

I am having a very weird error when I cast a numpy ndarray from one type to the other in Cython. For instance when I write the following convert_test.pyx:

cimport cython
import numpy as np
cimport numpy as np

DTYPE = np.float32
ctypedef np.float32_t DTYPE_t

def convert_to_int(np.ndarray[DTYPE_t, ndim=2] float_matrix):
    cdef np.ndarray[np.int, ndim=2] int_matrix=float_matrix.astype(np.int)
    return int_matrix

compile it and test:

from convert_test import convert_to_int
a_int=convert_to_int(np.zeros((2,2)).astype(np.float32))

I got the very familiar message:

ValueError: Buffer dtype mismatch, expected 'int object' but got 'long'

It is probably super obvious but I don't quite see it yet.

2
Python 3 doesn't have an int type. It has been implemented as long. So, maybe you should convert to long instead of int. Although, I have no experience with Cython, so I can't say if it would work. - xyres
I am using python2 but maybe you are on to something. - jeandut
@jean See my answer this works making memoryviews of different types in Cython. If you really want ndarray format I can write that out for you but it should be pretty intuitive if you compare my 2nd sample to the 1st sample. Also note that just casting from a single to an int it truncates the decimal points (no rounding) so this function may not be what you intend to do... - Matt

2 Answers

0
votes

You have to use _t types in your declaration: cdef np.ndarray[np.int_t, ndim=2].

0
votes

Why don't you just do this? Compiles and works just fine on my computer:

cimport cython
import numpy as np
cimport numpy as np

DTYPE = np.float32
ctypedef np.float32_t DTYPE_t

def convert_to_int(np.ndarray[DTYPE_t, ndim=2] float_matrix):
    int_matrix = np.array(float_matrix, dtype=np.int32)
    return int_matrix

Or if you really want a memoryview:

def convert_to_int(DTYPE_t[:,:] float_matrix):
    cdef int[:,:] int_matrix = np.array(float_matrix, dtype=np.int32)
    return np.asarray(int_matrix)

The second answer I just converted the older ndarray parameters to the modern typed memoryviews syntax for int_matrix and float_matrix. The style above is your contiguous memory format [:,:] for a matrix (like NumPy defaults to with numpy.zeros for example).

Note that the function you posted is just going to truncate everything after the decimal point (no rounding up/down) so be sure that's what you intended.