Skip to content

Conversation

@tempoxylophone
Copy link

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).

@review-notebook-app
Copy link

Check out this pull request on  ReviewNB

See visual diffs & provide feedback on Jupyter Notebooks.


Powered by ReviewNB

" output_array = np.full_like(input_array, np.nan)\n",
" for i in range(n_samples - offset):\n",
" ub = n_samples - offset if offset > 0 else n_samples\n",
" lb = offset * -1 if offset < 0 else 0\n",
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
" lb = offset * -1 if offset < 0 else 0\n",
" lb = -offset if offset < 0 else 0\n",

Copy link
Owner

@jmoralez jmoralez left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for your contribution! Can you please also export the code (nbdev_export) and clean the notebook (nbdev_clean)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants