简体   繁体   English

在Cython中声明numpy数组的列表/向量/数组

[英]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: 在Cython中,我可以声明它们的类型以获得快速的项目访问:

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. 但是,现在Cython不知道A[0]A[1] ,这会使访问速度变慢。 I don't think Cython has the concept of a "typed tuple". 我认为Cython没有“类型化元组”的概念。 So how can I declare A (or a similar object) so that I still get fast item access in the above expression? 那么,如何声明A (或类似的对象),以便在上述表达式中仍能快速访问项目?

Whether this is valid cython is speculative, but inspired by the cython example at the end of: 这是否是有效的cython具有推测性,但受到以下结尾的cython示例的启发:

https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html#putting-the-inner-loop-in-cython 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 . https://github.com/cython/cython/blob/master/tests/run/unpack.pyx-是解压缩测试pyx

Or maybe use A0 = aTuple[0] and A1 = aTuple[1] ; 或使用A0 = aTuple[0]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 cython处理数组时,另一个有用的页面是http://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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