Cython:解决方法scipy.optimize.cython_optimize.brentq参数ctype可与类方法ctype

问题描述

我正在尝试在类中使用根查找器scipy.optimize.cython_optimize.brentq,但是此函数的第一个参数仅接受类型ctypedef double (*callback_type)(double,void*),而我的类方法ctypedef double (*w_func)(test,double,void*)类型。 我该如何工作?

以下代码是该问题的一个例子。

%%cython
from scipy.optimize.cython_optimize cimport brentq

ctypedef double (*f_func)(test,double)
ctypedef double (*w_func)(test,void*)
ctypedef double (*callback_type)(double,void*)

ctypedef struct test_params:
    double y0
    double x1
    f_func f
    w_func w

cdef class test():
    def __init__(self):
        cdef test_params myargs
        myargs.y0 =  1.0
        myargs.x1 = 0.7
        myargs.f = self.sum2
        myargs.w = self.w
        print(self.brentqWrapper(myargs,-10,10,1e-3,10))
    
    cdef double sum2(self,double x1,double y1):
        return x1+y1

    cdef double w(self,double y1,void *args):
        cdef test_params *myargs = <test_params *> args
        return y1 - myargs.y0 - myargs.f(self,myargs.x1,y1)

    # Cython wrapper function
    cdef double brentqWrapper(self,test_params args,double xa,double xb,double xtol,double rtol,int mitr):
        return brentq(args.w,xa,xb,<test_params *> &args,xtol,rtol,mitr,NULL)

test()

解决方法

ISTM,最简单,最干净的方法是将代码重构为具有模块级函数,该函数在其最后一个参数中接收类实例。