I need to cythonize a function that takes in parameters lenscale and sigvar in order to construct a function. I'd like to be able to do this without have to make k_se a class. When I run the following code:
ctypedef float (*kfunc)(float, float)
cdef kfunc k_se(float lenscale, float sigvar):
cdef float f(float xi, float xj):
return sigvar**2. * _np.exp(-(1./(2. * lenscale**2.)) *\
_npl.norm(xi - xj)**2)
return f
I get the error:
Error compiling Cython file:
------------------------------------------------------------
...
cdef kfunc k_se(float lenscale, float sigvar):
cdef float f(float xi, float xj):
^
------------------------------------------------------------
BUILDGP.pyx:15:36: C function definition not allowed here
I've also tried this trying to return a lambda, which cython could not compile either. Any ideas, do do I have to create a constructor class for k_se functions?
You may construct a class, which can be initialized with a set of parameters and acts as callable:
class Function():
def __init__(self, float lenscale):
self.lenscale = lenscale
def __call__(self, float xi):
return self.lenscale*xi
f = Function(10)
print f(5)
The cython documentation has more details on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With