numpy配列で計算を行うためのcythonコードを書き込もうとしています。Cythonは、データ型と次元数を定義するために私が見たすべての例で使用されている[]を好まないようです。
たとえば、ファイル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;
これは、「python setup.pybuild_ext--inplace」で実行するsetup.py(投稿の最後を参照)を使用してコンパイルします。
次の出力が得られます。
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]」の部分を削除すると、正常に機能します。
誰かアイデアはありますか?
私のシステム設定について:OS:Windows XP
完全な完全なpythonxyインストール、バージョン2.6.5.1(この時点で最新)
pythonxyにはcythonが付属していると思われますが、最終的には次のサイトからPython2.6用のcythonバージョン0.12.1をインストールしました。http://www.lfd.uci.edu/~gohlke/pythonlibs/#cython
どういうわけかパスなどが欠落しているのではないかと思います。mingwが使用するインクルードパスにnumpyヘッダーファイルディレクトリを明示的に追加することで、いくつかの問題を解決しました(以下の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
)