Showing posts with label Cython odeint. Show all posts
Showing posts with label Cython odeint. Show all posts

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.