Skip to content
Draft
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
6 changes: 1 addition & 5 deletions nibabel/_typing.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
"""Helpers for typing compatibility across Python versions"""

import sys

if sys.version_info < (3, 10):
from typing_extensions import ParamSpec
else:
from typing import ParamSpec
from typing import ParamSpec

if sys.version_info < (3, 11):
from typing_extensions import Self
Expand Down
13 changes: 8 additions & 5 deletions nibabel/cifti2/cifti2_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -910,7 +910,7 @@ def to_mapping(self, dim):
mim.volume = cifti2.Cifti2Volume(self.volume_shape, affine)
for name, nvertex in self.nvertices.items():
mim.append(cifti2.Cifti2Surface(name, nvertex))
for name, voxels, vertices in zip(self.name, self.voxels, self.vertices):
for name, voxels, vertices in zip(self.name, self.voxels, self.vertices, strict=False):
cifti_voxels = cifti2.Cifti2VoxelIndicesIJK(voxels)
element = cifti2.Cifti2Parcel(name, cifti_voxels)
for name_vertex, idx_vertices in vertices.items():
Expand Down Expand Up @@ -963,7 +963,10 @@ def __eq__(self, other):
or len(self) != len(other)
or not np.array_equal(self.name, other.name)
or self.nvertices != other.nvertices
or any(not np.array_equal(vox1, vox2) for vox1, vox2 in zip(self.voxels, other.voxels))
or any(
not np.array_equal(vox1, vox2)
for vox1, vox2 in zip(self.voxels, other.voxels, strict=False)
)
):
return False
if self.affine is not None:
Expand All @@ -975,7 +978,7 @@ def __eq__(self, other):
return False
elif other.affine is not None:
return False
for vert1, vert2 in zip(self.vertices, other.vertices):
for vert1, vert2 in zip(self.vertices, other.vertices, strict=False):
if len(vert1) != len(vert2):
return False
for name in vert1.keys():
Expand Down Expand Up @@ -1130,7 +1133,7 @@ def to_mapping(self, dim):
:class:`.cifti2.Cifti2MatrixIndicesMap`
"""
mim = cifti2.Cifti2MatrixIndicesMap([dim], 'CIFTI_INDEX_TYPE_SCALARS')
for name, meta in zip(self.name, self.meta):
for name, meta in zip(self.name, self.meta, strict=False):
named_map = cifti2.Cifti2NamedMap(name, cifti2.Cifti2MetaData(meta))
mim.append(named_map)
return mim
Expand Down Expand Up @@ -1268,7 +1271,7 @@ def to_mapping(self, dim):
:class:`.cifti2.Cifti2MatrixIndicesMap`
"""
mim = cifti2.Cifti2MatrixIndicesMap([dim], 'CIFTI_INDEX_TYPE_LABELS')
for name, label, meta in zip(self.name, self.label, self.meta):
for name, label, meta in zip(self.name, self.label, self.meta, strict=False):
label_table = cifti2.Cifti2LabelTable()
for key, value in label.items():
label_table[key] = (value[0],) + tuple(value[1])
Expand Down
5 changes: 3 additions & 2 deletions nibabel/cifti2/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ def test_brain_models():
bml,
['ThalamusRight', 'Other', 'cortex_left', 'Other'],
(False, False, True, True),
strict=False,
):
assert np.all(bm.surface_mask == ~bm.volume_mask)
structures = list(bm.iter_structures())
Expand All @@ -148,7 +149,7 @@ def test_brain_models():
assert len(bmt) == 10
structures = list(bmt.iter_structures())
assert len(structures) == 3
for bm, (name, _, bm_split) in zip(bml[:3], structures):
for bm, (name, _, bm_split) in zip(bml[:3], structures, strict=False):
assert bm == bm_split
assert (bm_split.name == name).all()
assert bm == bmt[bmt.name == bm.name[0]]
Expand Down Expand Up @@ -725,7 +726,7 @@ def test_common_interface():
"""
Tests the common interface for all custom created CIFTI-2 axes
"""
for axis1, axis2 in zip(get_axes(), get_axes()):
for axis1, axis2 in zip(get_axes(), get_axes(), strict=False):
assert axis1 == axis2
concatenated = axis1 + axis2
assert axis1 != concatenated
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cifti2/tests/test_cifti2io_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def check_hcp_grayordinates(brain_model):
assert len(structures) == len(hcp_labels)
idx_start = 0
for idx, (name, _, bm), label, nel in zip(
range(len(structures)), structures, hcp_labels, hcp_n_elements
range(len(structures)), structures, hcp_labels, hcp_n_elements, strict=False
):
if idx < 2:
assert name in bm.nvertices.keys()
Expand Down
20 changes: 11 additions & 9 deletions nibabel/cifti2/tests/test_cifti2io_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,11 @@ def test_readwritedata():
img2 = ci.load('test.nii')
assert len(img.header.matrix) == len(img2.header.matrix)
# Order should be preserved in load/save
for mim1, mim2 in zip(img.header.matrix, img2.header.matrix):
for mim1, mim2 in zip(img.header.matrix, img2.header.matrix, strict=False):
named_maps1 = [m_ for m_ in mim1 if isinstance(m_, ci.Cifti2NamedMap)]
named_maps2 = [m_ for m_ in mim2 if isinstance(m_, ci.Cifti2NamedMap)]
assert len(named_maps1) == len(named_maps2)
for map1, map2 in zip(named_maps1, named_maps2):
for map1, map2 in zip(named_maps1, named_maps2, strict=False):
assert map1.map_name == map2.map_name
if map1.label_table is None:
assert map2.label_table is None
Expand All @@ -109,11 +109,11 @@ def test_nibabel_readwritedata():
img2 = nib.load('test.nii')
assert len(img.header.matrix) == len(img2.header.matrix)
# Order should be preserved in load/save
for mim1, mim2 in zip(img.header.matrix, img2.header.matrix):
for mim1, mim2 in zip(img.header.matrix, img2.header.matrix, strict=False):
named_maps1 = [m_ for m_ in mim1 if isinstance(m_, ci.Cifti2NamedMap)]
named_maps2 = [m_ for m_ in mim2 if isinstance(m_, ci.Cifti2NamedMap)]
assert len(named_maps1) == len(named_maps2)
for map1, map2 in zip(named_maps1, named_maps2):
for map1, map2 in zip(named_maps1, named_maps2, strict=False):
assert map1.map_name == map2.map_name
if map1.label_table is None:
assert map2.label_table is None
Expand Down Expand Up @@ -228,7 +228,7 @@ def test_read_geometry():
('CIFTI_STRUCTURE_THALAMUS_RIGHT', 1248, [32, 47, 34], [38, 55, 46]),
]
current_index = 0
for from_file, expected in zip(geometry_mapping.brain_models, expected_geometry):
for from_file, expected in zip(geometry_mapping.brain_models, expected_geometry, strict=False):
assert from_file.model_type in ('CIFTI_MODEL_TYPE_SURFACE', 'CIFTI_MODEL_TYPE_VOXELS')
assert from_file.brain_structure == expected[0]
assert from_file.index_offset == current_index
Expand Down Expand Up @@ -328,11 +328,13 @@ def test_read_parcels():
assert img.shape[1] == len(expected_parcels)
assert len(list(parcel_mapping.parcels)) == len(expected_parcels)

for (name, expected_surfaces), parcel in zip(expected_parcels, parcel_mapping.parcels):
for (name, expected_surfaces), parcel in zip(
expected_parcels, parcel_mapping.parcels, strict=False
):
assert parcel.name == name
assert len(parcel.vertices) == 2
for vertices, orientation, (length, first_element, last_element) in zip(
parcel.vertices, ('LEFT', 'RIGHT'), expected_surfaces
parcel.vertices, ('LEFT', 'RIGHT'), expected_surfaces, strict=False
):
assert len(vertices) == length
assert vertices[0] == first_element
Expand All @@ -350,7 +352,7 @@ def test_read_scalar():
assert len(list(scalar_mapping.named_maps)) == len(expected_names)

expected_meta = [('PaletteColorMapping', '<PaletteColorMapping Version="1">\n <ScaleMo')]
for scalar, name in zip(scalar_mapping.named_maps, expected_names):
for scalar, name in zip(scalar_mapping.named_maps, expected_names, strict=False):
assert scalar.map_name == name

assert len(scalar.metadata) == len(expected_meta)
Expand Down Expand Up @@ -402,7 +404,7 @@ def test_read_labels():
95: ('13b_OFP03', (1.0, 1.0, 0.0, 1.0)),
}

for named_map, name in zip(label_mapping.named_maps, expected_names):
for named_map, name in zip(label_mapping.named_maps, expected_names, strict=False):
assert named_map.map_name == name
assert len(named_map.metadata) == 0
assert len(named_map.label_table) == 96
Expand Down
8 changes: 4 additions & 4 deletions nibabel/cifti2/tests/test_new_cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def create_parcel_map(applies_to_matrix_dimension):
def check_parcel_map(mapping):
assert mapping.indices_map_to_data_type == 'CIFTI_INDEX_TYPE_PARCELS'
assert len(list(mapping.parcels)) == len(parcels)
for (name, elements), parcel in zip(parcels, mapping.parcels):
for (name, elements), parcel in zip(parcels, mapping.parcels, strict=False):
assert parcel.name == name
idx_surface = 0
for element in elements:
Expand All @@ -192,7 +192,7 @@ def check_parcel_map(mapping):
else:
assert parcel.voxel_indices_ijk._indices == element

for surface, orientation in zip(mapping.surfaces, ('LEFT', 'RIGHT')):
for surface, orientation in zip(mapping.surfaces, ('LEFT', 'RIGHT'), strict=False):
assert surface.brain_structure == f'CIFTI_STRUCTURE_CORTEX_{orientation}'
assert surface.surface_number_of_vertices == number_of_vertices

Expand All @@ -214,7 +214,7 @@ def check_scalar_map(mapping):
assert mapping.indices_map_to_data_type == 'CIFTI_INDEX_TYPE_SCALARS'
assert len(list(mapping.named_maps)) == 2

for expected, named_map in zip(scalars, mapping.named_maps):
for expected, named_map in zip(scalars, mapping.named_maps, strict=False):
assert named_map.map_name == expected[0]
if len(expected[1]) == 0:
assert named_map.metadata is None
Expand Down Expand Up @@ -258,7 +258,7 @@ def check_label_map(mapping):
assert mapping.indices_map_to_data_type == 'CIFTI_INDEX_TYPE_LABELS'
assert len(list(mapping.named_maps)) == 2

for expected, named_map in zip(scalars, mapping.named_maps):
for expected, named_map in zip(scalars, mapping.named_maps, strict=False):
assert named_map.map_name == expected[0]
if len(expected[1]) == 0:
assert named_map.metadata is None
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/ls.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def proc_file(f, opts):
counts = _err(f'{len(items)} uniques. Use --all-counts')
else:
freq = np.bincount(inv)
counts = ' '.join(f'{i:g}:{f}' for i, f in zip(items, freq))
counts = ' '.join(f'{i:g}:{f}' for i, f in zip(items, freq, strict=False))
row += ['@l' + counts]
except OSError as e:
verbose(2, f'Failed to obtain stats/counts -- {e}')
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/parrec2nii.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def proc_file(infile, opts):
with open(basefilename + '.ordering.csv', 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile, delimiter=',')
csvwriter.writerow(vol_keys)
for vals in zip(*[labels[k] for k in vol_keys]):
for vals in zip(*[labels[k] for k in vol_keys], strict=False):
csvwriter.writerow(vals)

# write out dwell time if requested
Expand Down
6 changes: 4 additions & 2 deletions nibabel/cmdline/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,14 @@ def table2string(table, out=None):

# eat whole entry while computing width for @w (for wide)
markup_strip = re.compile(r'^@([lrc]|w.*)')
col_width = [max(len(markup_strip.sub('', x)) for x in column) for column in zip(*table)]
col_width = [
max(len(markup_strip.sub('', x)) for x in column) for column in zip(*table, strict=False)
]
trans = str.maketrans('lrcw', '<>^^')
lines = []
for row in table:
line = []
for item, width in zip(row, col_width):
for item, width in zip(row, col_width, strict=False):
item = str(item)
if item.startswith('@'):
align = item[1]
Expand Down
8 changes: 4 additions & 4 deletions nibabel/dft.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def __getattribute__(self, name):
c.execute('SELECT * FROM series WHERE study = ?', (self.uid,))
cols = [el[0] for el in c.description]
for row in c:
d = dict(zip(cols, row))
d = dict(zip(cols, row, strict=False))
val.append(_Series(d))
self.series = val
return val
Expand Down Expand Up @@ -110,7 +110,7 @@ def __getattribute__(self, name):
c.execute(query, (self.uid,))
cols = [el[0] for el in c.description]
for row in c:
d = dict(zip(cols, row))
d = dict(zip(cols, row, strict=False))
val.append(_StorageInstance(d))
self.storage_instances = val
return val
Expand Down Expand Up @@ -289,7 +289,7 @@ def get_studies(base_dir=None, followlinks=False):
studies = []
cols = [el[0] for el in c.description]
for row in c:
d = dict(zip(cols, row))
d = dict(zip(cols, row, strict=False))
studies.append(_Study(d))
return studies
query = """SELECT study
Expand All @@ -309,7 +309,7 @@ def get_studies(base_dir=None, followlinks=False):
for uid in study_uids:
c.execute('SELECT * FROM study WHERE uid = ?', (uid,))
cols = [el[0] for el in c.description]
d = dict(zip(cols, c.fetchone()))
d = dict(zip(cols, c.fetchone(), strict=False))
studies.append(_Study(d))
return studies

Expand Down
2 changes: 1 addition & 1 deletion nibabel/freesurfer/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ def write_string(s):
# num_entries
write(ctab.shape[0])

for ind, (clu, name) in enumerate(zip(ctab, names)):
for ind, (clu, name) in enumerate(zip(ctab, names, strict=False)):
write(ind)
write_string(name)
for val in clu[:-1]:
Expand Down
2 changes: 1 addition & 1 deletion nibabel/gifti/tests/test_gifti.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ def test_metadata_list_interface():

def test_gifti_label_rgba():
rgba = rng.random(4)
kwargs = dict(zip(['red', 'green', 'blue', 'alpha'], rgba))
kwargs = dict(zip(['red', 'green', 'blue', 'alpha'], rgba, strict=False))

gl1 = GiftiLabel(**kwargs)
assert_array_equal(rgba, gl1.rgba)
Expand Down
2 changes: 1 addition & 1 deletion nibabel/nicom/dicomwrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ def __init__(self, dcm_data, frame_filters=None):
frame_slc_pos = [np.inner(ipp, self.slice_normal) for ipp in frame_ipps]
rnd_slc_pos = np.round(frame_slc_pos, 4)
uniq_slc_pos = np.unique(rnd_slc_pos)
pos_ord_map = dict(zip(uniq_slc_pos, np.argsort(uniq_slc_pos)))
pos_ord_map = dict(zip(uniq_slc_pos, np.argsort(uniq_slc_pos), strict=False))
self._frame_slc_ord = [pos_ord_map[pos] for pos in rnd_slc_pos]
if len(self._frame_slc_ord) > 1:
self._slice_spacing = (
Expand Down
4 changes: 2 additions & 2 deletions nibabel/nicom/tests/test_dicomwrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ def fake_frames(seq_name, field_name, value_seq, frame_seq=None):
"""
if frame_seq is None:
frame_seq = [pydicom.Dataset() for _ in range(len(value_seq))]
for value, fake_frame in zip(value_seq, frame_seq):
for value, fake_frame in zip(value_seq, frame_seq, strict=False):
if value is None:
continue
if hasattr(fake_frame, seq_name):
Expand Down Expand Up @@ -496,7 +496,7 @@ def __init__(self, div, sid, ipp, iop):
# create the PerFrameFunctionalGroupsSequence
frames = [
PerFrmFuncGrpSeqElem(div, sid, ipp, iop)
for div, sid, ipp, iop in zip(div_seq, sid_seq, ipp_seq, iop_seq)
for div, sid, ipp, iop in zip(div_seq, sid_seq, ipp_seq, iop_seq, strict=False)
]
return {
'NumberOfFrames': num_of_frames,
Expand Down
2 changes: 1 addition & 1 deletion nibabel/openers.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def __init__(self, fileish: str | io.IOBase, *args, **kwargs):
return
opener, arg_names = self._get_opener_argnames(fileish)
# Get full arguments to check for optional parameters
full_kwargs = {**kwargs, **dict(zip(arg_names, args))}
full_kwargs = {**kwargs, **dict(zip(arg_names, args, strict=False))}
# Set default mode
if 'mode' not in full_kwargs:
mode = 'rb'
Expand Down
4 changes: 2 additions & 2 deletions nibabel/orientations.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ def ornt2axcodes(ornt, labels=None):
('F', 'L', 'U')
"""
if labels is None:
labels = list(zip('LPI', 'RAS'))
labels = list(zip('LPI', 'RAS', strict=False))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
labels = list(zip('LPI', 'RAS', strict=False))
labels = list(zip('LPI', 'RAS', strict=True))

axcodes = []
for axno, direction in np.asarray(ornt):
if np.isnan(axno):
Expand Down Expand Up @@ -324,7 +324,7 @@ def axcodes2ornt(axcodes, labels=None):
[ 0., -1.],
[ 2., 1.]])
"""
labels = list(zip('LPI', 'RAS')) if labels is None else labels
labels = list(zip('LPI', 'RAS', strict=False)) if labels is None else labels
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
labels = list(zip('LPI', 'RAS', strict=False)) if labels is None else labels
labels = list(zip('LPI', 'RAS', strict=True)) if labels is None else labels

allowed_labels = sum(map(list, labels), [None])
if len(allowed_labels) != len(set(allowed_labels)):
raise ValueError(f'Duplicate labels in {allowed_labels}')
Expand Down
2 changes: 1 addition & 1 deletion nibabel/spaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def vox2out_vox(mapped_voxels, voxel_sizes=None):
if not np.all(np.array(voxel_sizes) > 0):
raise ValueError('voxel sizes should all be positive')
out_vox[:n_axes] = voxel_sizes
in_mn_mx = zip([0, 0, 0], np.array(in_shape) - 1)
in_mn_mx = zip([0, 0, 0], np.array(in_shape) - 1, strict=False)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
in_mn_mx = zip([0, 0, 0], np.array(in_shape) - 1, strict=False)
in_mn_mx = zip([0, 0, 0], np.array(in_shape) - 1, strict=True)

in_corners = list(product(*in_mn_mx))
out_corners = apply_affine(in_affine, in_corners)
out_mn = out_corners.min(axis=0)
Expand Down
Loading