Skip to content

Commit f54ae11

Browse files
committed
ENH: External GIFTI data files are mem-mapped by default
1 parent 39399fa commit f54ae11

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

nibabel/gifti/parse_gifti_fast.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def read_data_block(darray, fname, data, mmap):
5858
5959
Returns
6060
-------
61-
numpy.ndarray containing the parsed data
61+
``numpy.ndarray`` or ``numpy.memmap`` containing the parsed data
6262
"""
6363
if mmap not in (True, False, 'c', 'r', 'r+'):
6464
raise ValueError("mmap value should be one of True, False, 'c', "
@@ -87,10 +87,20 @@ def read_data_block(darray, fname, data, mmap):
8787
ext_fname = op.join(op.dirname(fname), darray.ext_fname)
8888
if not op.exists(ext_fname):
8989
raise GiftiParseError('Cannot locate external file ' + ext_fname)
90-
with open(ext_fname, 'rb') as f:
91-
f.seek(darray.ext_offset)
92-
nbytes = np.prod(darray.dims) * dtype().itemsize
93-
buff = f.read(nbytes)
90+
if mmap:
91+
newarr = np.memmap(ext_fname,
92+
dtype=dtype,
93+
mode=mmap,
94+
offset=darray.ext_offset,
95+
shape=tuple(darray.dims))
96+
else:
97+
# We can replace this with a call to np.fromfile in numpy>=1.17,
98+
# as an "offset" paramter was added in that version.
99+
with open(ext_fname, 'rb') as f:
100+
f.seek(darray.ext_offset)
101+
nbytes = np.prod(darray.dims) * dtype().itemsize
102+
buff = f.read(nbytes)
103+
newarr = np.frombuffer(buff, dtype=dtype)
94104

95105
# Numpy arrays created from bytes objects are read-only.
96106
# Neither b64decode nor decompress will return bytearrays, and there
@@ -107,9 +117,9 @@ def read_data_block(darray, fname, data, mmap):
107117
# GIFTI_ENCODING_B64GZ
108118
buff = bytearray(zlib.decompress(dec))
109119
del dec
120+
newarr = np.frombuffer(buff, dtype=dtype)
110121

111122
sh = tuple(darray.dims)
112-
newarr = np.frombuffer(buff, dtype=dtype)
113123
if len(newarr.shape) != len(sh):
114124
newarr = newarr.reshape(
115125
sh, order=array_index_order_codes.npcode[darray.ind_ord])

0 commit comments

Comments
 (0)