Skip to content

MNT: Apply refurb suggestions #1153

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Dec 13, 2022
3 changes: 1 addition & 2 deletions nibabel/cifti2/tests/test_cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,7 @@ def test_matrixindicesmap():
parcel = ci.Cifti2Parcel()

assert mim.volume is None
mim.append(volume)
mim.append(parcel)
mim.extend((volume, parcel))


assert mim.volume == volume
Expand Down
33 changes: 11 additions & 22 deletions nibabel/cifti2/tests/test_new_cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,7 @@ def test_dtseries():
series_map = create_series_map((0, ))
geometry_map = create_geometry_map((1, ))
matrix = ci.Cifti2Matrix()
matrix.append(series_map)
matrix.append(geometry_map)
matrix.extend((series_map, geometry_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(13, 10)
img = ci.Cifti2Image(data, hdr)
Expand All @@ -254,8 +253,7 @@ def test_dscalar():
scalar_map = create_scalar_map((0, ))
geometry_map = create_geometry_map((1, ))
matrix = ci.Cifti2Matrix()
matrix.append(scalar_map)
matrix.append(geometry_map)
matrix.extend((scalar_map, geometry_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(2, 10)
img = ci.Cifti2Image(data, hdr)
Expand All @@ -276,8 +274,7 @@ def test_dlabel():
label_map = create_label_map((0, ))
geometry_map = create_geometry_map((1, ))
matrix = ci.Cifti2Matrix()
matrix.append(label_map)
matrix.append(geometry_map)
matrix.extend((label_map, geometry_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(2, 10)
img = ci.Cifti2Image(data, hdr)
Expand Down Expand Up @@ -318,8 +315,7 @@ def test_ptseries():
series_map = create_series_map((0, ))
parcel_map = create_parcel_map((1, ))
matrix = ci.Cifti2Matrix()
matrix.append(series_map)
matrix.append(parcel_map)
matrix.extend((series_map, parcel_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(13, 4)
img = ci.Cifti2Image(data, hdr)
Expand All @@ -340,8 +336,7 @@ def test_pscalar():
scalar_map = create_scalar_map((0, ))
parcel_map = create_parcel_map((1, ))
matrix = ci.Cifti2Matrix()
matrix.append(scalar_map)
matrix.append(parcel_map)
matrix.extend((scalar_map, parcel_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(2, 4)
img = ci.Cifti2Image(data, hdr)
Expand All @@ -362,8 +357,7 @@ def test_pdconn():
geometry_map = create_geometry_map((0, ))
parcel_map = create_parcel_map((1, ))
matrix = ci.Cifti2Matrix()
matrix.append(geometry_map)
matrix.append(parcel_map)
matrix.extend((geometry_map, parcel_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(10, 4)
img = ci.Cifti2Image(data, hdr)
Expand All @@ -384,8 +378,7 @@ def test_dpconn():
parcel_map = create_parcel_map((0, ))
geometry_map = create_geometry_map((1, ))
matrix = ci.Cifti2Matrix()
matrix.append(parcel_map)
matrix.append(geometry_map)
matrix.extend((parcel_map, geometry_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(4, 10)
img = ci.Cifti2Image(data, hdr)
Expand All @@ -406,8 +399,7 @@ def test_plabel():
label_map = create_label_map((0, ))
parcel_map = create_parcel_map((1, ))
matrix = ci.Cifti2Matrix()
matrix.append(label_map)
matrix.append(parcel_map)
matrix.extend((label_map, parcel_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(2, 4)
img = ci.Cifti2Image(data, hdr)
Expand Down Expand Up @@ -448,8 +440,7 @@ def test_pconnseries():
series_map = create_series_map((2, ))

matrix = ci.Cifti2Matrix()
matrix.append(parcel_map)
matrix.append(series_map)
matrix.extend((parcel_map, series_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(4, 4, 13)
img = ci.Cifti2Image(data, hdr)
Expand All @@ -473,8 +464,7 @@ def test_pconnscalar():
scalar_map = create_scalar_map((2, ))

matrix = ci.Cifti2Matrix()
matrix.append(parcel_map)
matrix.append(scalar_map)
matrix.extend((parcel_map, scalar_map))
hdr = ci.Cifti2Header(matrix)
data = np.random.randn(4, 4, 2)
img = ci.Cifti2Image(data, hdr)
Expand All @@ -499,8 +489,7 @@ def test_wrong_shape():
brain_model_map = create_geometry_map((1, ))

matrix = ci.Cifti2Matrix()
matrix.append(scalar_map)
matrix.append(brain_model_map)
matrix.extend((scalar_map, brain_model_map))
hdr = ci.Cifti2Header(matrix)

# correct shape is (2, 10)
Expand Down
6 changes: 1 addition & 5 deletions nibabel/cmdline/dicomfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ def __init__(self, fno):
self.fno = fno
self.keep_cache = False
self.direct_io = False
return

def __str__(self):
return 'FileHandle(%d)' % self.fno
Expand All @@ -64,7 +63,6 @@ def __init__(self, *args, **kwargs):
self.dicom_path = kwargs.pop('dicom_path', None)
fuse.Fuse.__init__(self, *args, **kwargs)
self.fhs = {}
return

def get_paths(self):
paths = {}
Expand Down Expand Up @@ -119,8 +117,7 @@ def readdir(self, path, fh):
return -errno.ENOENT
logger.debug(f'matched {matched_path}')
fnames = [k.encode('ascii', 'replace') for k in matched_path.keys()]
fnames.append('.')
fnames.append('..')
fnames.extend(('.', '..'))
return [fuse.Direntry(f) for f in fnames]

def getattr(self, path):
Expand Down Expand Up @@ -190,7 +187,6 @@ def release(self, path, flags, fh):
logger.debug(path)
logger.debug(fh)
del self.fhs[fh.fno]
return


def get_opt_parser():
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def verbose(thing, msg):
"""Print `s` if `thing` is less than the `verbose_level`
"""
# TODO: consider using nibabel's logger
if thing <= int(verbose_level):
if thing <= verbose_level:
print(' ' * thing + msg)


Expand Down
4 changes: 2 additions & 2 deletions nibabel/deprecator.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ def __call__(self, message, since='', until='',
deprecator : func
Function returning a decorator.
"""
warn_class = warn_class if warn_class else self.warn_class
error_class = error_class if error_class else self.error_class
warn_class = warn_class or self.warn_class
error_class = error_class or self.error_class
messages = [message]
if (since, until) != ('', ''):
messages.append('')
Expand Down
9 changes: 0 additions & 9 deletions nibabel/dft.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ def __init__(self, series, i, si):
self.series = series
self.i = i
self.si = si
return

def __str__(self):
fmt = 'expecting instance number %d, got %d'
Expand All @@ -70,7 +69,6 @@ def __init__(self, d):
self.patient_birth_date = d['patient_birth_date']
self.patient_sex = d['patient_sex']
self.series = None
return

def __getattribute__(self, name):
val = object.__getattribute__(self, name)
Expand Down Expand Up @@ -103,7 +101,6 @@ def __init__(self, d):
self.bits_allocated = d['bits_allocated']
self.bits_stored = d['bits_stored']
self.storage_instances = None
return

def __getattribute__(self, name):
val = object.__getattribute__(self, name)
Expand Down Expand Up @@ -226,7 +223,6 @@ def __init__(self, d):
self.instance_number = d['instance_number']
self.series = d['series']
self.files = None
return

def __getattribute__(self, name):
val = object.__getattribute__(self, name)
Expand Down Expand Up @@ -256,7 +252,6 @@ def __exit__(self, type, value, traceback):
if type is None:
self.c.close()
DB.rollback()
return


class _db_change:
Expand All @@ -272,7 +267,6 @@ def __exit__(self, type, value, traceback):
DB.commit()
else:
DB.rollback()
return


def _get_subdirs(base_dir, files_dict=None, followlinks=False):
Expand Down Expand Up @@ -316,7 +310,6 @@ def update_cache(base_dir, followlinks=False):
else:
query = "INSERT INTO directory (path, mtime) VALUES (?, ?)"
c.execute(query, (dir, mtimes[dir]))
return


def get_studies(base_dir=None, followlinks=False):
Expand Down Expand Up @@ -382,7 +375,6 @@ def _update_dir(c, dir, files, studies, series, storage_instances):
SET mtime = ?, storage_instance = ?
WHERE directory = ? AND name = ?"""
c.execute(query, (mtime, si_uid, dir, fname))
return


def _update_file(c, path, fname, studies, series, storage_instances):
Expand Down Expand Up @@ -457,7 +449,6 @@ def clear_cache():
c.execute("DELETE FROM storage_instance")
c.execute("DELETE FROM series")
c.execute("DELETE FROM study")
return


CREATE_QUERIES = (
Expand Down
2 changes: 1 addition & 1 deletion nibabel/nicom/dicomwrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,7 +737,7 @@ def series_signature(self):
ice = csar.get_ice_dims(self.csa_header)
if ice is not None:
ice = ice[:6] + ice[8:9]
signature['ICE_Dims'] = (ice, lambda x, y: x == y)
signature['ICE_Dims'] = (ice, operator.eq)
return signature

@one_time
Expand Down
2 changes: 1 addition & 1 deletion nibabel/streamlines/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def save(tractogram, filename, **kwargs):
" 'TractogramFile' object.")
warnings.warn(msg, ExtensionWarning)

if len(kwargs) > 0:
if kwargs:
msg = ("A 'TractogramFile' object was provided, no need for"
" keyword arguments.")
raise ValueError(msg)
Expand Down
13 changes: 7 additions & 6 deletions nibabel/streamlines/tck.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,12 +249,13 @@ def _write_header(fileobj, header):
Field.VOXEL_TO_RASMM, # Streamlines are always in RAS+ mm.
"count", "datatype", "file"] # Fields being replaced.

lines = []
lines.append(f"count: {header[Field.NB_STREAMLINES]:010}")
lines.append("datatype: Float32LE") # Always Float32LE.
lines.extend([f"{k}: {v}"
for k, v in header.items()
if k not in exclude and not k.startswith("_")])
lines = [
f"count: {header[Field.NB_STREAMLINES]:010}",
"datatype: Float32LE", # Always Float32LE.
]
lines.extend(f"{k}: {v}"
for k, v in header.items()
if k not in exclude and not k.startswith("_"))
out = "\n".join(lines)

# Check the header is well formatted.
Expand Down
16 changes: 7 additions & 9 deletions nibabel/tests/data/gen_standard.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,17 @@ def _gen_straight_streamline(start, end, steps=3):
return np.array(coords).T

# Generate a 3D 'X' template fitting inside the voxel centered at (0,0,0).
X = []
X.append(_gen_straight_streamline((-0.5, -0.5, -0.5), (0.5, 0.5, 0.5)))
X.append(_gen_straight_streamline((-0.5, 0.5, -0.5), (0.5, -0.5, 0.5)))
X.append(_gen_straight_streamline((-0.5, 0.5, 0.5), (0.5, -0.5, -0.5)))
X.append(_gen_straight_streamline((-0.5, -0.5, 0.5), (0.5, 0.5, -0.5)))
X = [
_gen_straight_streamline((-0.5, -0.5, -0.5), (0.5, 0.5, 0.5)),
_gen_straight_streamline((-0.5, 0.5, -0.5), (0.5, -0.5, 0.5)),
_gen_straight_streamline((-0.5, 0.5, 0.5), (0.5, -0.5, -0.5)),
_gen_straight_streamline((-0.5, -0.5, 0.5), (0.5, 0.5, -0.5)),
]

# Get the coordinates of voxels 'on' in the mask.
coords = np.array(zip(*np.where(mask)))

streamlines = []
for c in coords:
for line in X:
streamlines.append((line + c) * voxel_size)
streamlines = [(line + c) * voxel_size for c in coords for line in X]

return streamlines

Expand Down
4 changes: 1 addition & 3 deletions nibabel/tests/test_volumeutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -947,9 +947,7 @@ def test_seek_tell():
# zeros in their wake. BZ2Files can't seek when writing,
# unless we enable the write0 flag to seek_tell
# ZstdFiles also does not support seek forward on write
if (not write0 and
(in_file == 'test.bz2' or
in_file == 'test.zst')): # Can't seek write in bz2, zst
if not write0 and in_file in ('test.bz2', 'test.zst'):
# write the zeros by hand for the read test below
fobj.write(b'\x00' * diff)
else:
Expand Down
1 change: 0 additions & 1 deletion nibabel/wrapstruct.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,6 @@ def __init__(self,
self._structarr = wstr.copy()
if check:
self.check_fix()
return

@classmethod
def from_fileobj(klass, fileobj, endianness=None, check=True):
Expand Down
5 changes: 2 additions & 3 deletions nisext/sexts.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,8 @@ def version_getter(pkg_name):
_add_append_key(setuptools_args['extras_require'],
optional,
dependency)
return
_add_append_key(setuptools_args, 'install_requires', dependency)
return
else:
_add_append_key(setuptools_args, 'install_requires', dependency)


def _package_status(pkg_name, version, version_getter, checker):
Expand Down
1 change: 0 additions & 1 deletion nisext/testers.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,6 @@ def contexts_print_info(mod_name, repo_path, install_path):
print(run_mod_cmd(mod_name, site_pkgs_path, cmd_str)[0])
# test from development tree
print(run_mod_cmd(mod_name, repo_path, cmd_str)[0])
return


def info_from_here(mod_name):
Expand Down