简体   繁体   English

使用scipy.weave.inline迭代数组数组

[英]Iterate over array of arrays with scipy.weave.inline

I have a numpy.ndarray of dtype object containing exclusively other arrays of different length. 我有一个numpy.ndarray对象的numpy.ndarraynumpy.ndarray包含不同长度的其他数组。 I have C code, that does some computations with the nested arrays, but I'm not sure how to grab the inner array and it's size when iterating over it using the numpy C-API. 我有C代码,它使用嵌套数组进行一些计算,但我不确定如何使用numpy C-API迭代内部数组及其大小。 So currently it looks something like this: 所以目前它看起来像这样:

from scipy.weave import inline
import numpy as np

arrs = np.zeros(10, dtype=object)
for i in xrange(10):
    arrs[i] = np.arange(i*i)

for arr in arrs:
    inline(ccode, ['arr', 'other', 'args'])

I know, that it's not an optimal structure, but neither would be sparse matrices I guess. 我知道,这不是一个最优的结构,但我认为也不是稀疏矩阵。 arrs is quite lengthy, about 100k, so including this python loop into C would be a great speedup, as it would eliminate the overhead of calling inline all the time. arrs非常冗长,大约100k,因此将这个python循环包含在C中将是一个很好的加速,因为它将消除一直调用内联的开销。 But how do I get arr in an iterated way from within C? 但是如何从C中以迭代的方式获得arr

So I finally figured out how to do it. 所以我终于想出了如何做到这一点。 scipy.weave seems not to like object arrays, so first I converted it to a list. scipy.weave似乎不喜欢对象数组,所以首先我把它转换成一个列表。 Then the list items can be grabbed using the python C-API. 然后可以使用python C-API获取列表项。 The object conversion is directly taken from some other precompiled inlined C-Code. 对象转换直接取自其他一些预编译的内联C代码。

arrs = list()
for i in xrange(5):
    arrs.append(np.arange(i * i, dtype=int))
code = r"""
    long arrs_size = PyList_Size(arrs);
    for (long i=0; i<arrs_size; i++) {
        PyArrayObject* arr_array = convert_to_numpy(PyList_GetItem(arrs,i), "arr");
        conversion_numpy_check_type(arr_array,PyArray_LONG, "arr");
        npy_intp* Narr = arr_array->dimensions;
        npy_intp* Sarr = arr_array->strides;
        int Darr = arr_array->nd;
        long* arr = (long*) arr_array->data;
        long arr_size = 1;
        for (int n=0; n<Darr; n++) arr_size *= Narr[n];
        for (int j=0; j<arr_size; j++) printf("%ld ", arr[j]);
        printf("\n");
    }
"""
inline(code, ['arrs'])

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

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