Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scipy griddata with 'linear' and 'cubic' yields nan

the following code should produce griddata. But in case I choose as interpolation type 'cubic' or 'linear' I am getting nan's in the z grid. Wen i'm choosing 'nearest' everything is running fine. Here is an example code:

import numpy as np
from scipy.interpolate import griddata

x = np.array([0.03,0.05,0033])
y = np.array([0.004,0.01,0.02])
z = np.array([1,2,3])


xy = np.zeros((2,np.size(x)))
xy[0] = x
xy[1] = y
xy = xy.T

grid_x, grid_y = np.mgrid[0.0:0.09:250*1j, 0.0:0.03:250*1j] #generating the grid


i_type= 'cubic' #nearest, linear, cubic
grid_z = griddata(xy, z, (grid_x, grid_y), method=i_type)

#check if there is a nan in the z grid:
print np.isnan(grid_z).any()

I don't have any idea why this is not working..

like image 730
Jan SE Avatar asked Jun 12 '18 11:06

Jan SE


Video Answer


1 Answers

Your area you look at is simply much larger than your input points. This doesn't matter for 'nearest' as this always puts the nearest value to a certain coordinate. But 'linear' and 'cubic' do not extrapolate but fill the values which are not within the input area with nan by default.

See also the docs of griddata:

fill_value : float, optional
Value used to fill in for requested points outside of the convex hull of the input points. If not provided, then the default is nan. This option has no effect for the ‘nearest’ method.

Best understandable when plotted by imshow:

enter image description here

plot created with:

import numpy as np
from scipy.interpolate import griddata

x = np.array([0.03,0.05,0.033])
y = np.array([0.004,0.01,0.02])
z = np.array([1,2,3])


xy = np.zeros((2,np.size(x)))
xy[0] = x
xy[1] = y
xy = xy.T

grid_x, grid_y = np.mgrid[0.0:0.09:250*1j, 0.0:0.03:250*1j] #generating the grid

fig, axs = plt.subplots(3)
for i, i_type in enumerate(['cubic', 'nearest', 'linear']): #, cubic
    grid_z = griddata(xy, z, (grid_x, grid_y), method=i_type)

    #check if there is a nan in the z grid:
    axs[i].imshow(grid_z)
    axs[i].set_title(i_type)

plt.tight_layout()
like image 197
SpghttCd Avatar answered Nov 03 '22 21:11

SpghttCd