python到cython - 消除python调用

时间:2013-01-06 22:10:24

标签: python numpy cython

我目前正在尝试将以下循环转换为cython:

cimport numpy as np
cimport cython
@cython.boundscheck(False) # turn of bounds-checking for entire function
def Interpolation(cells, int nmbcellsx):
    cdef np.ndarray[float, ndim=1] x,y,z
    cdef int i,j,len
    for i in range(nmbcellsx):
      x = cells[i].x
      y = cells[i].y
      z = cells[i].z
      len = x.size
      for j in range(len):
         x[j] = x[j] * y[j] * z[j]

    return 0

到目前为止,一切看起来都还不错,但是对单元格[i]。*的访问仍然需要python调用。这可以防止i-loop的并行化。

这是一个cython反馈(用cython -a生成):

cython -a feedback

因此问题:如何删除这些python回调(即第9-12行变为白色)?

当我尝试像这样添加Cell的类型时:

cimport numpy as np
cimport cython

cdef class cell_t:
   cdef np.ndarray x,y,z

@cython.boundscheck(False) # turn of bounds-checking for entire function
def Interpolation(np.ndarray[cell_t,ndim=1] cells, int nmbcellsx):
    cdef np.ndarray[float, ndim=1] x,y,z
    cdef int i,j,len
    for i in range(nmbcellsx):
      x = cells[i].x
      y = cells[i].y
      z = cells[i].z
      len = x.size
      for j in range(len):
         x[j] = x[j] * y[j] * z[j]

    return 0

我收到以下cython错误:dtype必须是“对象”,数字类型或结构(它抱怨声明中的cell_t)

非常感谢。

2 个答案:

答案 0 :(得分:2)

您没有告诉 Cython cells参数的类型,因此它将使用 Python 查找方法。尝试将定义更改为以下内容:

def Interpolation(np.ndarray cells, int nmbcellsx):

这将告诉 Cython 它获得ndarray类型,因此可以使用 C 访问。

答案 1 :(得分:2)

如何使用Typed Memoryview

cimport cython

cdef class cell_t:
    cdef public float[:] x, y, z

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z


@cython.boundscheck(False) # turn of bounds-checking for entire function
def Interpolation(cell_t[:] cells, int nmbcellsx):
    cdef float[:] x,y,z
    cdef int i,j,length
    cdef cell_t cell
    for i in range(nmbcellsx):
        cell = cells[i]
        x = cell.x
        y = cell.y
        z = cell.z
        length = len(x)
        for j in range(length):
            x[j] = x[j] * y[j] * z[j]
    return 0

这是测试代码:

import numpy as np
from cells import cell_t, Interpolation

x = np.array([1,2,3], np.float32)
y = np.array([4,5,6], np.float32)
z = np.array([7,8,9], np.float32)
c1 = cell_t(x, y, z)

x = np.array([1,1,1,1,1], np.float32)
y = np.array([2,2,2,2,2], np.float32)
z = np.array([3,3,3,3,3], np.float32)
c2 = cell_t(x, y, z)

cells = np.array([c1, c2], object)

Interpolation(cells, 2)

print c1.x.base
print c2.x.base

和输出:

[  28.   80.  162.]
[ 6.  6.  6.  6.  6.]