Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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
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("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
8 changes: 4 additions & 4 deletions nibabel/casting.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def type_info(np_type):
# and then give up. At this stage we're expecting exotic longdouble or
# their complex equivalent.
if np_type not in (np.longdouble, np.longcomplex) or width not in (16, 32):
raise FloatingError('We had not expected type %s' % np_type)
raise FloatingError(f'We had not expected type {np_type}')
if (vals == (1, 1, 16) and on_powerpc() and
_check_maxexp(np.longdouble, 1024)):
# double pair on PPC. The _check_nmant routine does not work for this
Expand Down Expand Up @@ -296,8 +296,8 @@ def type_info(np_type):
maxexp=16384,
width=width)
else: # don't recognize the type
raise FloatingError('We had not expected long double type %s '
'with info %s' % (np_type, info))
raise FloatingError(f'We had not expected long double '
f'type {np_type} with info {info}')
return ret


Expand Down Expand Up @@ -402,7 +402,7 @@ def as_int(x, check=True):
return ix
fx = np.floor(x)
if check and fx != x:
raise FloatingError('Not an integer: %s' % x)
raise FloatingError(f'Not an integer: {x}')
if not fx.dtype.type == np.longdouble:
return int(x)
# Subtract float64 chunks until we have all of the number. If the int is
Expand Down
16 changes: 7 additions & 9 deletions nibabel/cifti2/cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ class Cifti2HeaderError(Exception):
def _value_if_klass(val, klass):
if val is None or isinstance(val, klass):
return val
raise ValueError('Not a valid %s instance.' % klass.__name__)
raise ValueError(f'Not a valid {klass.__name__} instance.')


def _underscore(string):
Expand Down Expand Up @@ -291,8 +291,8 @@ def _to_xml_element(self):
v = _float_01(getattr(self, c_))
except ValueError:
raise Cifti2HeaderError(
'Label invalid %s needs to be a float between 0 and 1. '
'and it is %s' % (c_, v)
f'Label invalid {c_} needs to be a '
f'float between 0 and 1. and it is {v}'
)

lab = xml.Element('Label')
Expand Down Expand Up @@ -1379,9 +1379,8 @@ def __init__(self,
self.update_headers()

if self._dataobj.shape != self.header.matrix.get_data_shape():
warn("Dataobj shape {} does not match shape expected from CIFTI-2 header {}".format(
self._dataobj.shape, self.header.matrix.get_data_shape()
))
warn(f"Dataobj shape {self._dataobj.shape} does not match shape "
f"expected from CIFTI-2 header {self.header.matrix.get_data_shape()}")

@property
def nifti_header(self):
Expand Down Expand Up @@ -1459,9 +1458,8 @@ def to_file_map(self, file_map=None):
header.extensions.append(extension)
if self._dataobj.shape != self.header.matrix.get_data_shape():
raise ValueError(
"Dataobj shape {} does not match shape expected from CIFTI-2 header {}".format(
self._dataobj.shape, self.header.matrix.get_data_shape()
))
f"Dataobj shape {self._dataobj.shape} does not match shape "
f"expected from CIFTI-2 header {self.header.matrix.get_data_shape()}")
# if intent code is not set, default to unknown CIFTI
if header.get_intent()[0] == 'none':
header.set_intent('NIFTI_INTENT_CONNECTIVITY_UNKNOWN')
Expand Down
Loading