Search code examples
pythonarraysnumpyinterpolation

Interpolate many curves in parallel in Python


Let's say I have an N row by M column NumPy array. Each row contains the values of each of N functions, over M intervals. I have a vector X, which contains the x-values at which the functions were evaluated. I also have another NumPy array which is a 1D vector of length N. I want to interpolate each of the N functions to find their respective values at each of the N points in the vector. For instance, if I have

X = np.array([0.2,0.4,0.6,0.8])
matrix = np.array([[1,2,3,4],
                   [2,4,6,8],
                   [1,3,5,7]]) # N = 3, M = 4
vector = np.array([0.3, 0.6, 0.5])

def f(X, matrix, vector):
   # Some code
   return interpolated_values

interpolated_values should contain [1.5, 6, 4] because those are the values that each row of matrix has when linearly interpolated at the corresponding value of X.

I know I could do this using loops. But, if N is very large this would be slow. What should be in the function f to do this interpolation in parallel?

I guess the real issue comes in if X is is not the same vector for each of the N functions. I.e., X is no longer 1 x M, but it is instead N x M. Is there a way to parallelize the interpolation in this case (where the x-values of each function to be interpolated are not the same)?


Solution

  • Based on your requirement, the interp function would be beneficial to use.

    import numpy as np
    
    def f(X, matrix, vector):
        interpolated_values = np.apply_along_axis(np.interp, 0, X, matrix, vector)
        return interpolated_values
    

    Explanation of the above code:

    • np.apply_along_axis(np.interp, 0, X, matrix, vector). This applies the np.interp function on each row of the matrix.
    • np.interp. Interpolates the values of vector at the x-coordinates specified by X. Which will help you get the interpolated values for each function in parallel, and that should be much faster than using a loop if N is large.

    Code demo