From 60e4af989f9ef3f0bc0efe4917f4b1d2cd42f0c2 Mon Sep 17 00:00:00 2001 From: "Christopher J. Markiewicz" Date: Wed, 27 Jul 2022 07:36:43 -0400 Subject: [PATCH] STY: Manual, blue-compatible touchups [git-blame-ignore-rev] --- nibabel/analyze.py | 2 +- nibabel/arraywriters.py | 2 +- nibabel/brikhead.py | 12 ++---------- nibabel/casting.py | 16 ++++++++++----- nibabel/cifti2/cifti2.py | 16 ++++++++++----- nibabel/cifti2/cifti2_axes.py | 4 ++-- nibabel/cifti2/tests/test_new_cifti2.py | 4 ++-- nibabel/cmdline/diff.py | 4 ++-- nibabel/cmdline/ls.py | 2 +- nibabel/cmdline/nifti_dx.py | 2 +- nibabel/data.py | 4 +--- nibabel/dataobj_images.py | 2 +- nibabel/ecat.py | 6 +++--- nibabel/filebasedimages.py | 4 ++-- nibabel/filename_parser.py | 2 +- nibabel/fileslice.py | 2 +- nibabel/freesurfer/mghformat.py | 4 ++-- nibabel/gifti/gifti.py | 26 ++++++++++++------------- nibabel/gifti/giftiio.py | 4 ++-- nibabel/gifti/parse_gifti_fast.py | 6 +++--- nibabel/loadsave.py | 2 +- nibabel/minc1.py | 4 ++-- nibabel/minc2.py | 2 +- nibabel/nicom/csareader.py | 2 +- nibabel/nicom/dicomreaders.py | 4 ++-- nibabel/nicom/dicomwrappers.py | 14 ++++++------- nibabel/nifti1.py | 22 ++++++++++----------- nibabel/nifti2.py | 2 +- nibabel/optpkg.py | 2 +- nibabel/orientations.py | 8 ++++---- nibabel/parrec.py | 6 +++--- nibabel/processing.py | 4 ++-- nibabel/spatialimages.py | 6 +++--- nibabel/spm99analyze.py | 4 ++-- nibabel/streamlines/array_sequence.py | 2 +- nibabel/streamlines/trk.py | 11 ++++------- nibabel/tests/test_analyze.py | 2 +- nibabel/tests/test_image_types.py | 2 +- nibabel/viewers.py | 2 +- nibabel/volumeutils.py | 6 ++---- 40 files changed, 113 insertions(+), 118 deletions(-) diff --git a/nibabel/analyze.py b/nibabel/analyze.py index 4a76350d59..1818c9fc08 100644 --- a/nibabel/analyze.py +++ b/nibabel/analyze.py @@ -785,7 +785,7 @@ def set_slope_inter(self, slope, inter=None): """ if (slope in (None, 1) or np.isnan(slope)) and (inter in (None, 0) or np.isnan(inter)): return - raise HeaderTypeError('Cannot set slope != 1 or intercept != 0 ' 'for Analyze headers') + raise HeaderTypeError('Cannot set slope != 1 or intercept != 0 for Analyze headers') @classmethod def _get_checks(klass): diff --git a/nibabel/arraywriters.py b/nibabel/arraywriters.py index 58b1ed59c9..a40be09b2c 100644 --- a/nibabel/arraywriters.py +++ b/nibabel/arraywriters.py @@ -454,7 +454,7 @@ def _range_scale(self, in_min, in_max): if self._out_dtype.kind == 'u': if in_min < 0 and in_max > 0: raise WriterError( - 'Cannot scale negative and positive ' 'numbers to uint without intercept' + 'Cannot scale negative and positive numbers to uint without intercept' ) if in_max <= 0: # All input numbers <= 0 self.slope = in_min / out_max diff --git a/nibabel/brikhead.py b/nibabel/brikhead.py index 0559671217..3c96f97497 100644 --- a/nibabel/brikhead.py +++ b/nibabel/brikhead.py @@ -104,9 +104,7 @@ def _unpack_var(var): TEMPLATE_SPACE ORIG """ - err_msg = ( - 'Please check HEAD file to ensure it is AFNI compliant. ' f'Offending attribute:\n{var}' - ) + err_msg = f'Please check HEAD file to ensure it is AFNI compliant. Offending attribute:\n{var}' atype, aname = TYPE_RE.findall(var), NAME_RE.findall(var) if len(atype) != 1: raise AFNIHeaderError(f'Invalid attribute type entry in HEAD file. {err_msg}') @@ -354,13 +352,7 @@ def _calc_zooms(self): origin", and second giving "Time step (TR)". """ xyz_step = tuple(np.abs(self.info['DELTA'])) - t_step = self.info.get( - 'TAXIS_FLOATS', - ( - 0, - 0, - ), - ) + t_step = self.info.get('TAXIS_FLOATS', (0, 0)) if len(t_step) > 0: t_step = (t_step[1],) return xyz_step + t_step diff --git a/nibabel/casting.py b/nibabel/casting.py index ce58915fe9..a17a25a2c8 100644 --- a/nibabel/casting.py +++ b/nibabel/casting.py @@ -259,15 +259,15 @@ def type_info(np_type): if vals in ( (112, 15, 16), # binary128 (info_64.nmant, info_64.nexp, 8), # float64 - (63, 15, 12), - (63, 15, 16), - ): # Intel extended 80 + (63, 15, 12), # Intel extended 80 + (63, 15, 16), # Intel extended 80 + ): return ret # these are OK without modification # The remaining types are longdoubles with bad finfo values. Some we # correct, others we wait to hear of errors. # We start with float64 as basis ret = type_info(np.float64) - if vals in ((52, 15, 12), (52, 15, 16)): # windows float96 # windows float128? + if vals in ((52, 15, 12), (52, 15, 16)): # windows float96 / windows float128? # On windows 32 bit at least, float96 is Intel 80 storage but operating # at float64 precision. The finfo values give nexp == 15 (as for intel # 80) but in calculations nexp in fact appears to be 11 as for float64 @@ -298,7 +298,13 @@ def type_info(np_type): if np_type is np.longcomplex: max_val += 0j ret = dict( - min=-max_val, max=max_val, nmant=112, nexp=15, minexp=-16382, maxexp=16384, width=width + min=-max_val, + max=max_val, + nmant=112, + nexp=15, + minexp=-16382, + maxexp=16384, + width=width, ) else: # don't recognize the type raise FloatingError(f'We had not expected long double type {np_type} with info {info}') diff --git a/nibabel/cifti2/cifti2.py b/nibabel/cifti2/cifti2.py index fa22b09902..dfceb5c5c8 100644 --- a/nibabel/cifti2/cifti2.py +++ b/nibabel/cifti2/cifti2.py @@ -70,7 +70,7 @@ class Cifti2HeaderError(Exception): CIFTI_MODEL_TYPES = ( 'CIFTI_MODEL_TYPE_SURFACE', # Modeled using surface vertices - 'CIFTI_MODEL_TYPE_VOXELS', # Modeled using voxels. + 'CIFTI_MODEL_TYPE_VOXELS', # Modeled using voxels ) CIFTI_SERIESUNIT_TYPES = ('SECOND', 'HERTZ', 'METER', 'RADIAN') @@ -662,7 +662,7 @@ def __init__(self, name=None, voxel_indices_ijk=None, vertices=None): self.vertices = vertices if vertices is not None else [] for val in self.vertices: if not isinstance(val, Cifti2Vertices): - raise ValueError(('Cifti2Parcel vertices must be instances of ' 'Cifti2Vertices')) + raise ValueError(('Cifti2Parcel vertices must be instances of Cifti2Vertices')) @property def voxel_indices_ijk(self): @@ -1237,7 +1237,7 @@ def _validate_new_mim(self, value): a2md = self._get_indices_from_mim(value) if not set(self.mapped_indices).isdisjoint(a2md): raise Cifti2HeaderError( - 'Indices in this Cifti2MatrixIndicesMap ' 'already mapped in this matrix' + 'Indices in this Cifti2MatrixIndicesMap already mapped in this matrix' ) def __setitem__(self, key, value): @@ -1412,7 +1412,13 @@ class Cifti2Image(DataobjImage, SerializableImage): rw = True def __init__( - self, dataobj=None, header=None, nifti_header=None, extra=None, file_map=None, dtype=None + self, + dataobj=None, + header=None, + nifti_header=None, + extra=None, + file_map=None, + dtype=None, ): """Initialize image @@ -1485,7 +1491,7 @@ def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None): cifti_header = item.get_content() break else: - raise ValueError('NIfTI2 header does not contain a CIFTI-2 ' 'extension') + raise ValueError('NIfTI2 header does not contain a CIFTI-2 extension') # Construct cifti image. # Use array proxy object where possible diff --git a/nibabel/cifti2/cifti2_axes.py b/nibabel/cifti2/cifti2_axes.py index 3d88fca1e3..3142c8362b 100644 --- a/nibabel/cifti2/cifti2_axes.py +++ b/nibabel/cifti2/cifti2_axes.py @@ -665,7 +665,7 @@ def __add__(self, other): not np.allclose(other.affine, affine) or other.volume_shape != shape ): raise ValueError( - 'Trying to concatenate two BrainModels defined ' 'in a different brain volume' + 'Trying to concatenate two BrainModels defined in a different brain volume' ) nvertices = dict(self.nvertices) @@ -1008,7 +1008,7 @@ def __add__(self, other): not np.allclose(other.affine, affine) or other.volume_shape != shape ): raise ValueError( - 'Trying to concatenate two ParcelsAxis defined ' 'in a different brain volume' + 'Trying to concatenate two ParcelsAxis defined in a different brain volume' ) nvertices = dict(self.nvertices) for name, value in other.nvertices.items(): diff --git a/nibabel/cifti2/tests/test_new_cifti2.py b/nibabel/cifti2/tests/test_new_cifti2.py index 4e751d6865..aefe577781 100644 --- a/nibabel/cifti2/tests/test_new_cifti2.py +++ b/nibabel/cifti2/tests/test_new_cifti2.py @@ -472,7 +472,7 @@ def test_pconnseries(): hdr = ci.Cifti2Header(matrix) data = np.random.randn(4, 4, 13) img = ci.Cifti2Image(data, hdr) - img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_' 'PARCELLATED_SERIES') + img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_PARCELLATED_SERIES') with InTemporaryDirectory(): ci.save(img, 'test.pconnseries.nii') @@ -496,7 +496,7 @@ def test_pconnscalar(): hdr = ci.Cifti2Header(matrix) data = np.random.randn(4, 4, 2) img = ci.Cifti2Image(data, hdr) - img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_' 'PARCELLATED_SCALAR') + img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_PARCELLATED_SCALAR') with InTemporaryDirectory(): ci.save(img, 'test.pconnscalar.nii') diff --git a/nibabel/cmdline/diff.py b/nibabel/cmdline/diff.py index 5ca691ad64..799e17f645 100755 --- a/nibabel/cmdline/diff.py +++ b/nibabel/cmdline/diff.py @@ -51,7 +51,7 @@ def get_opt_parser(): '--header-fields', dest='header_fields', default='all', - help='Header fields (comma separated) to be printed as well' ' (if present)', + help='Header fields (comma separated) to be printed as well (if present)', ), Option( '--ma', @@ -59,7 +59,7 @@ def get_opt_parser(): dest='data_max_abs_diff', type=float, default=0.0, - help='Maximal absolute difference in data between files' ' to tolerate.', + help='Maximal absolute difference in data between files to tolerate.', ), Option( '--mr', diff --git a/nibabel/cmdline/ls.py b/nibabel/cmdline/ls.py index 50ddeb8ede..5ed8b3f194 100755 --- a/nibabel/cmdline/ls.py +++ b/nibabel/cmdline/ls.py @@ -20,7 +20,7 @@ import nibabel.cmdline.utils from nibabel.cmdline.utils import _err, ap, safe_get, table2string, verbose -__copyright__ = 'Copyright (c) 2011-18 Yaroslav Halchenko ' 'and NiBabel contributors' +__copyright__ = 'Copyright (c) 2011-18 Yaroslav Halchenko and NiBabel contributors' __license__ = 'MIT' diff --git a/nibabel/cmdline/nifti_dx.py b/nibabel/cmdline/nifti_dx.py index 64f02694ee..103bbf2640 100644 --- a/nibabel/cmdline/nifti_dx.py +++ b/nibabel/cmdline/nifti_dx.py @@ -15,7 +15,7 @@ import nibabel as nib __author__ = 'Matthew Brett' -__copyright__ = 'Copyright (c) 2011-18 Matthew Brett ' 'and NiBabel contributors' +__copyright__ = 'Copyright (c) 2011-18 Matthew Brett and NiBabel contributors' __license__ = 'MIT' diff --git a/nibabel/data.py b/nibabel/data.py index 5c04d51626..4fa1dc11a3 100644 --- a/nibabel/data.py +++ b/nibabel/data.py @@ -13,9 +13,7 @@ from .environment import get_nipy_system_dir, get_nipy_user_dir -DEFAULT_INSTALL_HINT = ( - 'If you have the package, have you set the ' 'path to the package correctly?' -) +DEFAULT_INSTALL_HINT = 'If you have the package, have you set the path to the package correctly?' class DataError(Exception): diff --git a/nibabel/dataobj_images.py b/nibabel/dataobj_images.py index a82480249b..5a027995b4 100644 --- a/nibabel/dataobj_images.py +++ b/nibabel/dataobj_images.py @@ -49,7 +49,7 @@ def dataobj(self): @property @deprecate_with_version( - '_data attribute not part of public API. ' 'please use "dataobj" property instead.', + '_data attribute not part of public API. Please use "dataobj" property instead.', '2.0', '4.0', ) diff --git a/nibabel/ecat.py b/nibabel/ecat.py index 27b0ccc522..a8809baac0 100644 --- a/nibabel/ecat.py +++ b/nibabel/ecat.py @@ -826,7 +826,7 @@ def __init__(self, dataobj, affine, header, subheader, mlist, extra=None, file_m def affine(self): if not self._subheader._check_affines(): warnings.warn( - 'Affines different across frames, loading affine ' 'from FIRST frame', UserWarning + 'Affines different across frames, loading affine from FIRST frame', UserWarning ) return self._affine @@ -908,7 +908,7 @@ def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None): # Get affine if not subheaders._check_affines(): warnings.warn( - 'Affines different across frames, loading affine ' 'from FIRST frame', UserWarning + 'Affines different across frames, loading affine from FIRST frame', UserWarning ) aff = subheaders.get_frame_affine() img = klass(data, aff, header, subheaders, mlist, extra=None, file_map=file_map) @@ -1025,7 +1025,7 @@ def to_file_map(self, file_map=None): @classmethod def from_image(klass, img): - raise NotImplementedError('Ecat images can only be generated ' 'from file objects') + raise NotImplementedError('Ecat images can only be generated from file objects') @classmethod def load(klass, filespec): diff --git a/nibabel/filebasedimages.py b/nibabel/filebasedimages.py index b109662cf3..d2cddc33f8 100644 --- a/nibabel/filebasedimages.py +++ b/nibabel/filebasedimages.py @@ -35,7 +35,7 @@ def from_header(klass, header=None): if type(header) == klass: return header.copy() raise NotImplementedError( - 'Header class requires a conversion ' f'from {klass} to {type(header)}' + f'Header class requires a conversion from {klass} to {type(header)}' ) @classmethod @@ -209,7 +209,7 @@ def __getitem__(self, key): raise TypeError('Cannot slice image objects.') @deprecate_with_version( - 'get_header method is deprecated.\n' 'Please use the ``img.header`` property ' 'instead.', + 'get_header method is deprecated.\nPlease use the ``img.header`` property instead.', '2.1', '4.0', ) diff --git a/nibabel/filename_parser.py b/nibabel/filename_parser.py index 223c9aa49b..86b6d2f579 100644 --- a/nibabel/filename_parser.py +++ b/nibabel/filename_parser.py @@ -114,7 +114,7 @@ def types_filenames( """ template_fname = _stringify_path(template_fname) if not isinstance(template_fname, str): - raise TypesFilenamesError('Need file name as input ' 'to set_filenames') + raise TypesFilenamesError('Need file name as input to set_filenames') if template_fname.endswith('.'): template_fname = template_fname[:-1] filename, found_ext, ignored, guessed_name = parse_filename( diff --git a/nibabel/fileslice.py b/nibabel/fileslice.py index 0c4bada62e..d2a38d263d 100644 --- a/nibabel/fileslice.py +++ b/nibabel/fileslice.py @@ -104,7 +104,7 @@ def canonical_slicers(sliceobj, shape, check_inds=True): if slicer == Ellipsis: remaining = sliceobj[i + 1 :] if Ellipsis in remaining: - raise ValueError('More than one Ellipsis in slicing ' 'expression') + raise ValueError('More than one Ellipsis in slicing expression') real_remaining = [r for r in remaining if r is not None] n_ellided = n_dim - n_real - len(real_remaining) can_slicers.extend((slice(None),) * n_ellided) diff --git a/nibabel/freesurfer/mghformat.py b/nibabel/freesurfer/mghformat.py index ba62d4a005..4ebc2f942b 100644 --- a/nibabel/freesurfer/mghformat.py +++ b/nibabel/freesurfer/mghformat.py @@ -313,7 +313,7 @@ def set_zooms(self, zooms): raise HeaderDataError('Expecting %d zoom values' % ndims) if np.any(zooms[:3] <= 0): raise HeaderDataError( - 'Spatial (first three) zooms must be positive; got ' f'{tuple(zooms[:3])}' + f'Spatial (first three) zooms must be positive; got {tuple(zooms[:3])}' ) hdr['delta'] = zooms[:3] if len(zooms) == 4: @@ -475,7 +475,7 @@ def as_byteswapped(self, endianness=None): """ if endianness is None or endian_codes[endianness] != '>': - raise ValueError('Cannot byteswap MGHHeader - ' 'must always be big endian') + raise ValueError('Cannot byteswap MGHHeader - must always be big endian') return self.copy() @classmethod diff --git a/nibabel/gifti/gifti.py b/nibabel/gifti/gifti.py index aede62d419..bd65fb01c0 100644 --- a/nibabel/gifti/gifti.py +++ b/nibabel/gifti/gifti.py @@ -108,7 +108,7 @@ def _sanitize(args, kwargs): @property @deprecate_with_version( - 'The data attribute is deprecated. Use GiftiMetaData object ' 'directly as a dict.', + 'The data attribute is deprecated. Use GiftiMetaData object directly as a dict.', '4.0', '6.0', ) @@ -123,7 +123,7 @@ def from_dict(klass, data_dict): return klass(data_dict) @deprecate_with_version( - 'get_metadata method deprecated. ' 'Use the metadata property instead.', '2.1', '4.0' + 'get_metadata method deprecated. Use the metadata property instead.', '2.1', '4.0' ) def get_metadata(self): return dict(self) @@ -153,7 +153,7 @@ class GiftiNVPairs: """ @deprecate_with_version( - 'GiftiNVPairs objects are deprecated. Use the GiftiMetaData object ' 'as a dict, instead.', + 'GiftiNVPairs objects are deprecated. Use the GiftiMetaData object as a dict, instead.', '4.0', '6.0', ) @@ -276,7 +276,7 @@ def __repr__(self): return f'' @deprecate_with_version( - 'get_rgba method deprecated. ' 'Use the rgba property instead.', '2.1', '4.0' + 'get_rgba method deprecated. Use the rgba property instead.', '2.1', '4.0' ) def get_rgba(self): return self.rgba @@ -525,7 +525,7 @@ def num_dim(self, value): @classmethod @deprecate_with_version( - 'from_array method is deprecated. ' 'Please use GiftiDataArray constructor instead.', + 'from_array method is deprecated. Please use GiftiDataArray constructor instead.', '2.1', '4.0', ) @@ -618,7 +618,7 @@ def _to_xml_element(self): return data_array @deprecate_with_version( - 'to_xml_open method deprecated. ' 'Use the to_xml() function instead.', '2.1', '4.0' + 'to_xml_open method deprecated. Use the to_xml() function instead.', '2.1', '4.0' ) def to_xml_open(self): out = """\n' @@ -666,7 +666,7 @@ def print_summary(self): print(self.coordsys.print_summary()) @deprecate_with_version( - 'get_metadata method deprecated. ' 'Use the metadata property instead.', '2.1', '4.0' + 'get_metadata method deprecated. Use the metadata property instead.', '2.1', '4.0' ) def get_metadata(self): return dict(self.meta) @@ -761,7 +761,7 @@ def labeltable(self, labeltable): self._labeltable = labeltable @deprecate_with_version( - 'set_labeltable method deprecated. ' 'Use the gifti_img.labeltable property instead.', + 'set_labeltable method deprecated. Use the gifti_img.labeltable property instead.', '2.1', '4.0', ) @@ -769,7 +769,7 @@ def set_labeltable(self, labeltable): self.labeltable = labeltable @deprecate_with_version( - 'get_labeltable method deprecated. ' 'Use the gifti_img.labeltable property instead.', + 'get_labeltable method deprecated. Use the gifti_img.labeltable property instead.', '2.1', '4.0', ) @@ -793,13 +793,13 @@ def meta(self, meta): self._meta = meta @deprecate_with_version( - 'set_meta method deprecated. ' 'Use the gifti_img.meta property instead.', '2.1', '4.0' + 'set_meta method deprecated. Use the gifti_img.meta property instead.', '2.1', '4.0' ) def set_metadata(self, meta): self.meta = meta @deprecate_with_version( - 'get_meta method deprecated. ' 'Use the gifti_img.meta property instead.', '2.1', '4.0' + 'get_meta method deprecated. Use the gifti_img.meta property instead.', '2.1', '4.0' ) def get_meta(self): return self.meta @@ -967,7 +967,7 @@ def agg_data(self, intent_code=None): return all_data @deprecate_with_version( - 'getArraysFromIntent method deprecated. ' 'Use get_arrays_from_intent instead.', + 'getArraysFromIntent method deprecated. Use get_arrays_from_intent instead.', '2.1', '4.0', ) diff --git a/nibabel/gifti/giftiio.py b/nibabel/gifti/giftiio.py index 35245e06b5..7ac6eba07f 100644 --- a/nibabel/gifti/giftiio.py +++ b/nibabel/gifti/giftiio.py @@ -14,7 +14,7 @@ @deprecate_with_version( - 'giftiio.read function deprecated. ' 'Use nibabel.load() instead.', '2.1', '4.0' + 'giftiio.read function deprecated. Use nibabel.load() instead.', '2.1', '4.0' ) def read(filename): """Load a Gifti image from a file @@ -35,7 +35,7 @@ def read(filename): @deprecate_with_version( - 'giftiio.write function deprecated. ' 'Use nibabel.save() instead.', '2.1', '4.0' + 'giftiio.write function deprecated. Use nibabel.save() instead.', '2.1', '4.0' ) def write(image, filename): """Save the current image to a new file diff --git a/nibabel/gifti/parse_gifti_fast.py b/nibabel/gifti/parse_gifti_fast.py index 7ceb957e62..341eec5539 100644 --- a/nibabel/gifti/parse_gifti_fast.py +++ b/nibabel/gifti/parse_gifti_fast.py @@ -86,7 +86,7 @@ def read_data_block(darray, fname, data, mmap): if enclabel == 'External': if fname is None: raise GiftiParseError( - 'ExternalFileBinary is not supported ' 'when loading from in-memory XML' + 'ExternalFileBinary is not supported when loading from in-memory XML' ) ext_fname = op.join(op.dirname(fname), darray.ext_fname) if not op.exists(ext_fname): @@ -413,7 +413,7 @@ def pending_data(self): class Outputter(GiftiImageParser): @deprecate_with_version( - 'Outputter class deprecated. ' 'Use GiftiImageParser instead.', '2.1', '4.0' + 'Outputter class deprecated. Use GiftiImageParser instead.', '2.1', '4.0' ) def __init__(self): super(Outputter, self).__init__() @@ -424,7 +424,7 @@ def initialize(self): @deprecate_with_version( - 'parse_gifti_file deprecated. ' 'Use GiftiImageParser.parse() instead.', '2.1', '4.0' + 'parse_gifti_file deprecated. Use GiftiImageParser.parse() instead.', '2.1', '4.0' ) def parse_gifti_file(fname=None, fptr=None, buffer_size=None): GiftiImageParser(buffer_size=buffer_size).parse(fname=fname, fptr=fptr) diff --git a/nibabel/loadsave.py b/nibabel/loadsave.py index da672a869d..756bef7784 100644 --- a/nibabel/loadsave.py +++ b/nibabel/loadsave.py @@ -202,7 +202,7 @@ def save(img, filename, **kwargs): @deprecate_with_version( - 'read_img_data deprecated. ' 'Please use ``img.dataobj.get_unscaled()`` instead.', '3.2', '5.0' + 'read_img_data deprecated. Please use ``img.dataobj.get_unscaled()`` instead.', '3.2', '5.0' ) def read_img_data(img, prefer='scaled'): """Read data from image associated with files diff --git a/nibabel/minc1.py b/nibabel/minc1.py index 222374a5ea..084db6df49 100644 --- a/nibabel/minc1.py +++ b/nibabel/minc1.py @@ -127,7 +127,7 @@ def _get_valid_range(self): except AttributeError: valid_range = [info.min, info.max] if valid_range[0] < info.min or valid_range[1] > info.max: - raise ValueError('Valid range outside input ' 'data type range') + raise ValueError('Valid range outside input data type range') return np.asarray(valid_range, dtype=np.float64) def _get_scalar(self, var): @@ -170,7 +170,7 @@ def _normalize(self, data, sliceobj=()): mx_dims = self._get_dimensions(image_max) mn_dims = self._get_dimensions(image_min) if mx_dims != mn_dims: - raise MincError('"image-max" and "image-min" do not have the same' 'dimensions') + raise MincError('"image-max" and "image-min" do not have the same dimensions') nscales = len(mx_dims) if nscales > 2: raise MincError('More than two scaling dimensions') diff --git a/nibabel/minc2.py b/nibabel/minc2.py index 18448d2d07..66d38ffbee 100644 --- a/nibabel/minc2.py +++ b/nibabel/minc2.py @@ -97,7 +97,7 @@ def _get_valid_range(self): valid_range = [info.min, info.max] else: if valid_range[0] < info.min or valid_range[1] > info.max: - raise ValueError('Valid range outside input ' 'data type range') + raise ValueError('Valid range outside input data type range') return np.asarray(valid_range, dtype=np.float64) def _get_scalar(self, var): diff --git a/nibabel/nicom/csareader.py b/nibabel/nicom/csareader.py index f03a458983..1ed38ed5d0 100644 --- a/nibabel/nicom/csareader.py +++ b/nibabel/nicom/csareader.py @@ -138,7 +138,7 @@ def read(csa_str): else: # CSA2 item_len = x1 if (ptr + item_len) > csa_len: - raise CSAReadError('Item is too long, ' 'aborting read') + raise CSAReadError('Item is too long, aborting read') if item_no >= n_values: assert item_len == 0 continue diff --git a/nibabel/nicom/dicomreaders.py b/nibabel/nicom/dicomreaders.py index 2693ea31e2..d1612c9852 100644 --- a/nibabel/nicom/dicomreaders.py +++ b/nibabel/nicom/dicomreaders.py @@ -170,9 +170,9 @@ def _third_pass(wrappers): '- slices are probably unsortable' ) if None in inos: - raise DicomReadError(msg_fmt % 'some or all slices with ' 'missing InstanceNumber') + raise DicomReadError(msg_fmt % 'some or all slices with missing InstanceNumber') if len(set(inos)) < len(inos): - raise DicomReadError(msg_fmt % 'some or all slices with ' 'the same InstanceNumber') + raise DicomReadError(msg_fmt % 'some or all slices with the same InstanceNumber') # sort by instance number wrappers.sort(key=_instance_sorter) # start loop, in which we start a new volume, each time we see a z diff --git a/nibabel/nicom/dicomwrappers.py b/nibabel/nicom/dicomwrappers.py index cf046058a9..d27764d577 100755 --- a/nibabel/nicom/dicomwrappers.py +++ b/nibabel/nicom/dicomwrappers.py @@ -195,7 +195,7 @@ def rotation_matrix(self): # motivated in ``doc/source/notebooks/ata_error.ipynb``, and from # discussion at https://github.com/nipy/nibabel/pull/156 if not np.allclose(np.eye(3), np.dot(R, R.T), atol=5e-5): - raise WrapperPrecisionError('Rotation matrix not nearly ' 'orthogonal') + raise WrapperPrecisionError('Rotation matrix not nearly orthogonal') return R @one_time @@ -297,7 +297,7 @@ def get(self, key, default=None): return self.dcm_data.get(key, default) @deprecate_with_version( - 'get_affine method is deprecated.\n' 'Please use the ``img.affine`` property ' 'instead.', + 'get_affine method is deprecated.\nPlease use the ``img.affine`` property instead.', '2.5.1', '4.0', ) @@ -547,7 +547,7 @@ def image_shape(self): stack_ids = set(frame.FrameContentSequence[0].StackID for frame in self.frames) if len(stack_ids) > 1: raise WrapperError( - 'File contains more than one StackID. ' 'Cannot handle multi-stack files' + 'File contains more than one StackID. Cannot handle multi-stack files' ) # Determine if one of the dimension indices refers to the stack id dim_seq = [dim.DimensionIndexPointer for dim in self.get('DimensionIndexSequence')] @@ -561,9 +561,7 @@ def image_shape(self): # derived volume is included derived_tag = pydicom.datadict.tag_for_keyword('DiffusionBValue') if derived_tag not in dim_seq: - raise WrapperError( - 'Missing information, cannot remove indices ' 'with confidence.' - ) + raise WrapperError('Missing information, cannot remove indices with confidence.') derived_dim_idx = dim_seq.index(derived_tag) frame_indices = np.delete(frame_indices, derived_dim_idx, axis=1) # account for the 2 additional dimensions (row and column) not included @@ -578,7 +576,7 @@ def image_shape(self): shape = (rows, cols) + tuple(ns_unique) n_vols = np.prod(shape[3:]) if n_frames != n_vols * shape[2]: - raise WrapperError('Calculated shape does not match number of ' 'frames.') + raise WrapperError('Calculated shape does not match number of frames.') return tuple(shape) @one_time @@ -592,7 +590,7 @@ def image_orient_patient(self): try: iop = self.frames[0].PlaneOrientationSequence[0].ImageOrientationPatient except AttributeError: - raise WrapperError('Not enough information for ' 'image_orient_patient') + raise WrapperError('Not enough information for image_orient_patient') if iop is None: return None iop = np.array(list(map(float, iop))) diff --git a/nibabel/nifti1.py b/nibabel/nifti1.py index 43da0adb4f..b921ae4fa2 100644 --- a/nibabel/nifti1.py +++ b/nibabel/nifti1.py @@ -815,7 +815,7 @@ def get_data_shape(self): vec_len = int(self._structarr['glmin']) if vec_len == 0: raise HeaderDataError( - '-1 in dim[1] but 0 in glmin; ' 'inconsistent freesurfer type header?' + '-1 in dim[1] but 0 in glmin; inconsistent freesurfer type header?' ) return (vec_len, 1, 1) + shape[3:] # Apply freesurfer hack for ico7 surface @@ -1095,7 +1095,7 @@ def set_qform(self, affine, code=None, strip_shears=True): P, S, Qs = npl.svd(R) PR = np.dot(P, Qs) if not strip_shears and not np.allclose(PR, R): - raise HeaderDataError('Shears in affine and `strip_shears` is ' 'False') + raise HeaderDataError('Shears in affine and `strip_shears` is False') # Convert to quaternion quat = mat2quat(PR) # Set into header @@ -1498,7 +1498,7 @@ def get_slice_duration(self): """ _, _, slice_dim = self.get_dim_info() if slice_dim is None: - raise HeaderDataError('Slice dimension must be set ' 'for duration to be valid') + raise HeaderDataError('Slice dimension must be set for duration to be valid') return float(self._structarr['slice_duration']) def set_slice_duration(self, duration): @@ -1515,20 +1515,20 @@ def set_slice_duration(self, duration): """ _, _, slice_dim = self.get_dim_info() if slice_dim is None: - raise HeaderDataError('Slice dimension must be set ' 'for duration to be valid') + raise HeaderDataError('Slice dimension must be set for duration to be valid') self._structarr['slice_duration'] = duration def get_n_slices(self): """Return the number of slices""" _, _, slice_dim = self.get_dim_info() if slice_dim is None: - raise HeaderDataError('Slice dimension not set in header ' 'dim_info') + raise HeaderDataError('Slice dimension not set in header dim_info') shape = self.get_data_shape() try: slice_len = shape[slice_dim] except IndexError: raise HeaderDataError( - f'Slice dimension index ({slice_dim}) ' f'outside shape tuple ({shape})' + f'Slice dimension index ({slice_dim}) outside shape tuple ({shape})' ) return slice_len @@ -1561,7 +1561,7 @@ def get_slice_times(self): duration = self.get_slice_duration() slabel = self.get_value_label('slice_code') if slabel == 'unknown': - raise HeaderDataError('Cannot get slice times when ' 'Slice code is "unknown"') + raise HeaderDataError('Cannot get slice times when slice code is "unknown"') slice_start, slice_end = (int(hdr['slice_start']), int(hdr['slice_end'])) if slice_start < 0: raise HeaderDataError('slice_start should be >= 0') @@ -1602,7 +1602,7 @@ def set_slice_times(self, slice_times): hdr = self._structarr slice_len = self.get_n_slices() if slice_len != len(slice_times): - raise HeaderDataError('Number of slice times does not ' 'match number of slices') + raise HeaderDataError('Number of slice times does not match number of slices') # Extract Nones at beginning and end. Check for others for ind, time in enumerate(slice_times): if time is not None: @@ -1617,12 +1617,12 @@ def set_slice_times(self, slice_times): timed = slice_times[slice_start : slice_end + 1] for time in timed: if time is None: - raise HeaderDataError('Cannot have None in middle ' 'of slice time vector') + raise HeaderDataError('Cannot have None in middle of slice time vector') # Find slice duration, check times are compatible with single # duration tdiffs = np.diff(np.sort(timed)) if not np.allclose(np.diff(tdiffs), 0): - raise HeaderDataError('Slice times not compatible with ' 'single slice duration') + raise HeaderDataError('Slice times not compatible with single slice duration') duration = np.mean(tdiffs) # To slice time order st_order = np.round(np.array(timed) / duration) @@ -1752,7 +1752,7 @@ def _chk_offset(hdr, fix=False): return hdr, rep if magic == hdr.single_magic and offset < hdr.single_vox_offset: rep.problem_level = 40 - rep.problem_msg = 'vox offset %d too low for ' 'single file nifti1' % offset + rep.problem_msg = 'vox offset %d too low for single file nifti1' % offset if fix: hdr['vox_offset'] = hdr.single_vox_offset rep.fix_msg = f'setting to minimum value of {hdr.single_vox_offset}' diff --git a/nibabel/nifti2.py b/nibabel/nifti2.py index 6c8727355b..b42588714f 100644 --- a/nibabel/nifti2.py +++ b/nibabel/nifti2.py @@ -211,7 +211,7 @@ def _chk_eol_check(hdr, fix=False): return hdr, rep rep.problem_level = 40 rep.problem_msg = ( - 'EOL check not 0 or 13, 10, 26, 10; data may be ' 'corrupted by EOL conversion' + 'EOL check not 0 or 13, 10, 26, 10; data may be corrupted by EOL conversion' ) if fix: hdr['eol_check'] = (13, 10, 26, 10) diff --git a/nibabel/optpkg.py b/nibabel/optpkg.py index c91ad0f1e8..d1eb9d17d5 100644 --- a/nibabel/optpkg.py +++ b/nibabel/optpkg.py @@ -105,7 +105,7 @@ def optional_package(name, trip_msg=None, min_version=None): trip_msg = f'These functions need {name} version >= {min_version}' if trip_msg is None: trip_msg = ( - f'We need package {name} for these functions, ' f'but ``import {name}`` raised {exc}' + f'We need package {name} for these functions, but ``import {name}`` raised {exc}' ) pkg = TripWire(trip_msg) diff --git a/nibabel/orientations.py b/nibabel/orientations.py index 271033c669..fc2ac8d99c 100644 --- a/nibabel/orientations.py +++ b/nibabel/orientations.py @@ -154,10 +154,10 @@ def apply_orientation(arr, ornt): ornt = np.asarray(ornt) n = ornt.shape[0] if t_arr.ndim < n: - raise OrientationError('Data array has fewer dimensions than ' 'orientation') + raise OrientationError('Data array has fewer dimensions than orientation') # no coordinates can be dropped for applying the orientations if np.any(np.isnan(ornt[:, 0])): - raise OrientationError('Cannot drop coordinates when ' 'applying orientation to data') + raise OrientationError('Cannot drop coordinates when applying orientation to data') # apply ornt transformations for ax, flip in enumerate(ornt[:, 1]): if flip == -1: @@ -226,13 +226,13 @@ def inv_ornt_aff(ornt, shape): @deprecate_with_version( - 'orientation_affine deprecated. ' 'Please use inv_ornt_aff instead.', '3.0', '4.0' + 'orientation_affine deprecated. Please use inv_ornt_aff instead.', '3.0', '4.0' ) def orientation_affine(ornt, shape): return inv_ornt_aff(ornt, shape) -@deprecate_with_version('flip_axis is deprecated. ' 'Please use numpy.flip instead.', '3.2', '5.0') +@deprecate_with_version('flip_axis is deprecated. Please use numpy.flip instead.', '3.2', '5.0') def flip_axis(arr, axis=0): """Flip contents of `axis` in array `arr` diff --git a/nibabel/parrec.py b/nibabel/parrec.py index 8a9100f692..f77e5835f8 100644 --- a/nibabel/parrec.py +++ b/nibabel/parrec.py @@ -805,7 +805,7 @@ def from_header(klass, header=None): raise PARRECError('Cannot create PARRECHeader from air.') if type(header) == klass: return header.copy() - raise PARRECError('Cannot create PARREC header from ' 'non-PARREC header.') + raise PARRECError('Cannot create PARREC header from non-PARREC header.') @classmethod def from_fileobj(klass, fileobj, permit_truncated=False, strict_sort=False): @@ -931,12 +931,12 @@ def _get_unique_image_prop(self, name): props = self.image_defs[name] if np.any(np.diff(props, axis=0)): raise PARRECError( - f'Varying {name} in image sequence ' f'({props}). This is not supported.' + f'Varying {name} in image sequence ({props}). This is not supported.' ) return props[0] @deprecate_with_version( - 'get_voxel_size deprecated. ' 'Please use "get_zooms" instead.', '2.0', '4.0' + 'get_voxel_size deprecated. Please use "get_zooms" instead.', '2.0', '4.0' ) def get_voxel_size(self): """Returns the spatial extent of a voxel. diff --git a/nibabel/processing.py b/nibabel/processing.py index 669b416fb6..57a215f602 100644 --- a/nibabel/processing.py +++ b/nibabel/processing.py @@ -155,7 +155,7 @@ def resample_from_to( # This check requires `shape` attribute of image if not spatial_axes_first(from_img): raise ValueError( - 'Cannot predict position of spatial axes for Image ' 'type ' + str(type(from_img)) + f'Cannot predict position of spatial axes for Image type {type(from_img)}' ) try: to_shape, to_affine = to_vox_map.shape, to_vox_map.affine @@ -276,7 +276,7 @@ def smooth_image(img, fwhm, mode='nearest', cval=0.0, out_class=Nifti1Image): # This check requires `shape` attribute of image if not spatial_axes_first(img): raise ValueError( - 'Cannot predict position of spatial axes for Image ' 'type ' + str(type(img)) + f'Cannot predict position of spatial axes for Image type {type(img)}' ) if out_class is None: out_class = img.__class__ diff --git a/nibabel/spatialimages.py b/nibabel/spatialimages.py index 40e5f2a1cd..bf2772f460 100644 --- a/nibabel/spatialimages.py +++ b/nibabel/spatialimages.py @@ -303,7 +303,7 @@ class Header(SpatialHeader): """Alias for SpatialHeader; kept for backwards compatibility.""" @deprecate_with_version( - 'Header class is deprecated.\n' 'Please use SpatialHeader instead.' 'instead.', + 'Header class is deprecated.\nPlease use SpatialHeader instead.', '2.1', '4.0', ) @@ -372,7 +372,7 @@ def check_slicing(self, slicer, return_spatial=False): raise IndexError('New axis not permitted in spatial dimensions') elif isinstance(subslicer, int): raise IndexError( - 'Scalar indices disallowed in spatial dimensions; ' 'Use `[x]` or `x:x+1`.' + 'Scalar indices disallowed in spatial dimensions; Use `[x]` or `x:x+1`.' ) return spatial_slices if return_spatial else slicer @@ -529,7 +529,7 @@ def set_data_dtype(self, dtype): self._header.set_data_dtype(dtype) @deprecate_with_version( - 'get_affine method is deprecated.\n' 'Please use the ``img.affine`` property ' 'instead.', + 'get_affine method is deprecated.\nPlease use the ``img.affine`` property instead.', '2.1', '4.0', ) diff --git a/nibabel/spm99analyze.py b/nibabel/spm99analyze.py index 3eabd76b29..6696f8cd48 100644 --- a/nibabel/spm99analyze.py +++ b/nibabel/spm99analyze.py @@ -88,7 +88,7 @@ def set_slope_inter(self, slope, inter=None): self._structarr['scl_slope'] = slope if inter in (None, 0) or np.isnan(inter): return - raise HeaderTypeError('Cannot set non-zero intercept ' 'for SPM headers') + raise HeaderTypeError('Cannot set non-zero intercept for SPM headers') class Spm99AnalyzeHeader(SpmAnalyzeHeader): @@ -282,7 +282,7 @@ def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None): if 'mat' in mats: # this overrides a 'M', and includes any flip mat = mats['mat'] if mat.ndim > 2: - warnings.warn('More than one affine in "mat" matrix, ' 'using first') + warnings.warn('More than one affine in "mat" matrix, using first') mat = mat[:, :, 0] ret._affine = mat elif 'M' in mats: # the 'M' matrix does not include flips diff --git a/nibabel/streamlines/array_sequence.py b/nibabel/streamlines/array_sequence.py index ac677f5e56..9c29642cc6 100644 --- a/nibabel/streamlines/array_sequence.py +++ b/nibabel/streamlines/array_sequence.py @@ -542,7 +542,7 @@ def _op(self, op, value=None, inplace=False): def __iter__(self): if len(self._lengths) != len(self._offsets): raise ValueError( - 'ArraySequence object corrupted:' ' len(self._lengths) != len(self._offsets)' + 'ArraySequence object corrupted: len(self._lengths) != len(self._offsets)' ) for offset, lengths in zip(self._offsets, self._lengths): diff --git a/nibabel/streamlines/trk.py b/nibabel/streamlines/trk.py index 27eb275eec..9c4d0f27a9 100644 --- a/nibabel/streamlines/trk.py +++ b/nibabel/streamlines/trk.py @@ -543,7 +543,7 @@ def save(self, fileobj): raise DataError(msg) if nb_properties_per_streamline != int(nb_properties_per_streamline): - msg = 'Nb. of properties differs from one streamline to' ' another!' + msg = 'Nb. of properties differs from one streamline to another!' raise DataError(msg) header[Field.NB_STREAMLINES] = nb_streamlines @@ -601,7 +601,7 @@ def _read_header(fileobj): pass # Nothing more to do. else: raise HeaderError( - 'NiBabel only supports versions 1 and 2 of ' 'the Trackvis file format' + 'NiBabel only supports versions 1 and 2 of the Trackvis file format' ) # Convert the first record of `header_rec` into a dictionary @@ -612,11 +612,8 @@ def _read_header(fileobj): if header[Field.VOXEL_TO_RASMM][3][3] == 0: header[Field.VOXEL_TO_RASMM] = np.eye(4, dtype=np.float32) warnings.warn( - ( - "Field 'vox_to_ras' in the TRK's header was" - " not recorded. Will continue assuming it's" - ' the identity.' - ), + "Field 'vox_to_ras' in the TRK's header was not recorded. " + "Will continue assuming it's the identity.", HeaderWarning, ) diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 61fd3b2c6a..902377553c 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -238,7 +238,7 @@ def test_logger_error(self): imageglobals.logger = logger hdr.copy().check_fix() assert str_io.getvalue() == ( - 'bitpix does not match datatype; ' 'setting bitpix to match datatype\n' + 'bitpix does not match datatype; setting bitpix to match datatype\n' ) # Check that error_level in fact causes error to be raised imageglobals.error_level = 10 diff --git a/nibabel/tests/test_image_types.py b/nibabel/tests/test_image_types.py index f8186f4147..9fd48ee697 100644 --- a/nibabel/tests/test_image_types.py +++ b/nibabel/tests/test_image_types.py @@ -104,7 +104,7 @@ def check_img(img_path, img_klass, sniff_mode, sniff, expect_success, msg): # Reuse the sniff... but it will only change for some # sniff_mode values. - msg = f'{expected_img_klass.__name__}/ {sniff_mode}/ ' f'{expect_success}' + msg = f'{expected_img_klass.__name__}/ {sniff_mode}/ {expect_success}' sniff = check_img( img_path, klass, diff --git a/nibabel/viewers.py b/nibabel/viewers.py index 072269edbd..5286aa5b41 100644 --- a/nibabel/viewers.py +++ b/nibabel/viewers.py @@ -319,7 +319,7 @@ def link_to(self, other): """ if not isinstance(other, self.__class__): raise TypeError( - 'other must be an instance of ' f'{self.__class__.__name__}, not {type(other)}' + f'other must be an instance of {self.__class__.__name__}, not {type(other)}' ) self._link(other, is_primary=True) diff --git a/nibabel/volumeutils.py b/nibabel/volumeutils.py index 379c05d853..f0fc8499a8 100644 --- a/nibabel/volumeutils.py +++ b/nibabel/volumeutils.py @@ -1344,7 +1344,7 @@ class BinOpener(Opener): __doc__ = Opener.__doc__ @deprecate_with_version( - 'BinOpener class deprecated. ' 'Please use Opener class instead.', '2.1', '4.0' + 'BinOpener class deprecated. Please use Opener class instead.', '2.1', '4.0' ) def __init__(self, *args, **kwargs): return super(BinOpener, self).__init__(*args, **kwargs) @@ -1382,9 +1382,7 @@ def fname_ext_ul_case(fname): return fname -@deprecate_with_version( - 'allopen is deprecated. ' 'Please use "Opener" class instead.', '2.0', '4.0' -) +@deprecate_with_version('allopen is deprecated. Please use "Opener" class instead.', '2.0', '4.0') def allopen(fileish, *args, **kwargs): """Compatibility wrapper for old ``allopen`` function