我正在尝试编写一些用numpy数组进行计算的cython代码。 Cython似乎不喜欢所有我见过的用于定义数据类型和维数的例子中使用的[]。在cython中使用numpy:定义ndarray数据类型/ ndims
例如,我有一个文件test.pyx:
cimport numpy as np
import numpy as np
ctypedef np.ndarray[np.float64_t, ndim=2] mymatrix
cpdef mymatrix hat (mymatrix x):
a = np.zeros((3,3));
a[0,1] = x[2,0];
a[0,2] = -x[1,0];
a[1,2] = x[0,0];
a[1,0] = -x[2,0];
a[2,0] = x[1,0];
a[2,1] = -x[0,0];
return a;
我此使用setup.py(参见后结束)编译,我与“蟒setup.py build_ext --inplace运行“
我得到以下输出:
running build_ext
cythoning test.pyx to test.c
Error converting Pyrex file to C:
------------------------------------------------------------
...
cimport numpy as np
import numpy as np
ctypedef np.ndarray[np.float64_t, ndim=2] mymatrix
^
------------------------------------------------------------
test.pyx:4:42: Syntax error in ctypedef statement
<snip, irrelevant>
而如果删除了 ”[np.float64_t,NDIM = 2]“ 的一部分,它工作正常。
有没有人有任何想法?
至于我的系统设置: 操作系统:Windows XP
充分,完整pythonxy安装,版本2.6.5.1(最新的在这一点上)
pythonxy理应带有用Cython,但我最终安装用Cython版本0.12.1为Python 2.6从此站点:http://www.lfd.uci.edu/~gohlke/pythonlibs/#cython
我怀疑,我不知是缺少路径或东西:我解决了明确添加numpy的头文件目录由MinGW的使用的包括路径的一些问题(见下面的setup.py文件)
这里是setup.py文件我提到:
from distutils.core import setup
from distutils.extension import Extension
from distutils.sysconfig import get_python_inc
from Cython.Distutils import build_ext
import os.path
inc_base = get_python_inc(plat_specific=1);
incdir = os.path.join(get_python_inc(plat_specific=1),);
#libraries=['math'],
ext_modules = [Extension("test",
["test.pyx"],
include_dirs = [
os.path.join(inc_base,'..\\Lib\\site-packages\\numpy\\core\\include\\numpy'),
]
)
]
setup(
name = 'test',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
你什么意思,'而如果我删除“[np.float64_t,NDIM = 2 ]“部分,它工作正常。”?你只是用np.ndarray [np.float64_t,ndim = 2'替换'mymatrix'发生的两个地方? – 2010-08-07 06:02:53
我不认为你可以使用ctypedef的缓冲接口。你必须每次使用cdef来声明它。 – carl 2010-08-16 10:07:15