Marc
Marc

Reputation: 150

Why when requesting the shape of a numpy array within a cython function I get 8 dimensions?

I have the following function,

%%cython  
cdef cytest(double[:,:] arr):
  return print(arr.shape)      
def pytest(arr):
  return cytest(arr)  

I run pytest with the following numpy array,

dummy = np.ones((2,2))  
pytest(dummy)  

I get the following result,

[2, 2, 0, 0, 0, 0, 0, 0]

Upvotes: 1

Views: 290

Answers (1)

Rocky Li
Rocky Li

Reputation: 5958

This is because in C, arrays have shapes that are fixed. The maximum number of dimension that a cython array can have is 8. Cython stores all dimension of an array in this fixed length array.

This can be verified by doing this:

%%cython  
cdef cytest(double[:,:,:,:,:,:,:,:,:] arr): # works up to 8 ':'
    return arr.shape  
def pytest(arr):
    return cytest(arr)

When compiling it, it throw this error:

Error compiling Cython file:
------------------------------------------------------------
...
cdef cytest(double[:,:,:,:,:,:,:,:,:] arr):
                  ^
------------------------------------------------------------

/path/to/_cython_magic_9a9aea2a10d5eb901ad6987411e371dd.pyx:1:19: More dimensions than the maximum number of buffer dimensions were used.

This essentially means the preset maximum amount of dimension is 8, I assume you can change this by changing the cython_magic source file.

Upvotes: 1

Related Questions