【发布时间】:2017-08-16 11:35:38
【问题描述】:
给定的是二维网格上函数的 z 值。网格坐标称为 x 和 y。
现在,我想对数据进行插值,这样我就可以获得任何 (x,y) 的 z 值。
为确保我的示例清晰,我不想缩短我的代码:
import numpy as np
import pylab as pl
from scipy.interpolate import SmoothBivariateSpline
from scipy.interpolate import interp1d
def Func(x, y): # Define a test-function.
return y**2 # A parabola.
SparseGridX, SparseGridY = np.mgrid[0:1:5j, 0:1:5j] # Generate a sparsely meshed grid.
SparseGridZ = Func(SparseGridX, SparseGridY) # A function evaluated for np-arrays of arbitrary shape, again yields np-arrays of the same shape. Hence, this yields again an array.
pl.figure(num='Sparsely sampled function.')
pl.pcolor(SparseGridX, SparseGridY, SparseGridZ) # Plot the sparsely sampled function on the grid.
pl.colorbar();pl.title("Sparsely sampled function.")
FineListX = np.linspace(0,1,20) # Generate a fine-mesh list along x...
FineListY = np.linspace(0,1,20) # ... as well as along y...
FineGridX, FineGridY = np.mgrid[0:1:20j, 0:1:20j] # ... and the corresponding fine-mesh grid.
ListedSparseGridX = SparseGridX.flatten() # Attain the list of x-coordinates in the fine-mesh grid.
ListedSparseGridY = SparseGridY.flatten() # Attain the list of y-coordinates in the fine-mesh grid.
ListedSparseGridZ = Func(ListedSparseGridX,ListedSparseGridY) # This yields a list, in which an element is the result of Func for the corresponding combination of elements of FineListX and FineListY.
IntObj = SmoothBivariateSpline(ListedSparseGridX, ListedSparseGridY, ListedSparseGridZ, kx=1, ky=1) # This yields an interpolated object of the sparsely meshed points.
Interpolation = IntObj(FineListX,FineListX) # This evaluates the interpolated object at the points of the fine-mesh grid and returns the corresponding array.
pl.figure(num='Fine-meshed interpolation.')
pl.pcolor(FineGridX, FineGridY, Interpolation) # Plot the interpolation in a fine-mesh grid.
pl.colorbar();pl.title("Fine-meshed interpolation.")
IntObj1Dim = interp1d(SparseGridY[3], SparseGridZ[3]) # This yields a one-dimensional interpolated object. The index 3 is arbitrary.
Interpolation1Dim = IntObj1Dim(FineListY) # This evaluates the interpolated object along the fine-meshed y-coordinate.
pl.figure(num="Plot only along y-coordinate.")
pl.plot(SparseGridY[3],SparseGridZ[3], label="Points to interpolate", marker="o", ls="None") # Plot the points (along y) that were used for the interpolation.
pl.plot(FineListY,Interpolation[5], label="Interpolation via SmoothBivariateSpline") # Plot the interpolation (along y).
pl.plot(FineListY,Interpolation1Dim, label="Interpolation via interp1d") # Plot the one-dimensional interpolation.
pl.legend(loc="best")
pl.title("Plot only along y-coordinate.")
如您所见, interp1d 给出了一个完全符合点的分段线性函数。相反,SmoothBivariateSpline 只产生一条直线。我的目标是使用 SmoothBivariateSpline 产生一个插值,它也是分段线性的,就像使用 interp1d 产生的那样。
我尝试使用 SmoothBivariateSpline 的参数s,但没有成功。特别是,我尝试了s=0。在这种情况下,插值应该完全符合数据点,但事实并非如此。
提前致谢!
【问题讨论】:
标签: python interpolation