【发布时间】:2016-02-25 03:19:37
【问题描述】:
我正在模拟 CCD 阵列中的陷阱。目前我正在使用 NumPy 和 Scipy,并且我已经能够对大多数调用进行矢量化,这给了我一些加速。 目前,我代码的瓶颈是我必须从代码内部循环中的大量不同插值中检索一个数字。这一特定步骤占用了约 97% 的计算时间。
我在这里做了一个简单的例子来说明我的问题:
import numpy as np
from scipy.interpolate import interp1d
# the CCD array containing values from 0-100
array = np.random.random(200)*100
# a number of traps at different positions in the CCD array
n_traps = 100
trap_positions = np.random.randint(0,200,n_traps)
# xvalues for the interpolations
xval = [0,10,100]
# each trap has y values corresponding to the x values
trap_yvals = [np.random.random(3)*100 for _ in range(n_traps)]
# The xval-to-yval interpolation is made for each trap
yval_interps = [interp1d(xval,yval) for yval in trap_yvals]
# moving the trap positions down over the array
for i in range(len(array)):
# calculating new trap position
new_trap_pos = trap_positions+i
# omitting traps that are outside array
trap_inside_array = new_trap_pos < len(array)
# finding the array_vals (corresponding to the xvalues in the interpolations)
array_vals = array[new_trap_pos[trap_inside_array]]
# retrieving the interpolated y-values (this is the bottleneck)
yvals = np.array([yval_interps[trap_inside_array[t]](array_vals[t])
for t in range(len(array_vals))])
# some more operations using yvals
有没有办法可以优化,可能使用 Cython 或类似的?
【问题讨论】:
-
请参阅this,而不是 interp1d,使用 InterpolatedUnivariateSpline。将性能提高几个数量级
-
另一个重大改进是将数组作为参数传递给 interp1d/InterpolatedUnivariateSpline,而不是尽可能循环单个值
-
@M.T:感谢有关使用 InterpolatedUnivariateSpline 加速的提示。我在单个值上循环的原因是每个值都需要从不同的插值中提取,我没有找到解决这个问题的方法。
标签: python numpy scipy linear-interpolation