Skip to content

Commit 80487b7

Browse files
authored
Merge pull request #899 from effigies/rf/tobytes
MNT: Drop deprecated ndarray.tostring for tobytes
2 parents ff7c276 + d63a4a0 commit 80487b7

28 files changed

+82
-83
lines changed

nibabel/analyze.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,7 @@ def data_to_fileobj(self, data, fileobj, rescale=True):
509509
>>> str_io = BytesIO()
510510
>>> data = np.arange(6).reshape(1,2,3)
511511
>>> hdr.data_to_fileobj(data, str_io)
512-
>>> data.astype(np.float64).tostring('F') == str_io.getvalue()
512+
>>> data.astype(np.float64).tobytes('F') == str_io.getvalue()
513513
True
514514
'''
515515
data = np.asanyarray(data)

nibabel/benchmarks/bench_fileslice.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def run_slices(file_like, repeat=3, offset=0, order='F'):
4848
times_arr = np.zeros((n_dim, n_slicers))
4949
with ImageOpener(file_like, 'wb') as fobj:
5050
fobj.write(b'\0' * offset)
51-
fobj.write(arr.tostring(order=order))
51+
fobj.write(arr.tobytes(order=order))
5252
with ImageOpener(file_like, 'rb') as fobj:
5353
for i, L in enumerate(SHAPE):
5454
for j, slicer in enumerate(_slices_for_len(L)):

nibabel/dft.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,7 @@ def as_png(self, index=None, scale_to_slice=True):
144144
max = data.max()
145145
data = data * 255 / (max - min)
146146
data = data.astype(numpy.uint8)
147-
im = frombytes('L', (self.rows, self.columns),
148-
data.tostring())
147+
im = frombytes('L', (self.rows, self.columns), data.tobytes())
149148

150149
s = BytesIO()
151150
im.save(s, 'PNG')
@@ -213,7 +212,7 @@ def as_nifti(self):
213212
s = BytesIO()
214213
hdr.write_to(s)
215214

216-
return s.getvalue() + data.tostring()
215+
return s.getvalue() + data.tobytes()
217216

218217
def nifti_size(self):
219218
return 352 + 2 * len(self.storage_instances) * self.columns * self.rows

nibabel/ecat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -981,7 +981,7 @@ def to_file_map(self, file_map=None):
981981

982982
# Write subheader
983983
subhdr = subheaders.subheaders[index]
984-
imgf.write(subhdr.tostring())
984+
imgf.write(subhdr.tobytes())
985985

986986
# Seek to the next image block
987987
pos = imgf.tell()

nibabel/externals/netcdf.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,7 @@ def flush(self):
421421
def _write(self):
422422
self.fp.seek(0)
423423
self.fp.write(b'CDF')
424-
self.fp.write(array(self.version_byte, '>b').tostring())
424+
self.fp.write(array(self.version_byte, '>b').tobytes())
425425

426426
# Write headers and data.
427427
self._write_numrecs()
@@ -531,7 +531,7 @@ def _write_var_data(self, name):
531531

532532
# Write data.
533533
if not var.isrec:
534-
self.fp.write(var.data.tostring())
534+
self.fp.write(var.data.tobytes())
535535
count = var.data.size * var.data.itemsize
536536
self._write_var_padding(var, var._vsize - count)
537537
else: # record variable
@@ -553,7 +553,7 @@ def _write_var_data(self, name):
553553
if not rec.shape and (rec.dtype.byteorder == '<' or
554554
(rec.dtype.byteorder == '=' and LITTLE_ENDIAN)):
555555
rec = rec.byteswap()
556-
self.fp.write(rec.tostring())
556+
self.fp.write(rec.tobytes())
557557
# Padding
558558
count = rec.size * rec.itemsize
559559
self._write_var_padding(var, var._vsize - count)
@@ -606,7 +606,7 @@ def _write_att_values(self, values):
606606
if not values.shape and (values.dtype.byteorder == '<' or
607607
(values.dtype.byteorder == '=' and LITTLE_ENDIAN)):
608608
values = values.byteswap()
609-
self.fp.write(values.tostring())
609+
self.fp.write(values.tobytes())
610610
count = values.size * values.itemsize
611611
self.fp.write(b'\x00' * (-count % 4)) # pad
612612

@@ -791,15 +791,15 @@ def _pack_begin(self, begin):
791791
self._pack_int64(begin)
792792

793793
def _pack_int(self, value):
794-
self.fp.write(array(value, '>i').tostring())
794+
self.fp.write(array(value, '>i').tobytes())
795795
_pack_int32 = _pack_int
796796

797797
def _unpack_int(self):
798798
return int(frombuffer(self.fp.read(4), '>i')[0])
799799
_unpack_int32 = _unpack_int
800800

801801
def _pack_int64(self, value):
802-
self.fp.write(array(value, '>q').tostring())
802+
self.fp.write(array(value, '>q').tobytes())
803803

804804
def _unpack_int64(self):
805805
return frombuffer(self.fp.read(8), '>q')[0]
@@ -1045,7 +1045,7 @@ def _get_encoded_fill_value(self):
10451045
"""
10461046
if '_FillValue' in self._attributes:
10471047
fill_value = np.array(self._attributes['_FillValue'],
1048-
dtype=self.data.dtype).tostring()
1048+
dtype=self.data.dtype).tobytes()
10491049
if len(fill_value) == self.itemsize():
10501050
return fill_value
10511051
else:

nibabel/freesurfer/io.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,7 @@ def _serialize_volume_info(volume_info):
613613
if not (np.array_equal(volume_info[key], [20]) or np.array_equal(
614614
volume_info[key], [2, 0, 20])):
615615
warnings.warn("Unknown extension code.")
616-
strings.append(np.array(volume_info[key], dtype='>i4').tostring())
616+
strings.append(np.array(volume_info[key], dtype='>i4').tobytes())
617617
elif key in ('valid', 'filename'):
618618
val = volume_info[key]
619619
strings.append('{0} = {1}\n'.format(key, val).encode('utf-8'))

nibabel/freesurfer/mghformat.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,7 @@ def writehdr_to(self, fileobj):
407407
buffer=self.binaryblock)
408408
# goto the very beginning of the file-like obj
409409
fileobj.seek(0)
410-
fileobj.write(hdr_nofooter.tostring())
410+
fileobj.write(hdr_nofooter.tobytes())
411411

412412
def writeftr_to(self, fileobj):
413413
''' Write footer to fileobj
@@ -427,7 +427,7 @@ def writeftr_to(self, fileobj):
427427
ftr_nd = np.ndarray((), dtype=self._ftrdtype,
428428
buffer=self.binaryblock, offset=ftr_loc_in_hdr)
429429
fileobj.seek(self.get_footer_offset())
430-
fileobj.write(ftr_nd.tostring())
430+
fileobj.write(ftr_nd.tobytes())
431431

432432
def copy(self):
433433
''' Return copy of structure '''

nibabel/freesurfer/tests/test_io.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ def gen_old_annot_file(fpath, nverts, labels, rgba, names):
309309
# number of vertices
310310
fbytes += struct.pack(dt, nverts)
311311
# vertices + annotation values
312-
fbytes += bytes(vdata.astype(dt).tostring())
312+
fbytes += vdata.astype(dt).tobytes()
313313
# is there a colour table?
314314
fbytes += struct.pack(dt, 1)
315315
# number of entries in colour table
@@ -321,7 +321,7 @@ def gen_old_annot_file(fpath, nverts, labels, rgba, names):
321321
# length of entry name (+1 for terminating byte)
322322
fbytes += struct.pack(dt, len(names[i]) + 1)
323323
fbytes += names[i].encode('ascii') + b'\x00'
324-
fbytes += bytes(rgba[i, :].astype(dt).tostring())
324+
fbytes += rgba[i, :].astype(dt).tobytes()
325325
with open(fpath, 'wb') as f:
326326
f.write(fbytes)
327327
with InTemporaryDirectory():

nibabel/gifti/gifti.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ def _data_tag_element(dataarray, encoding, dtype, ordering):
281281
# XXX Accommodating data_tag API - don't try to fix dtype
282282
if isinstance(dtype, str):
283283
dtype = dataarray.dtype
284-
out = np.asanyarray(dataarray, dtype).tostring(order)
284+
out = np.asanyarray(dataarray, dtype).tobytes(order)
285285
if enclabel == 'B64GZ':
286286
out = zlib.compress(out)
287287
da = base64.b64encode(out).decode()

nibabel/nicom/tests/test_dicomwrappers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,7 @@ def test_data_real(self):
618618
# data hash depends on the endianness
619619
if endian_codes[data.dtype.byteorder] == '>':
620620
data = data.byteswap()
621-
dat_str = data.tostring()
621+
dat_str = data.tobytes()
622622
assert_equal(sha1(dat_str).hexdigest(),
623623
'149323269b0af92baa7508e19ca315240f77fa8c')
624624

nibabel/nifti1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ def write_to(self, fileobj, byteswap):
376376
extinfo = np.array((rawsize, self._code), dtype=np.int32)
377377
if byteswap:
378378
extinfo = extinfo.byteswap()
379-
fileobj.write(extinfo.tostring())
379+
fileobj.write(extinfo.tobytes())
380380
# followed by the actual extension content
381381
# XXX if mangling upon load is implemented, it should be reverted here
382382
fileobj.write(self._mangle(self._content))

nibabel/spatialimages.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ def data_to_fileobj(self, data, fileobj, rescale=True):
266266
'''
267267
data = np.asarray(data)
268268
dtype = self.get_data_dtype()
269-
fileobj.write(data.astype(dtype).tostring(order=self.data_layout))
269+
fileobj.write(data.astype(dtype).tobytes(order=self.data_layout))
270270

271271
def data_from_fileobj(self, fileobj):
272272
''' Read binary image data from `fileobj` '''

nibabel/streamlines/tck.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ def save(self, fileobj):
205205
self._finalize_header(f, header, offset=beginning)
206206

207207
# Add the EOF_DELIMITER.
208-
f.write(asbytes(self.EOF_DELIMITER.tostring()))
208+
f.write(self.EOF_DELIMITER.tobytes())
209209
return
210210

211211
data_for_streamline = first_item.data_for_streamline
@@ -224,13 +224,13 @@ def save(self, fileobj):
224224

225225
for t in tractogram:
226226
data = np.r_[t.streamline, self.FIBER_DELIMITER]
227-
f.write(data.astype(dtype).tostring())
227+
f.write(data.astype(dtype).tobytes())
228228
nb_streamlines += 1
229229

230230
header[Field.NB_STREAMLINES] = nb_streamlines
231231

232232
# Add the EOF_DELIMITER.
233-
f.write(asbytes(self.EOF_DELIMITER.tostring()))
233+
f.write(asbytes(self.EOF_DELIMITER.tobytes()))
234234
self._finalize_header(f, header, offset=beginning)
235235

236236
@staticmethod

nibabel/streamlines/tests/test_tck.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -129,8 +129,8 @@ def test_load_file_with_wrong_information(self):
129129
assert_raises(HeaderError, TckFile.load, BytesIO(new_tck_file))
130130

131131
# Simulate a TCK file which is missing a streamline delimiter.
132-
eos = TckFile.FIBER_DELIMITER.tostring()
133-
eof = TckFile.EOF_DELIMITER.tostring()
132+
eos = TckFile.FIBER_DELIMITER.tobytes()
133+
eof = TckFile.EOF_DELIMITER.tobytes()
134134
new_tck_file = tck_file[:-(len(eos) + len(eof))] + tck_file[-len(eof):]
135135

136136
# Force TCK loading to use buffering.

nibabel/streamlines/trk.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -438,7 +438,7 @@ def save(self, fileobj):
438438
beginning = f.tell()
439439

440440
# Write temporary header that we will update at the end
441-
f.write(header.tostring())
441+
f.write(header.tobytes())
442442

443443
i4_dtype = np.dtype("<i4") # Always save in little-endian.
444444
f4_dtype = np.dtype("<f4") # Always save in little-endian.
@@ -467,7 +467,7 @@ def save(self, fileobj):
467467
header[Field.NB_PROPERTIES_PER_STREAMLINE] = 0
468468
# Overwrite header with updated one.
469469
f.seek(beginning, os.SEEK_SET)
470-
f.write(header.tostring())
470+
f.write(header.tobytes())
471471
return
472472

473473
# Update field 'property_name' using 'data_per_streamline'.
@@ -523,8 +523,8 @@ def save(self, fileobj):
523523
data = struct.pack(i4_dtype.str[:-1], len(points))
524524
pts_scalars = np.concatenate(
525525
[points, scalars], axis=1).astype(f4_dtype)
526-
data += pts_scalars.tostring()
527-
data += properties.tostring()
526+
data += pts_scalars.tobytes()
527+
data += properties.tobytes()
528528
f.write(data)
529529

530530
nb_streamlines += 1
@@ -552,7 +552,7 @@ def save(self, fileobj):
552552

553553
# Overwrite header with updated one.
554554
f.seek(beginning, os.SEEK_SET)
555-
f.write(header.tostring())
555+
f.write(header.tobytes())
556556

557557
@staticmethod
558558
def _read_header(fileobj):

nibabel/tests/test_arrayproxy.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def test_init():
6767
dtype = np.int32
6868
arr = np.arange(24, dtype=dtype).reshape(shape)
6969
bio.seek(16)
70-
bio.write(arr.tostring(order='F'))
70+
bio.write(arr.tobytes(order='F'))
7171
hdr = FunkyHeader(shape)
7272
ap = ArrayProxy(bio, hdr)
7373
assert_true(ap.file_like is bio)
@@ -84,7 +84,7 @@ def test_init():
8484
# C order also possible
8585
bio = BytesIO()
8686
bio.seek(16)
87-
bio.write(arr.tostring(order='C'))
87+
bio.write(arr.tobytes(order='C'))
8888
ap = CArrayProxy(bio, FunkyHeader((2, 3, 4)))
8989
assert_array_equal(np.asarray(ap), arr)
9090
# Illegal init
@@ -97,7 +97,7 @@ def test_tuplespec():
9797
dtype = np.int32
9898
arr = np.arange(24, dtype=dtype).reshape(shape)
9999
bio.seek(16)
100-
bio.write(arr.tostring(order='F'))
100+
bio.write(arr.tobytes(order='F'))
101101
# Create equivalent header and tuple specs
102102
hdr = FunkyHeader(shape)
103103
tuple_spec = (hdr.get_data_shape(), hdr.get_data_dtype(),
@@ -125,7 +125,7 @@ def write_raw_data(arr, hdr, fileobj):
125125
hdr.set_data_shape(arr.shape)
126126
hdr.set_data_dtype(arr.dtype)
127127
fileobj.write(b'\x00' * hdr.get_data_offset())
128-
fileobj.write(arr.tostring(order='F'))
128+
fileobj.write(arr.tobytes(order='F'))
129129

130130

131131
def test_nifti1_init():
@@ -163,15 +163,15 @@ def test_proxy_slicing():
163163
for order, klass in ('F', ArrayProxy), ('C', CArrayProxy):
164164
fobj = BytesIO()
165165
fobj.write(b'\0' * offset)
166-
fobj.write(arr.tostring(order=order))
166+
fobj.write(arr.tobytes(order=order))
167167
prox = klass(fobj, hdr)
168168
for sliceobj in slicer_samples(shape):
169169
assert_array_equal(arr[sliceobj], prox[sliceobj])
170170
# Check slicing works with scaling
171171
hdr.set_slope_inter(2.0, 1.0)
172172
fobj = BytesIO()
173173
fobj.write(b'\0' * offset)
174-
fobj.write(arr.tostring(order='F'))
174+
fobj.write(arr.tobytes(order='F'))
175175
prox = ArrayProxy(fobj, hdr)
176176
sliceobj = (None, slice(None), 1, -1)
177177
assert_array_equal(arr[sliceobj] * 2.0 + 1.0, prox[sliceobj])
@@ -199,7 +199,7 @@ def test_reshape_dataobj():
199199
bio = BytesIO()
200200
prox = ArrayProxy(bio, hdr)
201201
arr = np.arange(np.prod(shape), dtype=prox.dtype).reshape(shape)
202-
bio.write(b'\x00' * prox.offset + arr.tostring(order='F'))
202+
bio.write(b'\x00' * prox.offset + arr.tobytes(order='F'))
203203
assert_array_equal(prox, arr)
204204
assert_array_equal(reshape_dataobj(prox, (2, 3, 4)),
205205
np.reshape(arr, (2, 3, 4)))
@@ -245,7 +245,7 @@ def get_slope_inter(self):
245245
# Check standard read works
246246
arr = np.arange(24, dtype=np.int32).reshape(shape, order='F')
247247
bio.write(b'\x00' * hdr.get_data_offset())
248-
bio.write(arr.tostring(order='F'))
248+
bio.write(arr.tobytes(order='F'))
249249
prox = ArrayProxy(bio, hdr)
250250
assert_array_almost_equal(np.array(prox), arr * 2.1 + 3.14)
251251
# Check unscaled read works
@@ -294,7 +294,7 @@ def check_mmap(hdr, offset, proxy_class,
294294
with InTemporaryDirectory():
295295
with open(fname, 'wb') as fobj:
296296
fobj.write(b' ' * offset)
297-
fobj.write(arr.tostring(order='F'))
297+
fobj.write(arr.tobytes(order='F'))
298298
for mmap, expected_mode in (
299299
# mmap value, expected memmap mode
300300
# mmap=None -> no mmap value
@@ -405,10 +405,10 @@ def test_keep_file_open_true_false_invalid():
405405
# create the test data file
406406
if filetype == 'gz':
407407
with gzip.open(fname, 'wb') as fobj:
408-
fobj.write(data.tostring(order='F'))
408+
fobj.write(data.tobytes(order='F'))
409409
else:
410410
with open(fname, 'wb') as fobj:
411-
fobj.write(data.tostring(order='F'))
411+
fobj.write(data.tobytes(order='F'))
412412
# pass in a file name or open file handle. If the latter, we open
413413
# two file handles, because we're going to create two proxies
414414
# below.
@@ -459,7 +459,7 @@ def test_keep_file_open_true_false_invalid():
459459
with InTemporaryDirectory():
460460
fname = 'testdata'
461461
with open(fname, 'wb') as fobj:
462-
fobj.write(data.tostring(order='F'))
462+
fobj.write(data.tobytes(order='F'))
463463

464464
for invalid_kfo in (55, 'auto', 'cauto'):
465465
with assert_raises(ValueError):

0 commit comments

Comments
 (0)