Scipy interpolation of a large matrix

I have ndarray (Z) with approximately 500,000 elements on a rectangular grid (X, Y).

Now I want to interpolate values ​​at about 100 locations in x, y, which are not necessarily in the grid.

I have code working in Matlab:

data = interp2(X,Y,Z, x,y);

However, when I try to use the same approach with scipy.interpolate, I get different errors depending on the method. For example, interp2d fails with a MemoryError if I specify kind = 'linear'and "OverflowError: too many data points to interpolate" if I specify kind='cubic'. I also tried Rbfand bisplev, but they also fail.

So, the question arises: is there an interpolation function that allows interpolation of large matrices? Is there any other solution to the problem? (Or do I need to code a function that selects a suitable area around the points for interpolation and calls then interp2d?)

In addition: how to do this with complex numbers?

+2
source share
2 answers

Since your data is in a grid, you can use RectBivariateSpline .

To work with complex numbers you can interpolate data.real, and data.imagseparately (subroutines FITPACK IIRC not handle complex data).

+2
source

edit: . , !

, , , , , .

from scipy import interpolate
import numpy as np

def my_interp(X, Y, Z, x, y, spn=3):
    xs,ys = map(np.array,(x,y))
    z = np.zeros(xs.shape)
    for i,(x,y) in enumerate(zip(xs,ys)):
        # get the indices of the nearest x,y
        xi = np.argmin(np.abs(X[0,:]-x))
        yi = np.argmin(np.abs(Y[:,0]-y))
        xlo = max(xi-spn, 0)
        ylo = max(yi-spn, 0)
        xhi = min(xi+spn, X[0,:].size)
        yhi = min(yi+spn, Y[:,0].size)
        # make slices of X,Y,Z that are only a few items wide
        nX = X[xlo:xhi, ylo:yhi]
        nY = Y[xlo:xhi, ylo:yhi]
        nZ = Z[xlo:xhi, ylo:yhi]
        intp = interpolate.interp2d(nX, nY, nZ)
        z[i] = intp(x,y)[0]
    return z

N = 1000
X,Y = np.meshgrid(np.arange(N), np.arange(N))
Z = np.random.random((N, N))

print my_interp(X, Y, Z, [13.2, 999.9], [0.01, 45.3])
+1

Source: https://habr.com/ru/post/1612591/


All Articles