0

I have a np.array of 50 elements. For example:

data = np.array([9.22, 9. , 9.01, ..., 7.98, 6.77, 7.3 ])

For each element of the data np.array, I have a x and y data pair (both with the same length) that I want to interpolate with. For example:

x = np.array([[ 1, 2, 3, 4, 5 ],
              ...,
              [ 1.01, 2.01, 3.02, 4.03, 5.07 ]])
y = np.array([[0. , 1. , 0.95, ..., 0.07, 0.06, 0.06],
              ...,
              [0. , 0.99 , 0.85, ..., 0.03, 0.05, 0.06]])

I want to interpolate each data element with the respective np.array of x and y.

I have the following solution using map():

def cubic_spline(i):
     return scipy.interpolate.splev(x=data[i],
                                    tck=scipy.interpolate.splrep(x[i], y[i], k=3))

list(map(cubic_spline, np.arange(len(data)))

But I'm wondering if there is a way to do it directly with scipy and numpy to optimize the execution time. Something like:

scipy.interpolate.splev(x=data,
                        tck=scipy.interpolate.splrep(x, y, k=3))

Any suggestions will be appreciated. Thanks in advance.

  • 1
    Since the target Scipy functions does not support working on many arrays and there is apparently no functions to do that, I think the answer is no. In fact, even the [internal function called](https://github.com/scipy/scipy/blob/de80faf9d3480b9dbb9b888568b64499e0e70c19/scipy/interpolate/_fitpack_impl.py#L524) does not support vectorization on several Bspline at the same time. At least, not using Scipy. You can use `fitpack` directly from Scipy but this is not standard (implementation defined and may change in the future) and calling it wrongly just cause the interpreter to crash (I tried). – Jérôme Richard Dec 22 '22 at 02:35
  • Thanks @JérômeRichard for your answer. It is a pity that it can't be used for splines, because with linear interpolation (`spicy.interpolate.interp1d`) it is possible. I wll try Scipy's `fitpack` as you suggest. Thank you! – Nelson Salazar Dec 23 '22 at 17:09
  • 1
    `fitpack` and/or `fitpack_impl` are certainly not something a user should touch! – ev-br Dec 24 '22 at 07:22

1 Answers1

1

If you have a single x array and multiple y arrays, newer interpolators (make_interp_spline, PchipInterpolator etc) support multidimensional y arrays automatically.

If you really have a collection of pairs of 1D arrays, x and y, where x arrays differ, and you want scipy to loop over these datasets, then no, scipy does not support that. You'd need to loop over them manually.

ev-br
  • 24,968
  • 9
  • 65
  • 78
  • Thanks for your answer, @ev-br! I will explore the interpolators you commented. As you mention, in some specific cases I will be able to take advantage of the flexibility of the cubic interpolator, but in general I use the manual iteration with the `map()` function that I indicated in the question. Thanks! – Nelson Salazar Dec 28 '22 at 14:34