window_ops icon indicating copy to clipboard operation
window_ops copied to clipboard

Add Support for Negative Shifting In `window_ops.shift.shift_array`

Open tempoxylophone opened this issue 8 months ago • 1 comments

New behavior:

test_input = np.array([1.0, 1.0])

shift_array(t_input, offset=-1)

array([1., nan])

Old behavior:

test_input = np.array([1.0, 1.0])

shift_array(t_input, offset=-1)

array([1., 8.69623725e-311) (when compiled with numba, reads out of bounds)

The same code not compiled using numba will throw an IndexError:

>>> import numpy as np
>>> def shift_array(input_array: np.ndarray, offset: int) -> np.ndarray:
...     n_samples = input_array.size
...     output_array = np.full_like(input_array, np.nan)
...     for i in range(n_samples - offset):
...         output_array[i + offset] = input_array[i]
...     return output_array
...
>>> x = np.array([1.0, 1.0])
>>> shift_array(x, offset=-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in shift_array
IndexError: index 2 is out of bounds for axis 0 with size 2
>>>

This is expected behavior because of numba's Bounds Checking design. More specifically, an IndexError is deliberately not thrown - but we do read from out of bounds.

This PR adds the ability to shift an array in the opposite direction without quietly reading from out of bounds and without enabling bounds checking with numba.jit(boundscheck=True).

tempoxylophone avatar Jun 02 '24 03:06 tempoxylophone