Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython: How to return a function in Cython

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?

like image 965
jbbj94 Avatar asked Oct 20 '22 02:10

jbbj94


1 Answers

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.

like image 197
David Zwicker Avatar answered Oct 30 '22 16:10

David Zwicker