Skip to content

Commit cfea21a

Browse files
committed
chore(sty): black nitransforms/
1 parent efc7eec commit cfea21a

23 files changed

+867
-772
lines changed

nitransforms/__init__.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,17 @@
2323
from ._version import __version__
2424
except ModuleNotFoundError:
2525
from pkg_resources import get_distribution, DistributionNotFound
26+
2627
try:
27-
__version__ = get_distribution('nitransforms').version
28+
__version__ = get_distribution("nitransforms").version
2829
except DistributionNotFound:
29-
__version__ = 'unknown'
30+
__version__ = "unknown"
3031
del get_distribution
3132
del DistributionNotFound
3233

3334

3435
__all__ = [
35-
'Affine',
36-
'DisplacementsFieldTransform',
37-
'__version__',
36+
"Affine",
37+
"DisplacementsFieldTransform",
38+
"__version__",
3839
]

nitransforms/base.py

Lines changed: 48 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def factory(dataset):
3939
class SampledSpatialData:
4040
"""Represent sampled spatial data: regularly gridded (images) and surfaces."""
4141

42-
__slots__ = ['_ndim', '_coords', '_npoints', '_shape']
42+
__slots__ = ["_ndim", "_coords", "_npoints", "_shape"]
4343

4444
def __init__(self, dataset):
4545
"""Create a sampling reference."""
@@ -53,19 +53,20 @@ def __init__(self, dataset):
5353
if isinstance(dataset, (str, Path)):
5454
dataset = _nbload(str(dataset))
5555

56-
if hasattr(dataset, 'numDA'): # Looks like a Gifti file
57-
_das = dataset.get_arrays_from_intent(INTENT_CODES['pointset'])
56+
if hasattr(dataset, "numDA"): # Looks like a Gifti file
57+
_das = dataset.get_arrays_from_intent(INTENT_CODES["pointset"])
5858
if not _das:
5959
raise TypeError(
60-
'Input Gifti file does not contain reference coordinates.')
60+
"Input Gifti file does not contain reference coordinates."
61+
)
6162
self._coords = np.vstack([da.data for da in _das])
6263
self._npoints, self._ndim = self._coords.shape
6364
return
6465

6566
if isinstance(dataset, Cifti2Image):
6667
raise NotImplementedError
6768

68-
raise ValueError('Dataset could not be interpreted as an irregular sample.')
69+
raise ValueError("Dataset could not be interpreted as an irregular sample.")
6970

7071
@property
7172
def npoints(self):
@@ -91,7 +92,7 @@ def shape(self):
9192
class ImageGrid(SampledSpatialData):
9293
"""Class to represent spaces of gridded data (images)."""
9394

94-
__slots__ = ['_affine', '_inverse', '_ndindex']
95+
__slots__ = ["_affine", "_inverse", "_ndindex"]
9596

9697
def __init__(self, image):
9798
"""Create a gridded sampling reference."""
@@ -101,17 +102,15 @@ def __init__(self, image):
101102
self._affine = image.affine
102103
self._shape = image.shape
103104

104-
self._ndim = getattr(image, 'ndim', len(image.shape))
105+
self._ndim = getattr(image, "ndim", len(image.shape))
105106
if self._ndim == 4:
106107
self._shape = image.shape[:3]
107108
self._ndim = 3
108109

109-
self._npoints = getattr(image, 'npoints',
110-
np.prod(self._shape))
110+
self._npoints = getattr(image, "npoints", np.prod(self._shape))
111111
self._ndindex = None
112112
self._coords = None
113-
self._inverse = getattr(image, 'inverse',
114-
np.linalg.inv(image.affine))
113+
self._inverse = getattr(image, "inverse", np.linalg.inv(image.affine))
115114

116115
@property
117116
def affine(self):
@@ -128,8 +127,9 @@ def ndindex(self):
128127
"""List the indexes corresponding to the space grid."""
129128
if self._ndindex is None:
130129
indexes = tuple([np.arange(s) for s in self._shape])
131-
self._ndindex = np.array(np.meshgrid(
132-
*indexes, indexing='ij')).reshape(self._ndim, self._npoints)
130+
self._ndindex = np.array(np.meshgrid(*indexes, indexing="ij")).reshape(
131+
self._ndim, self._npoints
132+
)
133133
return self._ndindex
134134

135135
@property
@@ -139,7 +139,7 @@ def ndcoords(self):
139139
self._coords = np.tensordot(
140140
self._affine,
141141
np.vstack((self.ndindex, np.ones((1, self._npoints)))),
142-
axes=1
142+
axes=1,
143143
)[:3, ...]
144144
return self._coords
145145

@@ -152,15 +152,17 @@ def index(self, x):
152152
return _apply_affine(x, self._inverse, self._ndim)
153153

154154
def _to_hdf5(self, group):
155-
group.attrs['Type'] = 'image'
156-
group.attrs['ndim'] = self.ndim
157-
group.create_dataset('affine', data=self.affine)
158-
group.create_dataset('shape', data=self.shape)
155+
group.attrs["Type"] = "image"
156+
group.attrs["ndim"] = self.ndim
157+
group.create_dataset("affine", data=self.affine)
158+
group.create_dataset("shape", data=self.shape)
159159

160160
def __eq__(self, other):
161161
"""Overload equals operator."""
162-
return (np.allclose(self.affine, other.affine, rtol=EQUALITY_TOL)
163-
and self.shape == other.shape)
162+
return (
163+
np.allclose(self.affine, other.affine, rtol=EQUALITY_TOL)
164+
and self.shape == other.shape
165+
)
164166

165167
def __ne__(self, other):
166168
"""Overload not equal operator."""
@@ -170,7 +172,7 @@ def __ne__(self, other):
170172
class TransformBase:
171173
"""Abstract image class to represent transforms."""
172174

173-
__slots__ = ('_reference', )
175+
__slots__ = ("_reference",)
174176

175177
def __init__(self, reference=None):
176178
"""Instantiate a transform."""
@@ -195,13 +197,14 @@ def __add__(self, b):
195197
196198
"""
197199
from .manip import TransformChain
200+
198201
return TransformChain(transforms=[self, b])
199202

200203
@property
201204
def reference(self):
202205
"""Access a reference space where data will be resampled onto."""
203206
if self._reference is None:
204-
warnings.warn('Reference space not set')
207+
warnings.warn("Reference space not set")
205208
return self._reference
206209

207210
@reference.setter
@@ -213,8 +216,16 @@ def ndim(self):
213216
"""Access the dimensions of the reference space."""
214217
return self.reference.ndim
215218

216-
def apply(self, spatialimage, reference=None,
217-
order=3, mode='constant', cval=0.0, prefilter=True, output_dtype=None):
219+
def apply(
220+
self,
221+
spatialimage,
222+
reference=None,
223+
order=3,
224+
mode="constant",
225+
cval=0.0,
226+
prefilter=True,
227+
output_dtype=None,
228+
):
218229
"""
219230
Apply a transformation to an image, resampling on the reference spatial object.
220231
@@ -252,17 +263,18 @@ def apply(self, spatialimage, reference=None,
252263
if reference is not None and isinstance(reference, (str, Path)):
253264
reference = _nbload(str(reference))
254265

255-
_ref = self.reference if reference is None \
256-
else SpatialReference.factory(reference)
266+
_ref = (
267+
self.reference if reference is None else SpatialReference.factory(reference)
268+
)
257269

258270
if isinstance(spatialimage, (str, Path)):
259271
spatialimage = _nbload(str(spatialimage))
260272

261273
data = np.asanyarray(spatialimage.dataobj)
262274
output_dtype = output_dtype or data.dtype
263275
targets = ImageGrid(spatialimage).index( # data should be an image
264-
_as_homogeneous(self.map(_ref.ndcoords.T),
265-
dim=_ref.ndim))
276+
_as_homogeneous(self.map(_ref.ndcoords.T), dim=_ref.ndim)
277+
)
266278

267279
resampled = ndi.map_coordinates(
268280
data,
@@ -276,8 +288,8 @@ def apply(self, spatialimage, reference=None,
276288

277289
if isinstance(_ref, ImageGrid): # If reference is grid, reshape
278290
moved = spatialimage.__class__(
279-
resampled.reshape(_ref.shape),
280-
_ref.affine, spatialimage.header)
291+
resampled.reshape(_ref.shape), _ref.affine, spatialimage.header
292+
)
281293
moved.header.set_data_dtype(output_dtype)
282294
return moved
283295

@@ -304,12 +316,12 @@ def map(self, x, inverse=False):
304316
"""
305317
return x
306318

307-
def to_filename(self, filename, fmt='X5'):
319+
def to_filename(self, filename, fmt="X5"):
308320
"""Store the transform in BIDS-Transforms HDF5 file format (.x5)."""
309-
with h5py.File(filename, 'w') as out_file:
310-
out_file.attrs['Format'] = 'X5'
311-
out_file.attrs['Version'] = np.uint16(1)
312-
root = out_file.create_group('/0')
321+
with h5py.File(filename, "w") as out_file:
322+
out_file.attrs["Format"] = "X5"
323+
out_file.attrs["Version"] = np.uint16(1)
324+
root = out_file.create_group("/0")
313325
self._to_hdf5(root)
314326

315327
return filename
@@ -319,7 +331,7 @@ def _to_hdf5(self, x5_root):
319331
raise NotImplementedError
320332

321333

322-
def _as_homogeneous(xyz, dtype='float32', dim=3):
334+
def _as_homogeneous(xyz, dtype="float32", dim=3):
323335
"""
324336
Convert 2D and 3D coordinates into homogeneous coordinates.
325337

nitransforms/cli.py

Lines changed: 39 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ def cli_apply(pargs):
1818
$ nt apply warp.nii.gz moving.nii.gz --fmt afni --nonlinear
1919
2020
"""
21-
fmt = pargs.fmt or pargs.transform.split('.')[-1]
22-
if fmt in ('tfm', 'mat', 'h5', 'x5'):
23-
fmt = 'itk'
24-
elif fmt == 'lta':
25-
fmt = 'fs'
21+
fmt = pargs.fmt or pargs.transform.split(".")[-1]
22+
if fmt in ("tfm", "mat", "h5", "x5"):
23+
fmt = "itk"
24+
elif fmt == "lta":
25+
fmt = "fs"
2626

27-
if fmt not in ('fs', 'itk', 'fsl', 'afni', 'x5'):
27+
if fmt not in ("fs", "itk", "fsl", "afni", "x5"):
2828
raise ValueError(
2929
"Cannot determine transformation format, manually set format with the `--fmt` flag"
3030
)
@@ -42,28 +42,28 @@ def cli_apply(pargs):
4242
order=pargs.order,
4343
mode=pargs.mode,
4444
cval=pargs.cval,
45-
prefilter=pargs.prefilter
46-
)
47-
moved.to_filename(
48-
pargs.out or "nt_{}".format(os.path.basename(pargs.moving))
45+
prefilter=pargs.prefilter,
4946
)
47+
moved.to_filename(pargs.out or "nt_{}".format(os.path.basename(pargs.moving)))
5048

5149

5250
def get_parser():
53-
desc = dedent("""
51+
desc = dedent(
52+
"""
5453
NiTransforms command-line utility.
5554
5655
Commands:
5756
5857
apply Apply a transformation to an image
5958
6059
For command specific information, use 'nt <command> -h'.
61-
""")
60+
"""
61+
)
6262

6363
parser = ArgumentParser(
6464
description=desc, formatter_class=RawDescriptionHelpFormatter
6565
)
66-
subparsers = parser.add_subparsers(dest='command')
66+
subparsers = parser.add_subparsers(dest="command")
6767

6868
def _add_subparser(name, description):
6969
subp = subparsers.add_parser(
@@ -73,51 +73,51 @@ def _add_subparser(name, description):
7373
)
7474
return subp
7575

76-
applyp = _add_subparser('apply', cli_apply.__doc__)
76+
applyp = _add_subparser("apply", cli_apply.__doc__)
7777
applyp.set_defaults(func=cli_apply)
78-
applyp.add_argument('transform', help='The transform file')
79-
applyp.add_argument(
80-
'moving', help='The image containing the data to be resampled'
81-
)
82-
applyp.add_argument('--ref', help='The reference space to resample onto')
78+
applyp.add_argument("transform", help="The transform file")
79+
applyp.add_argument("moving", help="The image containing the data to be resampled")
80+
applyp.add_argument("--ref", help="The reference space to resample onto")
8381
applyp.add_argument(
84-
'--fmt',
85-
choices=('itk', 'fsl', 'afni', 'fs', 'x5'),
86-
help='Format of transformation. If no option is passed, nitransforms will '
87-
'estimate based on the transformation file extension.'
82+
"--fmt",
83+
choices=("itk", "fsl", "afni", "fs", "x5"),
84+
help="Format of transformation. If no option is passed, nitransforms will "
85+
"estimate based on the transformation file extension.",
8886
)
8987
applyp.add_argument(
90-
'--out', help="The transformed image. If not set, will be set to `nt_{moving}`"
88+
"--out", help="The transformed image. If not set, will be set to `nt_{moving}`"
9189
)
9290
applyp.add_argument(
93-
'--nonlinear', action='store_true', help='Transformation is nonlinear (default: False)'
91+
"--nonlinear",
92+
action="store_true",
93+
help="Transformation is nonlinear (default: False)",
9494
)
95-
applykwargs = applyp.add_argument_group('Apply customization')
95+
applykwargs = applyp.add_argument_group("Apply customization")
9696
applykwargs.add_argument(
97-
'--order',
97+
"--order",
9898
type=int,
9999
default=3,
100100
choices=range(6),
101-
help='The order of the spline transformation (default: 3)'
101+
help="The order of the spline transformation (default: 3)",
102102
)
103103
applykwargs.add_argument(
104-
'--mode',
105-
choices=('constant', 'reflect', 'nearest', 'mirror', 'wrap'),
106-
default='constant',
107-
help='Determines how the input image is extended when the resampling overflows a border '
108-
'(default: constant)'
104+
"--mode",
105+
choices=("constant", "reflect", "nearest", "mirror", "wrap"),
106+
default="constant",
107+
help="Determines how the input image is extended when the resampling overflows a border "
108+
"(default: constant)",
109109
)
110110
applykwargs.add_argument(
111-
'--cval',
111+
"--cval",
112112
type=float,
113113
default=0.0,
114-
help='Constant used when using "constant" mode (default: 0.0)'
114+
help='Constant used when using "constant" mode (default: 0.0)',
115115
)
116116
applykwargs.add_argument(
117-
'--prefilter',
118-
action='store_false',
117+
"--prefilter",
118+
action="store_false",
119119
help="Determines if the image's data array is prefiltered with a spline filter before "
120-
"interpolation (default: True)"
120+
"interpolation (default: True)",
121121
)
122122
return parser, subparsers
123123

@@ -131,4 +131,4 @@ def main(pargs=None):
131131
except Exception as e:
132132
subparser = subparsers.choices[pargs.command]
133133
subparser.print_help()
134-
raise(e)
134+
raise (e)

0 commit comments

Comments
 (0)