Sunday, July 24, 2011

Using Cython

The easiest way to convert old python code for use with cython is to rename your python file into something with the extension .pyx. This .pyx file can then be compiled with the (for distutils)script.

Here is an example which also shows how to include the math libray (-lm for gcc)

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules = [Extension("BvL_cython",["BvL_cython.pyx"],\

    name= 'BvL model class',
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules

The reason that I was interested in Cython was the long calculation times I encountered while doing a multi-variable optimization with a function evaluation that involved solving a differential equation with scipy.integrate.odeint. By simply replacing the class that contained the differential equation with a Cython version the calculation time dropped by a factor 5. Not bad for half a Sunday afternoons work.

First steps with Cython and Python(x,y)

Started today experimenting with Cython. With Cython you can write normal python code and compile it to C code. When you start to insert type information the speed up you get compared to normal python can be quite dramatic. The compiled c-code can be called from python (seemingly as if it was normal python code your calling). It is all nicely introduced here: Cython tutorial

On windows I am using Python(x,y). When you install it you have to tell the installer to include Cython. As c-compiler the Python (x,y) package includes mingw. Unfortunately Cython by default seems to expect a Visual C compiler. So the only way (so far) I found to use Cython is to run python from a normal command prompt when using the method (distutils) as described in the Cython Tutorial as follows:

python build_ext --inplace --compiler=mingw32

otherwise you get this error message:

error: Unable to find vcvarsall.bat