Cython: how to return a function in Cython

I need a cythonize function that takes lenscale and sigvar parameters in order to build a function. I would like to be able to do this without doing the k_se 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 am getting 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 also tried this, trying to return a lambda that cython could not compile either. Any ideas if I should create a constructor class for the k_se functions?

+3


source to share


1 answer


You can create a class that can be initialized with a set of parameters and acts like a 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.

+2


source







All Articles