0
$\begingroup$

I am writing some functions to interpolate data. While using interp2D, somehow, a sample matrix works but when I change the size of the matrix, it returns an error.

#!/usr/bin/python3

# 
# Useful interpolation functions in python.
# 

import numpy as np
import scipy.interpolate

def interp_2d(x,y,fxy,x_desired,y_desired):

    interp_func = scipy.interpolate.interp2d(x, y, fxy, kind='cubic')

    return interp_func(x_desired,y_desired)

#
# Main function.
#

def main():

    x   =  np.array([0.0,1.0,2.0,3.0])
    y   =  np.array([0.0,1.0,2.0,3.0])
    fxy =  np.array([[50.0,60.0,70.0,80.0],
                     [50.0,60.0,70.0,80.0],
                     [50.0,60.0,70.0,80.0],
                     [50.0,60.0,70.0,80.0]])

    # With the current definition of x,y and fxy works.

    x_desired = 1.0
    y_desired = 1.0

    print(interp_2d(x,y,fxy,x_desired,y_desired)[0]) # returns 60.0, ok !

    # With this definition, it crashes.

    x   =  np.array([0.0,1.0])
    y   =  np.array([0.0,1.0])
    fxy =  np.array([[50.0,60.0],[50.0,60.0]])

    x_desired = 1.0
    y_desired = 1.0

    print(interp_2d(x,y,fxy,x_desired,y_desired)[0]) # Crashes, should be 60 as well.


if __name__== "__main__":
    main()

It is still a squared matrix, however, it do not handles the problem properly.

The error it returns is:
Traceback (most recent call last):
  File "./interp_ask.py", line 49, in <module>
    main()
  File "./interp_ask.py", line 45, in main
    print(interp_2d(x,y,fxy,x_desired,y_desired)[0]) # Crashes
  File "./interp_ask.py", line 12, in interp_2d
    interp_func = scipy.interpolate.interp2d(x, y, fxy, kind='cubic')
  File "/usr/lib/python3.7/site-packages/scipy/interpolate/interpolate.py", line 249, in __init__
    kx=kx, ky=ky, s=0.0)
dfitpack.error: (mx>kx) failed for hidden mx: regrid_smth:mx=2

Thank you all !

$\endgroup$

1 Answer 1

2
$\begingroup$

According to the documentation, the minimum number of data points in the matrix should be $(k+1)^2$, where $k=1$, $k=3$ and $k=5$ for linear, cubic and quintic interpolations, respectively. Indeed, changing kind='cubic' to kind='linear' in your code gets rid of the error.

You probably want to check the size of the matrix at the beginning of the interp_2d function to either change the interpolation type and/or return an error if the matrix size is too small.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.