LoginSignup
35
24

More than 5 years have passed since last update.

[python]Cythonでnumpy使おうとする時のメモ

Posted at

はじめに

今回やりたいことは、
ctypedef numpy.float64_t DOUBLE_t
と定義したい。
これをやるためには、
cimport numpyをやる必要がある。
この二つのctypedefcimportをやりたいということです。

※英語が読めない自分が英語のdocument見ながらやったので間違ってる場合があります。途中のエラーとか見たくない人は最後だけみてください。

環境はこんな感じです。
OS X, Yosemite
Cython 0.23.4
Python 3.4.3

cythonコンパイル時に次のようなエラーが発生。

Cython 0.23.2 documentation: Building Cython codeのページを参考にし、下記の二つのスクリプトを作成してみる。

test.pyx
import numpy
cimport numpy
ctypedef numpy.float64_t DOUBLE_t
setup.py
from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = 'test',
    ext_modules = cythonize('test.pyx')
    )

これを使って、python setup.py build_ext --inplaceを行うと、下記のようなエラーが発生。

error.
sample.c:250:10: fatal error: 'numpy/arrayobject.h' file not found
#include "numpy/arrayobject.h"
         ^
1 error generated.
error: command 'clang' failed with exit status 1

ファイルが見当たらないってエラーが出ました。
パスが違うようですね、ってことでもう少し先ほどのサイトを見てみると、
こんなものが、Cython 0.23.2 documentation: Compilation

Often, Python packages that offer a C-level API provide a way to find the necessary include files, e.g. for NumPy:

include_path = [numpy.get_include()]

よくあることっぽかったですね。
とりあえず、これをsetup.pyに入れてみます。

setup.py
from distutils.core import setup
from Cython.Build import cythonize
import numpy

setup(
    name = 'test',
    ext_modules = cythonize('test.pyx')
    include_path = [numpy.get_include()]
    )

これ使ってみるとなんかまたエラー出る

error.
Unknown distribution option: 'include_path'

なんぞこれ、こんなオプションないって言われた。
stackoverflowとか色々見てみると、みんなinclude_pathなんか使ってなくて、include_dirsを使ってるっぽい。
とりあえずs/include_path/include_dirsしてみる。

setup.py
from distutils.core import setup
from Cython.Build import cythonize
import numpy

setup(
    name = 'test',
    ext_modules = cythonize('test.pyx')
    include_dirs = [numpy.get_include()]
    )

実行してみると、通った(o・ω・o)
なんかわからんけどできたっぽい。

まとめ

include_dirs = [numpy.get_include()]使うといいっぽい。
新しいものだと日本語で書かれているものが少ないので、英語がわからないと辛いものがある。
今回一応はコンパイル通ったが、unused functionのwarningがいっぱい出てたのでなんか直さないといけないかも?(unused functionだから放置しても良いかも)

35
24
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
35
24