I'm struggling hard to perform a simple linear interpolation of a datacube of size Nx*Ny*Nz into a new one that would keep the other two dimensions constant i.e. the resulting output would be Nxnew*Ny*Nz. It seems that RegularGridInterpolator from scipy seems to be the way to go, although, it is not intuitive to me how to generate the input.
from scipy.interpolate import RegularGridInterpolator
import numpy as np
x = np.linspace(1,4,11)
y = np.linspace(4,7,22)
z = np.linspace(7,9,33)
V = np.zeros((11,22,33))
for i in range(11):
for j in range(22):
for k in range(33):
V[i,j,k] = 100*x[i] + 10*y[j] + z[k]
fn = RegularGridInterpolator((x,y,z), V)
pts = np.array([[[[2,6,8],[3,5,7]], [[2,6,8],[3,5,7]]]])
out = fn(pts)
print(out, out.shape)
In this mwe, I'd like to use new points xnew = np.linspace(2,3,50), while keeping y and z the same, so the resulting array becomes of shape (50,22,33). Also, how would one generalize this to an interpolation along 1 dimension for an n-dimensional array, while keeping the rest of the coordinates the same?
As suggested in the comment, you can replace the triply-nested loop with a call to
np.meshgridto make the code more readable and efficient.As for generating the input to your
fnobject, note that its__call__method is expecting an input of shape(..., ndim). In this case,...is your desired shape (50, 22, 33), andndimis the number of coordinates (3 forx,y, andz). We can usemeshgridto generate the coordinates in three separate arrays, but to form the input tofn, we need to join them in such a way that the axis corresponding with coordinates comes last. There are several ways to do this, but the easiest is to usenp.stack.The meaning of "n" in your question about generalizing to "n-dimensional arrays" could be ambiguous. Presumably "n" represent the number of coordinates, that is, the dimensionality of your
V. In that case, generalization to situations with any number of coordinates is trivial: jiust treat those coordinates (e.g.t,u,v,w) as we have treatedx,y, andzin this example.