scipy: Unexpected behaviour for non-strictly monotonic values in scipy.interpolate.interp1d

I am having an issue with some unexpected behaviour with the scipy.interpolate.interp1d method for the following kinds:

  • kind= ['nearest','linear', 'previous' and 'next'] (i.e. kinds not involving spline interpolation according to the doc)

When providing non-strictly monotonic x values, unexpected results are returned rather than the method failing:

Reproducing code example:

import numpy as np
from scipy.interpolate import interp1d

x = np.array([0, 1, 1])
y = np.array([0, 1, 0])

for kind in ['nearest', 'linear', 'previous', 'next']:
    f = interp1d(x,y,kind=kind)
    print("{k}: ".format(k=kind), f(x))

Output

nearest:  [0. 1. 1.]
linear:  [0. 1. 1.]
previous:  [0. 0. 0.]
next:  [0. 1. 1.]

Error message:

For kind='cubic' it fails in a similar matter as I would expect it to for the others:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-30-064ad468e798> in <module>
----> 1 f = interp1d(x,y,kind='cubic')
      2 f(x)

C:\anaconda\envs\atlite\lib\site-packages\scipy\interpolate\interpolate.py in __init__(***failed resolving arguments***)
    533 
    534             self._spline = make_interp_spline(xx, yy, k=order,
--> 535                                               check_finite=False)
    536             if rewrite_nan:
    537                 self._call = self.__class__._call_nan_spline

C:\anaconda\envs\atlite\lib\site-packages\scipy\interpolate\_bsplines.py in make_interp_spline(x, y, k, t, bc_type, axis, check_finite)
    797 
    798     if x.ndim != 1 or np.any(x[1:] <= x[:-1]):
--> 799         raise ValueError("Expect x to be a 1-D sorted array_like.")
    800     if k < 0:
    801         raise ValueError("Expect non-negative k.")

ValueError: Expect x to be a 1-D sorted array_like.

Scipy/Numpy/Python version information:

[1]: import sys, scipy, numpy; print(scipy.__version__, numpy.__version__, sys.version_info)
1.2.1 1.15.4 sys.version_info(major=3, minor=6, micro=6, releaselevel='final', serial=0)

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 15 (10 by maintainers)

Most upvoted comments

@euronion sorry I tried a bunch of things and my comment was incomplete. Also x = np.array([0, 2, 1]) gives consistent results, it’s just [0, 1, 1] with two identical elements that does’t. The sorting of indices looks right; there’s something special for duplicate x-values here.