正确使用scipy.interpolate.RegularGridInterpolator

Mat*_*ock 4 python interpolation numpy scipy

对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)
Run Code Online (Sandbox Code Playgroud)

现在,RegularGridInterpolator采取一个points论点和一个values论点.

points:float的ndarray元组,带有形状(m1,),...,(mn,)n个维度中定义规则网格的点.

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

我将此解释为可以这样调用:

import scipy.interpolate as irp

rgi = irp.RegularGridInterpolator(X, F)
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,我收到以下错误:

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

我在文档中误解了什么?

uho*_*hoh 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])
Run Code Online (Sandbox Code Playgroud)

收益:

1.93765972087
1.92113615659
Run Code Online (Sandbox Code Playgroud)


Mat*_*ock 7

好的,当我回答我自己的问题时,我感到愚蠢,但是我在原始regulargrid库的文档帮助下发现了我的错误:

https://github.com/JohannesBuchner/regulargrid

points 应该是一个数组列表,指定点沿每个轴的间距.

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

pts = ( np.array([0,1.]), )*3
Run Code Online (Sandbox Code Playgroud)

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

pts = ( np.array([0,1.]), np.array([0,1.]), np.array([0,0.5,1.]) )
Run Code Online (Sandbox Code Playgroud)

最后,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]]))
Run Code Online (Sandbox Code Playgroud)

最后,

rgi = irp.RegularGridInterpolator(points=pts, values=vals)
Run Code Online (Sandbox Code Playgroud)

运行并按要求执行.