正确使用scipy.interpolate.RegularGridInterpolator

时间:2015-05-05 15:00:50

标签: python numpy scipy interpolation

我对documentation for scipy.interpolate.RegularGridInterpolator感到有些困惑。

比方说我有一个函数f:R ^ 3 => R在单位立方体的顶点上采样。我想插值以便在立方体内找到值。

import numpy as np

# Grid points / sample locations
X = np.array([[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,1.]])

# Function values at the grid points
F = np.random.rand(8)

现在,RegularGridInterpolator采用points参数和values参数。

  

积分:浮点数的ndarray元组,带有形状(m1,),...,(mn,)   在n维中定义规则网格的点。

     

:array_like,shape(m1,...,mn,...)   n维规则网格上的数据。

我认为这可以这样打电话:

import scipy.interpolate as irp

rgi = irp.RegularGridInterpolator(X, F)

然而,当我这样做时,我收到以下错误:

  

ValueError:有8个点数组,但值有1个维度

我在文档中误解了什么?

2 个答案:

答案 0 :(得分:8)

你的答案更好,你完全可以接受它。我只是将其添加为"替代"编写脚本的方法。

import numpy as np
import scipy.interpolate as spint

RGI = spint.RegularGridInterpolator

x = np.linspace(0, 1, 3) #  or  0.5*np.arange(3.) works too

# populate the 3D array of values (re-using x because lazy)
X, Y, Z = np.meshgrid(x, x, x, indexing='ij')
vals = np.sin(X) + np.cos(Y) + np.tan(Z)

# make the interpolator, (list of 1D axes, values at all points)
rgi = RGI(points=[x, x, x], values=vals)  # can also be [x]*3 or (x,)*3

tst = (0.47, 0.49, 0.53)

print rgi(tst)
print np.sin(tst[0]) + np.cos(tst[1]) + np.tan(tst[2])

返回:

1.93765972087
1.92113615659

答案 1 :(得分:7)

好的,当我回答我自己的问题时,我感到愚蠢,但是我在原始regulargrid lib的文档中找到了我的错误:

https://github.com/JohannesBuchner/regulargrid

points应该是一个数组列表,用于指定各点如何沿每个轴间隔开。

例如,要获取上面的单位立方体,我应该设置:

pts = ( np.array([0,1.]), )*3

或者如果我有沿最后一个轴以更高分辨率采样的数据,我可能会设置:

pts = ( np.array([0,1.]), np.array([0,1.]), np.array([0,0.5,1.]) )

最后,values的形状必须与points隐式布局的网格相对应。例如,

val_size = map(lambda q: q.shape[0], pts)
vals = np.zeros( val_size )

# make an arbitrary function to test:
func = lambda pt: (pt**2).sum()

# collect func's values at grid pts
for i in range(pts[0].shape[0]):
    for j in range(pts[1].shape[0]):
        for k in range(pts[2].shape[0]):
            vals[i,j,k] = func(np.array([pts[0][i], pts[1][j], pts[2][k]]))

最后,

rgi = irp.RegularGridInterpolator(points=pts, values=vals)

按需运行并执行。