torch_pchip

selfeeg.utils.utils.torch_pchip(x: 1D Tensor, y: ND Tensor, xv: 1D Tensor, save_memory: bool = True, new_y_max_numel: int = 4194304) torch.Tensor[source]

performs the pchip interpolation on the last dimension of the input tensor.

This function is a pytorch adaptation of the scipy’s pchip_interpolate [pchip] . It performs sp-pchip interpolation (Shape Preserving Piecewise Cubic Hermite Interpolating Polynomial) on the last dimension of the y tensor. x is the original time grid and xv new virtual grid. So, the new values of y at time xv are given by the polynomials evaluated at the time grid x.

This function is compatible with GPU devices.

Parameters:
  • x (1D Tensor) – Tensor with the original time grid. Must be the same length as the last dimension of y.

  • y (ND Tensor) – Tensor to interpolate. The last dimension must be the time dimension of the signals to interpolate.

  • xv (1D Tensor) – Tensor with the new virtual grid, i.e. the time points where to interpolate

  • save_memory (bool, optional) –

    Whether to perform the interpolation on subsets of the y tensor by recursive function calls or not. Does not apply if y is a 1-D tensor. If set to False memory usage can greatly increase (for example with a 128 MB tensor, the memory usage of the function is 1.2 GB), but it can speed up the process. However, this is not the case for all devices and performance may also decrease.

    Default = True

  • new_y_max_numel (int, optional) –

    The number of elements which the tensor needs to surpass in order to make the function start doing recursive calls. It can be considered as an indicator of the maximum allowed memory usage since the lower the number, the lower the memory used.

    Default = 256*1024*16 (approximately 16s of recording of a 256 Channel EEG sampled at 1024 Hz).

Returns:

new_y (torch.Tensor) – The pchip interpolated tensor.

Note

Some technical information and difference with other interpolation can be found here: https://blogs.mathworks.com/cleve/2012/07/16/splines-and-pchips/

References

Example

>>> from scipy.interpolate import pchip_interpolate
>>> import numpy as np
>>> import selfeeg.utils
>>> import torch
>>> x = torch.zeros(16,32,1024) + torch.sin(torch.linspace(0, 8*torch.pi,1024))*500
>>> xnp = x.numpy()
>>> x_pchip = utils.torch_pchip(torch.arange(1024), x, torch.linspace(0,1023,475)).numpy()
>>> xnp_pchip = pchip_interpolate(np.arange(1024),xnp, np.linspace(0,1023,475), axis=-1)
>>> print(
...     np.isclose(x_pchip, xnp_pchip, rtol=1e-3,atol=0.5*1e-3).sum()==16*32*475
... ) # Should return True