3

使用 Cython,有没有办法编写适用于不同维度数组的快速通用函数?例如对于这个简单的去锯齿函数案例:

import numpy as np
cimport numpy as np

ctypedef np.uint8_t DTYPEb_t
ctypedef np.complex128_t DTYPEc_t


def dealiasing1D(DTYPEc_t[:, :] data, 
                 DTYPEb_t[:] where_dealiased):
    """Dealiasing data for 1D solvers."""
    cdef Py_ssize_t ik, i0, nk, n0

    nk = data.shape[0]
    n0 = data.shape[1]

    for ik in range(nk):
        for i0 in range(n0):
            if where_dealiased[i0]:
                data[ik, i0] = 0.


def dealiasing2D(DTYPEc_t[:, :, :] data, 
                 DTYPEb_t[:, :] where_dealiased):
    """Dealiasing data for 2D solvers."""
    cdef Py_ssize_t ik, i0, i1, nk, n0, n1

    nk = data.shape[0]
    n0 = data.shape[1]
    n1 = data.shape[2]

    for ik in range(nk):
        for i0 in range(n0):
            for i1 in range(n1):
                if where_dealiased[i0, i1]:
                    data[ik, i0, i1] = 0.


def dealiasing3D(DTYPEc_t[:, :, :, :] data, 
                 DTYPEb_t[:, :, :] where_dealiased):
    """Dealiasing data for 3D solvers."""
    cdef Py_ssize_t ik, i0, i1, i2, nk, n0, n1, n2

    nk = data.shape[0]
    n0 = data.shape[1]
    n1 = data.shape[2]
    n2 = data.shape[3]

    for ik in range(nk):
        for i0 in range(n0):
            for i1 in range(n1):
                for i2 in range(n2):
                    if where_dealiased[i0, i1, i2]:
                        data[ik, i0, i1, i2] = 0.

在这里,我需要针对一维、二维和三维情况的三个函数。有没有一种好的方法来编写一个可以为所有(合理的)维度完成工作的函数?

PS:在这里,我尝试使用 memoryviews,但我不确定这是正确的方法。我很惊讶命令if where_dealiased[i0]: data[ik, i0] = 0.生成的带注释的 html 中的行不是白色的cython -a。有什么不对?

4

2 回答 2

2

我要说的第一件事是,想要保留这 3 个函数是有原因的,如果使用更通用的函数,您可能会错过 cython 编译器和 c 编译器的优化。

制作一个包含这 3 个函数的函数是非常可行的,它只需将两个数组作为 python 对象,检查形状,然后调用相关的其他函数。

但是,如果要尝试这样做,那么我将尝试的只是编写最高维度的函数,然后使用新的轴符号将较低维度的数组重新转换为更高维度的数组:

cdef np.uint8_t [:] a1d = np.zeros((256, ), np.uint8) # 1d
cdef np.uint8_t [:, :] a2d = a1d[None, :]             # 2d
cdef np.uint8_t [:, :, :] a3d = a1d[None, None, :]    # 3d
a2d[0, 100] = 42
a3d[0, 0, 200] = 108
print(a1d[100], a1d[200])
# (42, 108)

cdef np.uint8_t [:, :] data2d = np.zeros((128, 256), np.uint8) #2d
cdef np.uint8_t [:, :, :, :] data4d = data2d[None, None, :, :] #4d
data4d[0, 0, 42, 108] = 64
print(data2d[42, 108])
# 64

如您所见,内存视图可以转换为更高维度,并可用于修改原始数据。在将新视图传递给最高维函数之前,您可能仍想编写一个执行这些技巧的包装函数。我怀疑这个技巧在你的情况下会很好用,但你必须四处看看它是否会对你的数据做你想做的事情。

用你的 PS:,有一个非常简单的解释。“额外代码”是生成索引错误、类型错误的代码,它允许您使用 [-1] 从数组末尾而不是开头(环绕)开始索引。您可以禁用这些额外的 python 功能,并通过使用编译器指令将其简化为 c 数组功能,例如,要从整个文件中消除这些额外代码,您可以在文件开头包含注释:

# cython: boundscheck=False, wraparound=False, nonecheck=False

编译器指令也可以使用装饰器在函数级别应用。医生解释说。

于 2014-10-06T01:53:48.133 回答
1

numpy.ndindex()您可以使用对象的strided属性以一般方式读取展平数组np.ndarray,以便位置由以下方式确定:

indices[0]*strides[0] + indices[1]*strides[1] + ... + indices[n]*strides[n]

(strides*indices).sum()strides是一维数组时,这很容易完成。下面的代码显示了如何构建一个工作示例:

#cython profile=True
#blacython wraparound=False
#blacython boundscheck=False
#blacython nonecheck=False
#blacython cdivision=True
cimport numpy as np
import numpy as np

def readNDArray(x):
    if not isinstance(x, np.ndarray):
        raise ValueError('x must be a valid np.ndarray object')
    if x.itemsize != 8:
        raise ValueError('x.dtype must be float64')
    cdef np.ndarray[double, ndim=1] v # view of x
    cdef np.ndarray[int, ndim=1] strides
    cdef int pos

    shape = list(x.shape)
    strides = np.array([s//x.itemsize for s in x.strides], dtype=np.int32)
    v = x.ravel()
    for indices in np.ndindex(*shape):
        pos = (strides*indices).sum()
        v[pos] = 2.
    return np.reshape(v, newshape=shape)

如果它是 C 连续的,则此算法不会复制原始数组:

def main():
    # case 1
    x = np.array(np.random.random((3,4,5,6)), order='F')
    y = readNDArray(x)
    print(np.may_share_memory(x, y))
    # case 2
    x = np.array(np.random.random((3,4,5,6)), order='C')
    y = readNDArray(x)
    print np.may_share_memory(x, y)
    return 0

结果是:

False
True
于 2014-10-06T06:25:17.957 回答