问题描述
我正在尝试创建一个用cython构建的切片采样库。通用切片采样库,您可以在其中提供对数密度,初始值并获得结果。现在正在研究单变量模型。根据响应here,我提出了以下建议。
所以我在cSlice.pyx中定义了一个函数:
cdef double univariate_slice_sample(f_type_1 logd,double starter,double increment_size = 0.5):
some stuff
return value
我已经在cSlice.pxd中定义了
cdef ctypedef double (*f_type_1)(double)
cdef double univariate_slice_sample(f_type_1 logd,double increment_size = *)
其中logd是通用的单变量对数密度。
在我的分发文件中,假设cDistribution.pyx,我具有以下内容:
from cSlice cimport univariate_slice_sample,f_type_1
cdef double log_distribution(alpha_k,y_k,prior):
some stuff
return value
cdef double _sample_alpha_k_slice(
double starter,double[:] y_k,Prior prior,double increment_size
):
cdef f_type_1 f = lambda alpha_k: log_distribution(alpha_k),prior)
return univariate_slice_sample(f,starter,increment_size)
cpdef double sample_alpha_k_slice(
double starter,double[:] y_1,double increment_size = 0.5
):
return _sample_alpha_1_slice(starter,y_1,prior,increment_size)
包装器,因为显然lambda
中不允许使用cpdef
。
当我尝试编译分发文件时,得到以下信息:
cDistribution.pyx:289:22: Cannot convert Python object to 'f_type_1'
指向cdef f_type_1 f = ...
行。
我不确定该怎么办。我希望此代码保持C速度,并且重要的是不要命中GIL。有什么想法吗?
解决方法
您可以为任何Python函数设置C回调/包装器(无法隐式完成从Python对象到指针的广播),例如如何在本SO-post中进行解释。
但是,该函数的核心将保持缓慢的纯Python函数。 Numba使您可以通过@cfunc
创建真实的C回调。这是一个简化的示例:
from numba import cfunc
@cfunc("float64(float64)")
def id_(x):
return x
这就是它的用法:
%%cython
ctypedef double(*f_type)(double)
cdef void c_print_double(double x,f_type f):
print(2.0*f(x))
import numba
expected_signature = numba.float64(numba.float64)
def print_double(double x,f):
# check the signature of f:
if not f._sig == expected_signature:
raise TypeError("cfunc has not the right type")
# it is not possible to cast a Python object to a pointer directly,# so we cast the address first to unsigned long long
c_print_double(x,<f_type><unsigned long long int>(f.address))
现在:
print_double(1.0,id_)
# 2.0
我们需要在运行时检查cfunc
对象的签名,否则强制转换<f_type><unsigned long long int>(f.address)
对于具有错误签名的功能也将“起作用”-仅在(可能)崩溃期间发生通话或给出有趣的难以调试的错误。我只是不确定我的方法是否是最好的-即使它可行:
...
@cfunc("float32(float32)")
def id3_(x):
return x
print_double(1.0,id3_)
# TypeError: cfunc has not the right type