Skip to content

Commit 263fca9

Browse files
committed
STY: Manual, blue-compatible touchups
[git-blame-ignore-rev]
1 parent 0ab2856 commit 263fca9

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

66 files changed

+961
-799
lines changed

nibabel/analyze.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -394,8 +394,8 @@ def from_header(klass, header=None, check=True):
394394
obj.set_data_dtype(orig_code)
395395
except HeaderDataError:
396396
raise HeaderDataError(
397-
f'Input header {header.__class__} has '
398-
f"datatype {header.get_value_label('datatype')} "
397+
f'Input header {header.__class__} has datatype '
398+
f'{header.get_value_label("datatype")} '
399399
f'but output header {klass} does not support it'
400400
)
401401
obj.set_data_dtype(header.get_data_dtype())
@@ -785,7 +785,7 @@ def set_slope_inter(self, slope, inter=None):
785785
"""
786786
if (slope in (None, 1) or np.isnan(slope)) and (inter in (None, 0) or np.isnan(inter)):
787787
return
788-
raise HeaderTypeError('Cannot set slope != 1 or intercept != 0 ' 'for Analyze headers')
788+
raise HeaderTypeError('Cannot set slope != 1 or intercept != 0 for Analyze headers')
789789

790790
@classmethod
791791
def _get_checks(klass):

nibabel/arraywriters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -432,7 +432,7 @@ def _range_scale(self, in_min, in_max):
432432
if self._out_dtype.kind == 'u':
433433
if in_min < 0 and in_max > 0:
434434
raise WriterError(
435-
'Cannot scale negative and positive ' 'numbers to uint without intercept'
435+
'Cannot scale negative and positive numbers to uint without intercept'
436436
)
437437
if in_max <= 0: # All input numbers <= 0
438438
self.slope = in_min / out_max

nibabel/brikhead.py

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,12 @@
5858
}
5959

6060
space_codes = Recoder(
61-
((0, 'unknown', ''), (1, 'scanner', 'ORIG'), (3, 'talairach', 'TLRC'), (4, 'mni', 'MNI')),
61+
(
62+
(0, 'unknown', ''),
63+
(1, 'scanner', 'ORIG'),
64+
(3, 'talairach', 'TLRC'),
65+
(4, 'mni', 'MNI'),
66+
),
6267
fields=('code', 'label', 'space'),
6368
)
6469

@@ -104,9 +109,7 @@ def _unpack_var(var):
104109
TEMPLATE_SPACE ORIG
105110
"""
106111

107-
err_msg = (
108-
'Please check HEAD file to ensure it is AFNI compliant. ' f'Offending attribute:\n{var}'
109-
)
112+
err_msg = f'Please check HEAD file to ensure it is AFNI compliant. Offending attribute:\n{var}'
110113
atype, aname = TYPE_RE.findall(var), NAME_RE.findall(var)
111114
if len(atype) != 1:
112115
raise AFNIHeaderError(f'Invalid attribute type entry in HEAD file. {err_msg}')
@@ -119,8 +122,7 @@ def _unpack_var(var):
119122
attr = [atype(f) for f in attr.split()]
120123
except ValueError:
121124
raise AFNIHeaderError(
122-
'Failed to read variable from HEAD file '
123-
f'due to improper type casting. {err_msg}'
125+
f'Failed to read variable from HEAD file due to improper type casting. {err_msg}'
124126
)
125127
else:
126128
# AFNI string attributes will always start with open single quote and
@@ -354,13 +356,7 @@ def _calc_zooms(self):
354356
origin", and second giving "Time step (TR)".
355357
"""
356358
xyz_step = tuple(np.abs(self.info['DELTA']))
357-
t_step = self.info.get(
358-
'TAXIS_FLOATS',
359-
(
360-
0,
361-
0,
362-
),
363-
)
359+
t_step = self.info.get('TAXIS_FLOATS', (0, 0))
364360
if len(t_step) > 0:
365361
t_step = (t_step[1],)
366362
return xyz_step + t_step

nibabel/casting.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -259,15 +259,15 @@ def type_info(np_type):
259259
if vals in (
260260
(112, 15, 16), # binary128
261261
(info_64.nmant, info_64.nexp, 8), # float64
262-
(63, 15, 12),
263-
(63, 15, 16),
264-
): # Intel extended 80
262+
(63, 15, 12), # Intel extended 80
263+
(63, 15, 16), # Intel extended 80
264+
):
265265
return ret # these are OK without modification
266266
# The remaining types are longdoubles with bad finfo values. Some we
267267
# correct, others we wait to hear of errors.
268268
# We start with float64 as basis
269269
ret = type_info(np.float64)
270-
if vals in ((52, 15, 12), (52, 15, 16)): # windows float96 # windows float128?
270+
if vals in ((52, 15, 12), (52, 15, 16)): # windows float96 / windows float128?
271271
# On windows 32 bit at least, float96 is Intel 80 storage but operating
272272
# at float64 precision. The finfo values give nexp == 15 (as for intel
273273
# 80) but in calculations nexp in fact appears to be 11 as for float64
@@ -298,7 +298,13 @@ def type_info(np_type):
298298
if np_type is np.longcomplex:
299299
max_val += 0j
300300
ret = dict(
301-
min=-max_val, max=max_val, nmant=112, nexp=15, minexp=-16382, maxexp=16384, width=width
301+
min=-max_val,
302+
max=max_val,
303+
nmant=112,
304+
nexp=15,
305+
minexp=-16382,
306+
maxexp=16384,
307+
width=width,
302308
)
303309
else: # don't recognize the type
304310
raise FloatingError(f'We had not expected long double type {np_type} with info {info}')

nibabel/cifti2/cifti2.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,15 @@ class Cifti2HeaderError(Exception):
7070

7171
CIFTI_MODEL_TYPES = (
7272
'CIFTI_MODEL_TYPE_SURFACE', # Modeled using surface vertices
73-
'CIFTI_MODEL_TYPE_VOXELS', # Modeled using voxels.
73+
'CIFTI_MODEL_TYPE_VOXELS', # Modeled using voxels.
7474
)
7575

76-
CIFTI_SERIESUNIT_TYPES = ('SECOND', 'HERTZ', 'METER', 'RADIAN')
76+
CIFTI_SERIESUNIT_TYPES = (
77+
'SECOND',
78+
'HERTZ',
79+
'METER',
80+
'RADIAN',
81+
)
7782

7883
CIFTI_BRAIN_STRUCTURES = (
7984
'CIFTI_STRUCTURE_ACCUMBENS_LEFT',
@@ -662,7 +667,7 @@ def __init__(self, name=None, voxel_indices_ijk=None, vertices=None):
662667
self.vertices = vertices if vertices is not None else []
663668
for val in self.vertices:
664669
if not isinstance(val, Cifti2Vertices):
665-
raise ValueError('Cifti2Parcel vertices must be instances of ' 'Cifti2Vertices')
670+
raise ValueError('Cifti2Parcel vertices must be instances of Cifti2Vertices')
666671

667672
@property
668673
def voxel_indices_ijk(self):
@@ -1237,7 +1242,7 @@ def _validate_new_mim(self, value):
12371242
a2md = self._get_indices_from_mim(value)
12381243
if not set(self.mapped_indices).isdisjoint(a2md):
12391244
raise Cifti2HeaderError(
1240-
'Indices in this Cifti2MatrixIndicesMap ' 'already mapped in this matrix'
1245+
'Indices in this Cifti2MatrixIndicesMap already mapped in this matrix'
12411246
)
12421247

12431248
def __setitem__(self, key, value):
@@ -1412,7 +1417,13 @@ class Cifti2Image(DataobjImage, SerializableImage):
14121417
rw = True
14131418

14141419
def __init__(
1415-
self, dataobj=None, header=None, nifti_header=None, extra=None, file_map=None, dtype=None
1420+
self,
1421+
dataobj=None,
1422+
header=None,
1423+
nifti_header=None,
1424+
extra=None,
1425+
file_map=None,
1426+
dtype=None,
14161427
):
14171428
"""Initialize image
14181429
@@ -1485,7 +1496,7 @@ def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None):
14851496
cifti_header = item.get_content()
14861497
break
14871498
else:
1488-
raise ValueError('NIfTI2 header does not contain a CIFTI-2 ' 'extension')
1499+
raise ValueError('NIfTI2 header does not contain a CIFTI-2 extension')
14891500

14901501
# Construct cifti image.
14911502
# Use array proxy object where possible

nibabel/cifti2/cifti2_axes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -665,7 +665,7 @@ def __add__(self, other):
665665
not np.allclose(other.affine, affine) or other.volume_shape != shape
666666
):
667667
raise ValueError(
668-
'Trying to concatenate two BrainModels defined ' 'in a different brain volume'
668+
'Trying to concatenate two BrainModels defined in a different brain volume'
669669
)
670670

671671
nvertices = dict(self.nvertices)
@@ -1008,7 +1008,7 @@ def __add__(self, other):
10081008
not np.allclose(other.affine, affine) or other.volume_shape != shape
10091009
):
10101010
raise ValueError(
1011-
'Trying to concatenate two ParcelsAxis defined ' 'in a different brain volume'
1011+
'Trying to concatenate two ParcelsAxis defined in a different brain volume'
10121012
)
10131013
nvertices = dict(self.nvertices)
10141014
for name, value in other.nvertices.items():

nibabel/cifti2/parse_cifti2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ def StartElementHandler(self, name, attrs):
335335
raise Cifti2HeaderError(
336336
'Volume element can only be a child of the CIFTI-2 MatrixIndicesMap element'
337337
)
338-
dimensions = tuple([int(val) for val in attrs['VolumeDimensions'].split(',')])
338+
dimensions = tuple(int(val) for val in attrs['VolumeDimensions'].split(','))
339339
volume = Cifti2Volume(volume_dimensions=dimensions)
340340
mim.append(volume)
341341
self.fsm_state.append('Volume')

nibabel/cifti2/tests/test_axes.py

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,9 @@ def test_brain_models():
128128
assert (bml[4].vertex == [2, 9, 14]).all()
129129

130130
for bm, label, is_surface in zip(
131-
bml, ['ThalamusRight', 'Other', 'cortex_left', 'Other'], (False, False, True, True)
131+
bml,
132+
['ThalamusRight', 'Other', 'cortex_left', 'Other'],
133+
(False, False, True, True),
132134
):
133135
assert np.all(bm.surface_mask == ~bm.volume_mask)
134136
structures = list(bm.iter_structures())
@@ -176,18 +178,27 @@ def test_brain_models():
176178

177179
# Test the constructor
178180
bm_vox = axes.BrainModelAxis(
179-
'thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)
181+
'thalamus_left',
182+
voxel=np.ones((5, 3), dtype=int),
183+
affine=np.eye(4),
184+
volume_shape=(2, 3, 4),
180185
)
181186
assert np.all(bm_vox.name == ['CIFTI_STRUCTURE_THALAMUS_LEFT'] * 5)
182187
assert np.array_equal(bm_vox.vertex, np.full(5, -1))
183188
assert np.array_equal(bm_vox.voxel, np.full((5, 3), 1))
184189
with pytest.raises(ValueError):
185190
# no volume shape
186-
axes.BrainModelAxis('thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4))
191+
axes.BrainModelAxis(
192+
'thalamus_left',
193+
voxel=np.ones((5, 3), dtype=int),
194+
affine=np.eye(4),
195+
)
187196
with pytest.raises(ValueError):
188197
# no affine
189198
axes.BrainModelAxis(
190-
'thalamus_left', voxel=np.ones((5, 3), dtype=int), volume_shape=(2, 3, 4)
199+
'thalamus_left',
200+
voxel=np.ones((5, 3), dtype=int),
201+
volume_shape=(2, 3, 4),
191202
)
192203
with pytest.raises(ValueError):
193204
# incorrect name
@@ -207,7 +218,11 @@ def test_brain_models():
207218
)
208219
with pytest.raises(ValueError):
209220
# no voxels or vertices
210-
axes.BrainModelAxis('thalamus_left', affine=np.eye(4), volume_shape=(2, 3, 4))
221+
axes.BrainModelAxis(
222+
'thalamus_left',
223+
affine=np.eye(4),
224+
volume_shape=(2, 3, 4),
225+
)
211226
with pytest.raises(ValueError):
212227
# incorrect voxel shape
213228
axes.BrainModelAxis(
@@ -218,7 +233,9 @@ def test_brain_models():
218233
)
219234

220235
bm_vertex = axes.BrainModelAxis(
221-
'cortex_left', vertex=np.ones(5, dtype=int), nvertices={'cortex_left': 20}
236+
'cortex_left',
237+
vertex=np.ones(5, dtype=int),
238+
nvertices={'cortex_left': 20},
222239
)
223240
assert np.array_equal(bm_vertex.name, ['CIFTI_STRUCTURE_CORTEX_LEFT'] * 5)
224241
assert np.array_equal(bm_vertex.vertex, np.full(5, 1))
@@ -227,11 +244,15 @@ def test_brain_models():
227244
axes.BrainModelAxis('cortex_left', vertex=np.ones(5, dtype=int))
228245
with pytest.raises(ValueError):
229246
axes.BrainModelAxis(
230-
'cortex_left', vertex=np.ones(5, dtype=int), nvertices={'cortex_right': 20}
247+
'cortex_left',
248+
vertex=np.ones(5, dtype=int),
249+
nvertices={'cortex_right': 20},
231250
)
232251
with pytest.raises(ValueError):
233252
axes.BrainModelAxis(
234-
'cortex_left', vertex=-np.ones(5, dtype=int), nvertices={'cortex_left': 20}
253+
'cortex_left',
254+
vertex=-np.ones(5, dtype=int),
255+
nvertices={'cortex_left': 20},
235256
)
236257

237258
# test from_mask errors
@@ -244,7 +265,10 @@ def test_brain_models():
244265

245266
# tests error in adding together or combining as ParcelsAxis
246267
bm_vox = axes.BrainModelAxis(
247-
'thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)
268+
'thalamus_left',
269+
voxel=np.ones((5, 3), dtype=int),
270+
affine=np.eye(4),
271+
volume_shape=(2, 3, 4),
248272
)
249273
bm_vox + bm_vox
250274
assert (bm_vertex + bm_vox)[: bm_vertex.size] == bm_vertex
@@ -289,7 +313,10 @@ def test_brain_models():
289313

290314
# test equalities
291315
bm_vox = axes.BrainModelAxis(
292-
'thalamus_left', voxel=np.ones((5, 3), dtype=int), affine=np.eye(4), volume_shape=(2, 3, 4)
316+
'thalamus_left',
317+
voxel=np.ones((5, 3), dtype=int),
318+
affine=np.eye(4),
319+
volume_shape=(2, 3, 4),
293320
)
294321
bm_other = deepcopy(bm_vox)
295322
assert bm_vox == bm_other

nibabel/cifti2/tests/test_cifti2.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -79,10 +79,7 @@ def test_cifti2_metadata():
7979

8080
with pytest.raises(KeyError):
8181
md.difference_update({'a': 'aval', 'd': 'dval'})
82-
assert (
83-
md.to_xml().decode('utf-8')
84-
== '<MetaData><MD><Name>b</Name><Value>bval</Value></MD></MetaData>'
85-
)
82+
assert md.to_xml() == b'<MetaData><MD><Name>b</Name><Value>bval</Value></MD></MetaData>'
8683

8784

8885
def test__float_01():
@@ -195,8 +192,7 @@ def test_cifti2_parcel():
195192

196193
assert len(pl.vertices) == 0
197194
assert (
198-
pl.to_xml().decode('utf-8')
199-
== '<Parcel Name="region"><VoxelIndicesIJK>1 2 3</VoxelIndicesIJK></Parcel>'
195+
pl.to_xml() == b'<Parcel Name="region"><VoxelIndicesIJK>1 2 3</VoxelIndicesIJK></Parcel>'
200196
)
201197

202198

@@ -207,7 +203,7 @@ def test_cifti2_vertices():
207203

208204
vs.brain_structure = 'CIFTI_STRUCTURE_OTHER'
209205

210-
assert vs.to_xml().decode('utf-8') == '<Vertices BrainStructure="CIFTI_STRUCTURE_OTHER" />'
206+
assert vs.to_xml() == b'<Vertices BrainStructure="CIFTI_STRUCTURE_OTHER" />'
211207

212208
assert len(vs) == 0
213209
vs.extend(np.array([0, 1, 2]))
@@ -217,10 +213,7 @@ def test_cifti2_vertices():
217213
with pytest.raises(ValueError):
218214
vs.insert(1, 'a')
219215

220-
assert (
221-
vs.to_xml().decode('utf-8')
222-
== '<Vertices BrainStructure="CIFTI_STRUCTURE_OTHER">0 1 2</Vertices>'
223-
)
216+
assert vs.to_xml() == b'<Vertices BrainStructure="CIFTI_STRUCTURE_OTHER">0 1 2</Vertices>'
224217

225218
vs[0] = 10
226219
assert vs[0] == 10
@@ -254,7 +247,7 @@ def test_cifti2_vertexindices():
254247
vi.to_xml()
255248
vi.extend(np.array([0, 1, 2]))
256249
assert len(vi) == 3
257-
assert vi.to_xml().decode('utf-8') == '<VertexIndices>0 1 2</VertexIndices>'
250+
assert vi.to_xml() == b'<VertexIndices>0 1 2</VertexIndices>'
258251

259252
with pytest.raises(ValueError):
260253
vi[0] = 'a'

nibabel/cifti2/tests/test_cifti2io_header.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from os.path import dirname
1212
from os.path import join as pjoin
1313

14+
import numpy as np
1415
import pytest
1516
from numpy.testing import assert_array_almost_equal
1617
from packaging.version import Version
@@ -249,12 +250,17 @@ def test_read_geometry():
249250
assert from_file.voxel_indices_ijk[-1] == expected[3]
250251
assert current_index == img.shape[1]
251252

252-
expected_affine = [[-2, 0, 0, 90], [0, 2, 0, -126], [0, 0, 2, -72], [0, 0, 0, 1]]
253+
expected_affine = [
254+
[-2, 0, 0, 90],
255+
[0, 2, 0, -126],
256+
[0, 0, 2, -72],
257+
[0, 0, 0, 1],
258+
]
253259
expected_dimensions = (91, 109, 91)
254-
assert (
255-
geometry_mapping.volume.transformation_matrix_voxel_indices_ijk_to_xyz.matrix
256-
== expected_affine
257-
).all()
260+
assert np.array_equal(
261+
geometry_mapping.volume.transformation_matrix_voxel_indices_ijk_to_xyz.matrix,
262+
expected_affine,
263+
)
258264
assert geometry_mapping.volume.volume_dimensions == expected_dimensions
259265

260266

0 commit comments

Comments
 (0)