首页 > 解决方案 > Numba for SciPy Integration and Interpolation

问题描述

I have used Numba for speeding up my code. It works great and provides a 2-3x factor improvement. However the major time spent in my code (about 90%) is in the scipy quad integration and interpolation (linear and Cubic Spline). I do these integrations several hundred times so I figured this is something that Numba can boost. It does not look like Numba supports these? I heard of Numba-Scipy which is suppose to make Numba recognize Scipy, but this still does not seem to work. Is there a way to make Numba optimize my integrations/interpolations?

标签: pythonscipyintegrationinterpolationnumba

解决方案


刚刚为cquadpack编写了一个包装器,它NumbaQuadpack应该可以满足您的需求:https ://github.com/Nicholaswogan/NumbaQuadpack 。cquadpack 是 Quadpack 的 C 版本,这就是它的scipy.integrate.quad用途。

from NumbaQuadpack import quadpack_sig, dqags
import numpy as np
import numba as nb
import timeit

@nb.cfunc(quadpack_sig)
def f(x, data):
    return x**2 + 2 + np.log(x)
funcptr = f.address
a = 0
b = 1
sol, abserr, success = dqags(funcptr, a, b)
print(sol) # definite integral solution

# test speed
@nb.njit()
def timetest_nb():
    sol, abserr, success = dqags(funcptr, a, b)
timetest_nb()
n_time=10000
print(timeit.Timer(timetest_nb).timeit(number=n_time)/n_time) 

在我的电脑上,这个小积分需要 4.2 µs,而当我用 scipy.integrate.quad 做同样的事情时,需要 68.1 µs。

对于插值,只需使用np.interp(一维插值)。它可以在 numba-jitted 函数中使用。

通常,任何 C/C++ 或 fortran 代码都可以用 ctypes 包装,并从 numba-jitted 函数中调用。


推荐阅读