jbbj94
jbbj94

Reputation: 334

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?

Upvotes: 5

Views: 1470

Answers (1)

David Zwicker
David Zwicker

Reputation: 24278

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.

Upvotes: 3

Related Questions