Amanda
Amanda

Reputation: 2163

Understanding interpn function of scipy.interpolate

I am trying to understand the working of the function scipy.interpolate. I created a small setup but it is giving errors. Here is what I did:

import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.arange(10)
gx, gy = np.meshgrid(x,y)
v = np.ones((10,10))


sample_at = np.random.random((10,10))

interpolated = scipy.interpolate.interpn((gx, gy), v, sample_at)


print(interpolated.shape)

This gives an error:

    Traceback (most recent call last):
File "test.py", line 13, in <module>
    interpolated = scipy.interpolate.interpn((gx, gy), v, sample_at)
File "/home/lib/python3.5/site-packages/scipy/interpolate/interpolate.py", line 2624, in interpn
    "1-dimensional" % i)
ValueError: The points in dimension 0 must be 1-dimensional

What is happening here?

Upvotes: 2

Views: 3977

Answers (1)

gboffi
gboffi

Reputation: 25093

You are making a wrong assumption wrt the structure of the grid requested by interpn

ValueError: The points in dimension 0 must be 1-dimensional

This message, a little bit obscure, references the elements of the grid and tells you that they must be 1-dimensional, or in other words you must call interpn not with (gx, gy) as first argument but with (x, y).

scipy.interpolate.interpn((x, y), v, sample_at)

But there is another wrong assumption in your code, because if you use the call above, with your definition of sample_at, you'll get a different error

ValueError: The requested sample points xi have dimension 10, but this RegularGridInterpolator has dimension 2

that hopefully has a clearer meaning: if your grid has two dimensions (x and y, that is) all your points on which interpn has to interpolate must be 2-dimensional as well... In other words, in your example the LAST dimension of the grid must be 2

Putting it all together (I'll use a location matrix sample_at of 5 rows by 3 columns of 2-D points in this example) we have

In [69]: import numpy as np 
    ...: import scipy.interpolate 
    ...: import matplotlib.pyplot as plt 
    ...:  
    ...: x = np.arange(10) 
    ...: y = np.arange(10) 
    ...: v = np.ones((10,10)) 
    ...: sample_at = 8*np.random.random((30)).reshape(5, 3, 2) 
    ...:  
    ...: scipy.interpolate.interpn((x, y), v, sample_at)                                                       
Out[69]: 
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

PS: read the source code1, the comments in it are much better than the error messages...


(1) for me the source code is located at

~/lib/miniconda3/lib/python3.7/site-packages/scipy/interpolate/interpolate.py

Upvotes: 6

Related Questions