Skip to content

Instantly share code, notes, and snippets.

@nfoti
Created July 25, 2012 00:33
Show Gist options
  • Save nfoti/3173622 to your computer and use it in GitHub Desktop.
Save nfoti/3173622 to your computer and use it in GitHub Desktop.
Cythonize instance method of Python class
import numpy as np
from scipy.special import gammaln
class MyClass(object):
def __init__(self, n, x):
self.n = n
self.x = np.abs(x)
def fun(self):
return (np.random.rand(self.n), gammaln(self.x))
if __name__ == '__main__':
np.random.seed(8675309)
mc = MyClass(5, 12)
(r, gx) = mc.fun()
print r
print gx
import types
import numpy as np
import cy1fun
class MyClass(object):
def __init__(self, n, x):
self.n = n
self.x = np.abs(x)
# Add the cython implementation of fun to the class as an instance method
# Want to do this, but it doesn't work
# MyClass.fun = cy1fun.fun
# Need to do this instead
MyClass.fun = types.MethodType(cy1fun.fun, None, MyClass)
if __name__ == '__main__':
np.random.seed(8675309)
mc = MyClass(5, 12)
(r, gx) = mc.fun()
print r
print gx
# build with: python setup.py build_ext --inplace
# see setup.py below
import numpy as np
cimport numpy as np
from scipy.special import gammaln
def fun(object self):
return (np.random.rand(self.n), gammaln(self.x))
import types
import numpy as np
import cy2fun
class MyClass(object):
def __init__(self, n, x):
self.n = n
self.x = np.abs(x)
# Add the cython implementation of fun to the class as an instance method
# Want to do this, but it doesn't work
# MyClass.fun = cy2fun.fun
# Need to do this instead
MyClass.fun = types.MethodType(cy2fun.fun, None, MyClass)
if __name__ == '__main__':
np.random.seed(8675309)
mc = MyClass(5, 12)
(r, gx) = mc.fun()
print r
print gx
# build with: python setup.py build_ext --inplace
# see setup.py below
import numpy as np
cimport numpy as np
cdef extern from "gsl/gsl_sf_gamma.h":
double gsl_sf_lngamma(double x)
cdef gammaln(double x):
return gsl_sf_lngamma(x)
def fun(object self):
return (np.random.rand(self.n), gammaln(self.x))
import numpy as np
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
cy1fun = Extension("cy1fun", ["cy1fun.pyx"],
include_dirs=[np.get_include()],
)
gsl_include_dir = "/usr/local/include"
gsl_lib_dir = "/usr/local/lib"
cy2fun = Extension("cy2fun", ["cy2fun.pyx"],
include_dirs=[np.get_include(),
gsl_include_dir],
library_dirs=[gsl_lib_dir],
libraries=["gsl"],
)
setup(cmdclass={'build_ext': build_ext},
ext_modules=[cy1fun, cy2fun]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment