如何实现从Numba调用的C以与nquad高效集成? [英] How can you implement a C callable from Numba for efficient integration with nquad?
问题描述
我需要在python中的6D中进行数值积分.由于scipy.integrate.nquad函数运行缓慢,因此我目前正在尝试通过将被积分数定义为scipy.LowLevelCallable以及Numba来加快处理速度.
I need to do a numerical integration in 6D in python. Because the scipy.integrate.nquad function is slow I am currently trying to speed things up by defining the integrand as a scipy.LowLevelCallable with Numba.
通过复制给定
10000次循环,最好为3:每个循环128 µs 10000 loops, best of 3: 128 µs per loop 100000个循环,每个循环中最好为3个:7.08 µs 100000 loops, best of 3: 7.08 µs per loop 当我现在想使用nquad进行此操作时,nquad文档说: When I want to do this now with nquad, the nquad documentation says: 如果用户希望改善集成性能,则f可能是
scipy.LowLevelCallable,并带有以下签名之一: If the user desires improved integration performance, then f may be a
scipy.LowLevelCallable with one of the signatures: 其中n是额外参数的数量,而args是一个数组
附加参数的两倍,则xx数组包含
坐标. user_data是包含在
scipy.LowLevelCallable. where n is the number of extra parameters and args is an array of
doubles of the additional parameters, the xx array contains the
coordinates. The user_data is the data contained in the
scipy.LowLevelCallable. 但是以下代码给了我一个错误: But the following code gives me an error: 错误:四元组:第一个参数是签名不正确的ctypes函数指针 error: quad: first argument is a ctypes function pointer with incorrect signature 是否可以使用numba编译可直接在代码中与nquad一起使用而无需在外部文件中定义该函数的函数? Is it possible to compile a function with numba that can be used with nquad directly in the code and without defining the function in an external file? 非常感谢您! 将函数包装在
查看全文
# integration with compiled function
%timeit integrate.quad(nb_integrand.ctypes, 1, np.inf)
double func(int n, double *xx)
double func(int n, double *xx, void *user_data)
from numba import cfunc
import ctypes
def func(n_arg,x):
xe = x[0]
xh = x[1]
return np.sin(2*np.pi*xe)*np.sin(2*np.pi*xh)
nb_func = cfunc("float64(int64,CPointer(float64))")(func)
integrate.nquad(nb_func.ctypes, [[0,1],[0,1]], full_output=True)
推荐答案