Skip to content

RF: Use safe resizing for ArraySequence extension #724

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion nibabel/streamlines/array_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ def is_ndarray_of_int_or_bool(obj):
np.issubdtype(obj.dtype, np.bool_)))


def _safe_resize(a, shape):
""" Resize an ndarray safely, using minimal memory """
try:
a.resize(shape)
except ValueError:
a = a.copy()
a.resize(shape, refcheck=False)
return a


class _BuildCache(object):
def __init__(self, arr_seq, common_shape, dtype):
self.offsets = list(arr_seq._offsets)
Expand Down Expand Up @@ -196,7 +206,7 @@ def _resize_data_to(self, n_rows, build_cache):
if self._data.size == 0:
self._data = np.empty(new_shape, dtype=build_cache.dtype)
else:
self._data.resize(new_shape)
self._data = _safe_resize(self._data, new_shape)

def shrink_data(self):
self._data.resize((self._get_next_offset(),) + self.common_shape,
Expand Down
4 changes: 4 additions & 0 deletions nibabel/streamlines/tests/test_array_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,10 @@ def test_arraysequence_extend(self):
seq = SEQ_DATA['seq'].copy() # Copy because of in-place modification.
assert_raises(ValueError, seq.extend, data)

# Extend after extracting some slice
working_slice = seq[:2]
seq.extend(ArraySequence(new_data))

def test_arraysequence_getitem(self):
# Get one item
for i, e in enumerate(SEQ_DATA['seq']):
Expand Down