Numpy 三线性插值-无需Scipy的矢量化

Numpy 三线性插值-无需Scipy的矢量化,numpy,3d,scipy,interpolation,Numpy,3d,Scipy,Interpolation,我正在寻找矢量化这段代码,但不知道从哪里开始。这个网站上有另一个答案,回答了一个与我类似的问题:但我对如何实现它感到困惑。我不能使用SciPy中的任何东西,但我需要我的代码速度快,因为目前对于大型阵列来说,它需要绝对的时间(正如您所期望的那样)。我意识到我的代码很慢,因为a)使用列表,b)使用嵌套for循环 我有一个规则的三维速度网格(V)表示纬度(lat)/经度(lon)/时间(t)。我希望能够获取特定纬度/经度/时间的单个值 我的代码如下: def intrp_vel(lon_2_inter

我正在寻找矢量化这段代码,但不知道从哪里开始。这个网站上有另一个答案,回答了一个与我类似的问题:但我对如何实现它感到困惑。我不能使用SciPy中的任何东西,但我需要我的代码速度快,因为目前对于大型阵列来说,它需要绝对的时间(正如您所期望的那样)。我意识到我的代码很慢,因为a)使用列表,b)使用嵌套for循环

我有一个规则的三维速度网格(V)表示纬度(lat)/经度(lon)/时间(t)。我希望能够获取特定纬度/经度/时间的单个值

我的代码如下:

def intrp_vel(lon_2_interp, lat_2_interp, t_2_interp, X, Y, T, V):
# lonlat should be a tuple of (lon, lat)
# t_2_interp should be a float of the current time step
# This function returns the surface velocity at any location in time.

Tlen = len(T)
Ylen = len(Y)-1
Xlen = len(X)-1

t_2_index = Tlen*(1-(T[-1]-t_2_interp)/(T[-1]-T[0]))
lat_2_index = Ylen*(1-(Y[-1]-lat_2_interp)/(Y[-1]-Y[0]))
lon_2_index = Xlen*(1-(X[-1]-lon_2_interp)/(X[-1]-X[0]))

time = np.linspace(0, Tlen, V.shape[0])
latitudes = np.linspace(0, Ylen, V.shape[1])
longitudes = np.linspace(0, Xlen, V.shape[2])

V1 = [] # To be brought down to 2D intp
V2 = [] # To be brought down to 1D intp
append1 = V1.append
for lats in latitudes:
    for lons in longitudes:
        append1(np.interp(t_2_index, time, V[:,lats,lons]))
V1 = np.reshape(V1, (len(Y),len(X)))
append2 = V2.append
for lons in longitudes:
    append2(np.interp(lat_2_index, latitudes, V1[:,lons]))

intrpvel = np.interp(lon_2_index, longitudes, V2)

return intrpvel

任何帮助都将不胜感激,或者如果您理解上面链接中的代码,并且能够告诉我如何在我自己的案例中使用它。

以下是一些删除
np.interp()的for循环调用的方法。

由于
t_2_索引
时间
在循环中不会改变,因此可以使用
np.interp()
来计算
V
的线性混合参数。以下是确认该想法的代码:

y = np.sin(x)
x2 = np.linspace(x[0]-1, x[-1]+1, 100)
y2 = np.interp(x2, x, y)
计算混合参数:

idx = np.arange(len(x))
idx_float = np.interp(x2, x, idx)
idx0 = idx_float.astype(int)
idx1 = np.clip(idx0 + 1, 0, len(x)-1)
a = idx_float - idx0
b = 1 - a
然后计算interp结果:

y3 = y[idx0] * b + y[idx1] * a
print np.allclose(y2, y3)
对于您的代码,如果您从
t_2_索引
时间
计算
idx0、idx1、a、b
,则您可以通过以下方式计算interp结果:

V[idx0, :, :] * b + V[idx1, :, :] * a