简体   繁体   中英

Declaring a list/vector/array of numpy arrays in Cython

Say I have several arrays, potentially of different sizes:

A0 = rand(3,3)
A1 = rand(4,4)

In Cython, I can declare their types to get fast item access:

cdef np.ndarray[double, ndim=2] A0
cdef np.ndarray[double, ndim=2] A1

However, say I want to access them by index:

A = (A0,A1)
A[0][2,1] += A[1][1,0]

However, now Cython doesn't know the type of A[0] and A[1] , which makes access slow. I don't think Cython has the concept of a "typed tuple". So how can I declare A (or a similar object) so that I still get fast item access in the above expression?

Whether this is valid cython is speculative, but inspired by the cython example at the end of:

https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#putting-the-inner-loop-in-cython

I'd suggest:

cdef foo(aTuple):
    cdef np.ndarray[double, ndim=2] A0
    cdef np.ndarray[double, ndim=2] A1
    A0, A1 = aTuple    # use unpacking
    A0[2,1] += A1[1,0]    

https://github.com/cython/cython/blob/master/tests/run/unpack.pyx - is the unpack test pyx .

Or maybe use A0 = aTuple[0] and A1 = aTuple[1] ; The idea is to use the array typing where it matters, for its own indexing. The tuple just holds pointers, so the typing doesn't matter.

Another useful page when working with arrays in cython is http://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM