Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
2 changes: 1 addition & 1 deletion bin/nib-dicomfs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@
from nibabel.cmdline.dicomfs import main

if __name__ == '__main__':
main()
main()
5 changes: 3 additions & 2 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@

# General information about the project.
project = u'NiBabel'
copyright = u'2006-2020, %(maintainer)s <%(author_email)s>' % metadata
copyright = f"2006-2020, {metadata['maintainer']} <{metadata['author_email']}>"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
Expand Down Expand Up @@ -206,7 +206,8 @@
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
html_sidebars = {'index': ['localtoc.html', 'relations.html', 'sourcelink.html', 'indexsidebar.html', 'searchbox.html', 'reggie.html']}
html_sidebars = {'index': ['localtoc.html', 'relations.html', 'sourcelink.html',
'indexsidebar.html', 'searchbox.html', 'reggie.html']}

# Additional templates that should be rendered to pages, maps page names to
# template names.
Expand Down
2 changes: 1 addition & 1 deletion doc/source/devel/register_me.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def main():
dsource.set(name, version, OUR_PATH)
dsource.write(file(ini_fname, 'wt'))

print('Registered package %s, %s to %s' % (name, version, ini_fname))
print(f'Registered package {name}, {version} to {ini_fname}')


if __name__ == '__main__':
Expand Down
7 changes: 3 additions & 4 deletions doc/tools/apigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,8 +342,7 @@ def _survives_exclude(self, matchstr, match_type):
elif match_type == 'package':
patterns = self.package_skip_patterns
else:
raise ValueError('Cannot interpret match type "%s"'
% match_type)
raise ValueError(f'Cannot interpret match type "{match_type}"')
# Match to URI without package name
L = len(self.package_name)
if matchstr[:L] == self.package_name:
Expand Down Expand Up @@ -424,7 +423,7 @@ def write_modules_api(self, modules, outdir):
written_modules = []

for ulm, mods in module_by_ulm.items():
print("Generating docs for %s:" % ulm)
print(f"Generating docs for {ulm}:")
document_head = []
document_body = []

Expand Down Expand Up @@ -505,5 +504,5 @@ def write_index(self, outdir, froot='gen', relative_to=None):
w("=" * len(title) + "\n\n")
w('.. toctree::\n\n')
for f in self.written_modules:
w(' %s\n' % os.path.join(relpath, f))
w(f' {os.path.join(relpath, f)}\n')
idx.close()
2 changes: 1 addition & 1 deletion doc/tools/build_modref_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@


def abort(error):
print('*WARNING* API documentation not generated: %s' % error)
print(f'*WARNING* API documentation not generated: {error}')
exit(1)


Expand Down
39 changes: 19 additions & 20 deletions nibabel/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,20 +87,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(f"unable to run {dispcmd}")
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
print(f"unable to find command, tried {commands}")
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
print(f"unable to run {dispcmd} (error)")
print(f"stdout was {stdout}")
return None, p.returncode
return stdout, p.returncode

Expand All @@ -125,8 +125,8 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
root = os.path.dirname(root) # up a level

if verbose:
print("Tried directories %s but none started with prefix %s" %
(str(rootdirs), parentdir_prefix))
print(f"Tried directories {str(rootdirs)} but "
f"none started with prefix {parentdir_prefix}")
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")


Expand Down Expand Up @@ -201,9 +201,9 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
print(f"discarding '{','.join(refs - tags)}', no digits")
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
print(f"likely tags: {','.join(sorted(tags))}")
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
Expand All @@ -214,7 +214,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not re.match(r'\d', r):
continue
if verbose:
print("picking %s" % r)
print(f"picking {r}")
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None,
Expand Down Expand Up @@ -243,14 +243,14 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
hide_stderr=True)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
print(f"Directory {root} not under git control")
raise NotThisMethod("'git rev-parse --git-dir' returned error")

# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
"--match", f"{tag_prefix}*"],
cwd=root)
# --long was added in git-1.5.5
if describe_out is None:
Expand Down Expand Up @@ -283,18 +283,17 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
pieces["error"] = f"unable to parse git-describe output: '{describe_out}'"
return pieces

# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
txt = f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'"
print(txt)
pieces["error"] = (f"tag '{full_tag}' doesn't start with prefix "
f"'{tag_prefix}'")
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]

Expand Down Expand Up @@ -384,13 +383,13 @@ def render_pep440_post(pieces):
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
rendered += f"g{pieces['short']}"
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
rendered += f"+g{pieces['short']}"
return rendered


Expand Down Expand Up @@ -481,7 +480,7 @@ def render(pieces, style):
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
raise ValueError(f"unknown style '{style}'")

return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None,
Expand Down
17 changes: 7 additions & 10 deletions nibabel/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,11 +394,9 @@ def from_header(klass, header=None, check=True):
try:
obj.set_data_dtype(orig_code)
except HeaderDataError:
raise HeaderDataError('Input header %s has datatype %s but '
'output header %s does not support it'
% (header.__class__,
header.get_value_label('datatype'),
klass))
raise HeaderDataError(f"Input header {header.__class__} has "
f"datatype {header.get_value_label('datatype')} "
f"but output header {klass} does not support it")
obj.set_data_dtype(header.get_data_dtype())
obj.set_data_shape(header.get_data_shape())
obj.set_zooms(header.get_zooms())
Expand Down Expand Up @@ -571,16 +569,16 @@ def set_data_dtype(self, datatype):
dt = np.dtype(dt)
except TypeError:
raise HeaderDataError(
'data dtype "{0}" not recognized'.format(datatype))
f'data dtype "{datatype}" not recognized')
if dt not in self._data_type_codes:
raise HeaderDataError(
'data dtype "{0}" not supported'.format(datatype))
f'data dtype "{datatype}" not supported')
code = self._data_type_codes[dt]
dtype = self._data_type_codes.dtype[code]
# test for void, being careful of user-defined types
if dtype.type is np.void and not dtype.fields:
raise HeaderDataError(
'data dtype "{0}" known but not supported'.format(datatype))
f'data dtype "{datatype}" known but not supported')
self._structarr['datatype'] = code
self._structarr['bitpix'] = dtype.itemsize * 8

Expand Down Expand Up @@ -632,8 +630,7 @@ def set_data_shape(self, shape):
values_fit = np.all(dims[1:ndims + 1] == shape)
# Error if we did not succeed setting dimensions
if not values_fit:
raise HeaderDataError('shape %s does not fit in dim datatype' %
(shape,))
raise HeaderDataError(f'shape {shape} does not fit in dim datatype')
self._structarr['pixdim'][ndims + 1:] = 1.0

def get_base_affine(self):
Expand Down
8 changes: 4 additions & 4 deletions nibabel/arrayproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,8 @@ def _should_keep_file_open(self, file_like, keep_file_open):
if keep_file_open is None:
keep_file_open = KEEP_FILE_OPEN_DEFAULT
if keep_file_open not in (True, False):
raise ValueError("nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT must be boolean. "
"Found: {}".format(keep_file_open))
raise ValueError(f"nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT "
f"must be boolean. Found: {keep_file_open}")
elif keep_file_open not in (True, False):
raise ValueError('keep_file_open must be one of {None, True, False}')

Expand Down Expand Up @@ -412,8 +412,8 @@ def reshape(self, shape):
shape = tuple(unknown_size if e == -1 else e for e in shape)

if np.prod(shape) != size:
raise ValueError("cannot reshape array of size {:d} into shape "
"{!s}".format(size, shape))
raise ValueError(f"cannot reshape array of size {size:d} "
f"into shape {shape!s}")
return self.__class__(file_like=self.file_like,
spec=(shape, self._dtype, self._offset,
self._slope, self._inter),
Expand Down
3 changes: 1 addition & 2 deletions nibabel/batteryrunners.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,7 @@ def write_raise(self, stream, error_level=40, log_level=30):
write the report to `stream`, otherwise we write nothing.
"""
if self.problem_level >= log_level:
stream.write('Level %s: %s\n' %
(self.problem_level, self.message))
stream.write(f'Level {self.problem_level}: {self.message}\n')
if self.problem_level and self.problem_level >= error_level:
if self.error:
raise self.error(self.problem_msg)
13 changes: 6 additions & 7 deletions nibabel/benchmarks/bench_arrayproxy_slicing.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,12 @@ def fmt_sliceobj(sliceobj):
slcstr.append(s)
else:
slcstr.append(str(int(s * SHAPE[i])))
return '[{}]'.format(', '.join(slcstr))
return f"[{', '.join(slcstr)}]"

with InTemporaryDirectory():

print('Generating test data... ({} MB)'.format(
int(round(np.prod(SHAPE) * 4 / 1048576.))))
print(f'Generating test data... '
f'({int(round(np.prod(SHAPE) * 4 / 1048576.0))} MB)')

data = np.array(np.random.random(SHAPE), dtype=np.float32)

Expand Down Expand Up @@ -133,8 +133,7 @@ def fmt_sliceobj(sliceobj):
have_igzip, keep_open, sliceobj = test
seed = seeds[SLICEOBJS.index(sliceobj)]

print('Running test {} of {} ({})...'.format(
ti + 1, len(tests), label))
print(f'Running test {ti + 1} of {len(tests)} ({label})...')

# load uncompressed and compressed versions of the image
img = nib.load(testfile, keep_file_open=keep_open)
Expand Down Expand Up @@ -181,8 +180,8 @@ def testfunc():
data[:, 2] = np.nan
data[:, 3] = [r[5] - r[6] for r in results]

rowlbls = ['Type {}, keep_open {}, slice {}'.format(
r[0], r[1], fmt_sliceobj(r[2])) for r in results]
rowlbls = [(f'Type {r[0]}, keep_open {r[1]}, '
f'slice {fmt_sliceobj(r[2])}') for r in results]
collbls = ['Time', 'Baseline time', 'Time ratio', 'Memory deviation']

print(rst_table(data, rowlbls, collbls))
4 changes: 2 additions & 2 deletions nibabel/benchmarks/bench_fileslice.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from ..tmpdirs import InTemporaryDirectory

SHAPE = (64, 64, 32, 100)
ROW_NAMES = ['axis {0}, len {1}'.format(i, SHAPE[i])
ROW_NAMES = [f'axis {i}, len {SHAPE[i]}'
for i in range(len(SHAPE))]
COL_NAMES = ['mid int',
'step 1',
Expand Down Expand Up @@ -79,7 +79,7 @@ def my_table(title, times, base):
print()
print(rst_table(times, ROW_NAMES, COL_NAMES, title,
val_fmt='{0[0]:3.2f} ({0[1]:3.2f})'))
print('Base time: {0:3.2f}'.format(base))
print(f'Base time: {base:3.2f}')
if bytes:
fobj = BytesIO()
times, base = run_slices(fobj, repeat)
Expand Down
10 changes: 4 additions & 6 deletions nibabel/benchmarks/bench_streamlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,14 @@ def bench_load_trk():
streamlines_old = [d[0] - 0.5
for d in tv.read(trk_file, points_space="rasmm")[0]]
mtime_old = measure('tv.read(trk_file, points_space="rasmm")', repeat)
print("Old: Loaded {:,} streamlines in {:6.2f}".format(NB_STREAMLINES,
mtime_old))
print(f"Old: Loaded {NB_STREAMLINES:,} streamlines in {mtime_old:6.2f}")

trk = nib.streamlines.load(trk_file, lazy_load=False)
streamlines_new = trk.streamlines
mtime_new = measure('nib.streamlines.load(trk_file, lazy_load=False)',
repeat)
print("\nNew: Loaded {:,} streamlines in {:6.2}".format(NB_STREAMLINES,
mtime_new))
print("Speedup of {:.2f}".format(mtime_old / mtime_new))
print(f"\nNew: Loaded {NB_STREAMLINES:,} streamlines in {mtime_new:6.2}")
print(f"Speedup of {mtime_old / mtime_new:.2f}")
for s1, s2 in zip(streamlines_new, streamlines_old):
assert_array_equal(s1, s2)

Expand Down Expand Up @@ -81,7 +79,7 @@ def bench_load_trk():
repeat)
msg = "New: Loaded {:,} streamlines with scalars in {:6.2f}"
print(msg.format(NB_STREAMLINES, mtime_new))
print("Speedup of {:2f}".format(mtime_old / mtime_new))
print(f"Speedup of {mtime_old / mtime_new:2f}")
for s1, s2 in zip(scalars_new, scalars_old):
assert_array_equal(s1, s2)

Expand Down
4 changes: 1 addition & 3 deletions nibabel/benchmarks/butils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
def print_git_title(title):
""" Prints title string with git hash if possible, and underline
"""
title = '{0} for git revision {1}'.format(
title,
get_info()['commit_hash'])
title = f"{title} for git revision {get_info()['commit_hash']}"
print(title)
print('-' * len(title))
14 changes: 6 additions & 8 deletions nibabel/brikhead.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,23 +114,21 @@ def _unpack_var(var):
TEMPLATE_SPACE ORIG
"""

err_msg = ('Please check HEAD file to ensure it is AFNI compliant. '
'Offending attribute:\n%s' % var)
err_msg = (f'Please check HEAD file to ensure it is AFNI compliant. '
f'Offending attribute:\n{var}')
atype, aname = TYPE_RE.findall(var), NAME_RE.findall(var)
if len(atype) != 1:
raise AFNIHeaderError('Invalid attribute type entry in HEAD file. '
'%s' % err_msg)
raise AFNIHeaderError(f'Invalid attribute type entry in HEAD file. {err_msg}')
if len(aname) != 1:
raise AFNIHeaderError('Invalid attribute name entry in HEAD file. '
'%s' % err_msg)
raise AFNIHeaderError(f'Invalid attribute name entry in HEAD file. {err_msg}')
atype = _attr_dic.get(atype[0], str)
attr = ' '.join(var.strip().splitlines()[3:])
if atype is not str:
try:
attr = [atype(f) for f in attr.split()]
except ValueError:
raise AFNIHeaderError('Failed to read variable from HEAD file due '
'to improper type casting. %s' % err_msg)
raise AFNIHeaderError(f'Failed to read variable from HEAD file '
f'due to improper type casting. {err_msg}')
else:
# AFNI string attributes will always start with open single quote and
# end with a tilde (NUL). These attributes CANNOT contain tildes (so
Expand Down
Loading