patrick-kidger / torchcubicspline

Interpolating natural cubic splines. Includes batching, GPU support, support for missing values, evaluating derivatives of the spline, and backpropagation.
Apache License 2.0
198 stars 18 forks source link

Interpolating over 2D-grid. #10

Closed JeanKaddour closed 2 years ago

JeanKaddour commented 2 years ago

Hi Patrick,

first of all, thank you very much for creating this great library.

I've got a very basic question:

I want to interpolate over a 2D-grid. In SciPy, I run the following code:

import numpy as np
from scipy import interpolate
# Data Generation
X = np.linspace(0.0, 1.0, num=12)
Y = np.linspace(0.0, 1.0, num=4)
z_list = [
    [0.8, 1.6, 2.0, 3.0],
    [0.6, 1.4, 2.5, 2.9],
    [0.2, 0.9, 0.6, 2.8],
    [0.5, 1.0, 1.2, 2.7],
    [0.5, 1.5, 1.6, 2.6],
    [0.5, 1.4, 1.5, 2.5],
    [0.3, 1.4, 1.2, 2.4],
    [0.5, 1.2, 1.5, 2.3],
    [0.4, 1.2, 1.5, 2.0],
    [0.35, 0.9, 1.4, 1.5],
    [0.35, 0.9, 1.4, 1.5],
    [0.35, 0.9, 1.4, 1.5],
]
Z = np.array(z_list)
Z = Z.transpose()
interpol_function = interpolate.interp2d(X, Y, Z, kind="cubic")

Then, I can evaluate interpol_function(X, Y) at arbitrary X and Y.

I tried to match the dimensions to your "batch-length-channel" format, resulting in

num_X, num_Y = 12, 4
X = torch.linspace(0.0, 1.0, steps=num_X)
Y = torch.linspace(0.0, 1.0, steps=num_Y)
t = torch.meshgrid([X, Y])
x = torch.Tensor(
    [
        [0.8, 1.6, 2.0, 3.0],
        [0.6, 1.4, 2.5, 2.9],
        [0.2, 0.9, 0.6, 2.8],
        [0.5, 1.0, 1.2, 2.7],
        [0.5, 1.5, 1.6, 2.6],
        [0.5, 1.4, 1.5, 2.5],
        [0.3, 1.4, 1.2, 2.4],
        [0.5, 1.2, 1.5, 2.3],
        [0.4, 1.2, 1.5, 2.0],
        [0.35, 0.9, 1.4, 1.5],
        [0.35, 0.9, 1.4, 1.5],
        [0.35, 0.9, 1.4, 1.5],
    ]
)
x = torch.reshape(x, (num_X, num_Y, 1))
coeffs = natural_cubic_spline_coeffs(t, x)

However, this results in an error due to the time tensor t not containing one-dimensional floating point values. How would you recommend to reshape the dimensions here?

patrick-kidger commented 2 years ago

Unfortunately torchcubicspline isn't designed to handle two dimensions. It's only capable of interpolating problems of the form f(t) = x, where t is a scalar.

JeanKaddour commented 2 years ago

Got it. Thank you very much!