Eric Bal
Eric Bal

Reputation: 1185

Unable to interpolate data using Rbf in Scipy

I tried to interpolate the data using Rbf.

import numpy as np, matplotlib.pyplot as plt
from scipy.interpolate import Rbf

x = np.array([110, 112, 114, 115, 119, 120, 122, 124]).astype(float)

y = np.array([60, 61, 63, 67, 68, 70, 75, 81]).astype(float)

d = np.array([4, 6, 5, 3, 2, 1, 7, 9]).astype(float)

ulx, lrx = np.min(x), np.max(x)
uly, lry = np.max(y), np.min(y)
xi = np.linspace(ulx, lrx, 4)
yi = np.linspace(uly, lry, 4)

rbfi = Rbf(x, y, d) 
di = rbfi(xi, yi)   
plt.imshow(di)
plt.show()

However, I got:

TypeError: Invalid dimensions for image data

How is the solution?

Upvotes: 0

Views: 332

Answers (1)

hpaulj
hpaulj

Reputation: 231335

With your original data (from the SO with griddata), this works:

Clean up the x,y, removing the outliers:

yreg=y.reshape(15,15)[:,[0]].repeat(15,1).flatten()
xreg=x.reshape(15,15)[[0],:].repeat(15,0).flatten()
ulx, lrx = np.min(xreg), np.max(xreg)
uly, lry = np.max(yreg), np.min(yreg)
N = 20
xi = np.linspace(ulx, lrx, N)
yi = np.linspace(uly, lry, N)
# grided_data = interpolate.griddata((xreg, yreg), z, (xi.reshape(1,-1), yi.reshape(-1,1)),
    method='nearest',fill_value=0)

I don't think Rbf (and similar interpolators) handle broadcasting like griddata does. So I have to construct 2 vectors defining all the interpolation points.

yyi=np.repeat(yi,N)
xxi=np.repeat(xi[None,:],N,0).flatten()

rbfi=interpolate.Rbf(xreg,yreg,z,function='linear')
zzi=rbfi(xxi,yyi).reshape(N,N)

Timing wise, Rbf is noticeably slower than griddata.

With xreg, yreg, the interpolation results (for both methods) look similar to the image of z.reshape(15,15) - a square with 2 square plateaus in the lower left corner.

Upvotes: 2

Related Questions