0
給定的是二維網格上函數的值z。網格座標稱爲x和y。通過SmoothBivariateSpline分段線性插值
現在,我想插入數據,這樣我就可以得到任何(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
。在這種情況下,插值函數應該完全符合數據點,但不是。
在此先感謝!