Skip to content

Commit 3d21376

Browse files
matthew-bretteffigies
authored andcommitted
NF: add reshape_dataobj function
At some point soon, we plan to add a `reshape` method to some arrayproxy objects. Make space for that extension to the API, by adding a function that selects that method when possible, otherwise falling back to the numpy array API.
1 parent c3ec7f0 commit 3d21376

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

nibabel/arrayproxy.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
"""
2828
import warnings
2929

30+
import numpy as np
31+
3032
from .volumeutils import array_from_file, apply_read_scaling
3133
from .fileslice import fileslice
3234
from .keywordonly import kw_only_meth
@@ -164,3 +166,10 @@ def is_proxy(obj):
164166
return obj.is_proxy
165167
except AttributeError:
166168
return False
169+
170+
171+
def reshape_dataobj(obj, shape):
172+
""" Use `obj` reshape method if possible, else numpy reshape function
173+
"""
174+
return (obj.reshape(shape) if hasattr(obj, 'reshape')
175+
else np.reshape(obj, shape))

nibabel/tests/test_arrayproxy.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import numpy as np
1919

20-
from ..arrayproxy import ArrayProxy, is_proxy
20+
from ..arrayproxy import ArrayProxy, is_proxy, reshape_dataobj
2121
from ..nifti1 import Nifti1Header
2222

2323
from numpy.testing import assert_array_equal, assert_array_almost_equal
@@ -158,6 +158,33 @@ class NP(object):
158158
assert_false(is_proxy(NP()))
159159

160160

161+
def test_reshape_dataobj():
162+
# Test function that reshapes using method if possible
163+
shape = (1, 2, 3, 4)
164+
hdr = FunkyHeader(shape)
165+
bio = BytesIO()
166+
prox = ArrayProxy(bio, hdr)
167+
arr = np.arange(np.prod(shape), dtype=prox.dtype).reshape(shape)
168+
bio.write(b'\x00' * prox.offset + arr.tostring(order='F'))
169+
assert_array_equal(prox, arr)
170+
assert_array_equal(reshape_dataobj(prox, (2, 3, 4)),
171+
np.reshape(arr, (2, 3, 4)))
172+
assert_equal(prox.shape, shape)
173+
assert_equal(arr.shape, shape)
174+
assert_array_equal(reshape_dataobj(arr, (2, 3, 4)),
175+
np.reshape(arr, (2, 3, 4)))
176+
assert_equal(arr.shape, shape)
177+
178+
class ArrGiver(object):
179+
180+
def __array__(self):
181+
return arr
182+
183+
assert_array_equal(reshape_dataobj(ArrGiver(), (2, 3, 4)),
184+
np.reshape(arr, (2, 3, 4)))
185+
assert_equal(arr.shape, shape)
186+
187+
161188
def test_get_unscaled():
162189
# Test fetch of raw array
163190
class FunkyHeader2(FunkyHeader):

0 commit comments

Comments
 (0)