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 setup.py (for distutils)script.

Here is an example setup.py 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"],\
    libraries=["m"])]

setup(
    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.

3 comments:

  1. I am trying to do the exact same thing: use Cython to reduce the time for optimizations that involve scipy.integrate.odeint. Can you post a full example or would you be willing to email me your files? I haev a grad student working on this project and he is having trouble converting the pure python version to cython.

    ReplyDelete
  2. In the weekend I will try to post a full example (I do not have time right now and I have to edit it a bit)

    ReplyDelete
  3. Done. See the post of 10 december 2011.

    ReplyDelete