我有在3D网格上指定的数据,例如:
import numpy as np
f = np.random.rand(4, 4, 4)
有没有办法为任意点(即不在网格上)获取此数据的(插值)值? interpolation文档显示您可以显示此类数据,但我不知道如何获取值 f(arbitrary_point)。感谢。
答案 0 :(得分:1)
scipy.interpolate.griddata允许N维插值。下面是一个3D示例,我在网格上评估f(r)= cos(r)^ 2,然后插入网格数据。可以在下面绘制网格数据或插值数据,以验证插值是否正常工作:
%matplotlib inline
from __future__ import division
import numpy as np
from scipy import interpolate
from math import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
#define grid points and f(r) = cos^2(r) and format for interpolation:
N = 10;
x_range, y_range, z_range = [np.linspace(0,pi,N), np.linspace(0,pi,N), np.linspace(0,pi,N)];
x_grid,y_grid,z_grid = np.meshgrid(x_range,y_range,z_range);
xi, yi, zi = x_grid.ravel(), y_grid.ravel(), z_grid.ravel();
xi, yi, zi = xi[:], yi[:], zi[:];
f = np.cos((xi**2 + yi**2 + zi**2)**(1/2))**2;
points = np.dstack([xi, yi, zi]);
points = points[0,:,:];
#create random points and interpolate f(r):
[x_rand, y_rand, z_rand] = [pi*np.random.rand(N**3), pi*np.random.rand(N**3), pi*np.random.rand(N**3)]
random_points = np.dstack([x_rand, y_rand, z_rand])
random_points = random_points[0,:,:]
f_interpolated = interpolate.griddata(points, f, random_points, method='linear');
#PLOT THE RESULTS:
fig = plt.figure()
ax = fig.gca(projection='3d')
#_____________PLOT GRID OR INTERPOLATED DATA ______________
surf = ax.scatter(xi,yi,zi,c=f,s=20,alpha=.8)
surf = ax.scatter(x_rand,y_rand,z_rand,c=f_interpolated)
fig.colorbar(surf, aspect=16)
plt.show()