Skip to content

Commit 5f1c1c4

Browse files
committed
sty: pacify flake8, add docstrings
1 parent 4c2ebda commit 5f1c1c4

File tree

1 file changed

+32
-12
lines changed

1 file changed

+32
-12
lines changed

nitransforms/io/itk.py

Lines changed: 32 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,28 @@
44

55

66
class ITKLinearTransform(StringBasedStruct):
7+
"""A string-based structure for ITK linear transforms."""
8+
79
template_dtype = np.dtype([
810
('type', 'i4'),
9-
('id', 'i4'),
11+
('index', 'i4'),
1012
('parameters', 'f4', (4, 4)),
1113
('offset', 'f4', 3), # Center of rotation
1214
])
1315
dtype = template_dtype
1416

1517
def __init__(self):
18+
"""Initialize with default offset and index."""
1619
super().__init__()
1720
self.structarr['offset'] = [0, 0, 0]
18-
self.structarr['id'] = 1
21+
self.structarr['index'] = 1
22+
self.structarr['parameters'] = np.eye(4)
1923

20-
def to_string(self, banner=True):
24+
def __str__(self):
25+
"""Generate a string representation."""
2126
sa = self.structarr
2227
lines = [
23-
'#Transform {:d}'.format(sa['id']),
28+
'#Transform {:d}'.format(sa['index']),
2429
'Transform: MatrixOffsetTransformBase_double_3_3',
2530
'Parameters: {}'.format(' '.join(
2631
['%g' % p
@@ -29,12 +34,22 @@ def to_string(self, banner=True):
2934
'FixedParameters: {:g} {:g} {:g}'.format(*sa['offset']),
3035
'',
3136
]
32-
if banner:
33-
lines.insert(0, '#Insight Transform File V1.0')
3437
return '\n'.join(lines)
3538

39+
def to_string(self, banner=None):
40+
"""Convert to a string directly writeable to file."""
41+
string = '%s'
42+
43+
if banner is None:
44+
banner = self.structarr['index'] == 1
45+
46+
if banner:
47+
string = '#Insight Transform File V1.0\n%s'
48+
return string % self
49+
3650
@classmethod
3751
def from_string(klass, string):
52+
"""Read the struct from string."""
3853
tf = klass()
3954
sa = tf.structarr
4055
lines = [l for l in string.splitlines()
@@ -44,7 +59,7 @@ def from_string(klass, string):
4459
lines = lines[1:] # Drop banner with version
4560

4661
parameters = np.eye(4, dtype='f4')
47-
sa['id'] = int(lines[0][lines[0].index('T'):].split()[1])
62+
sa['index'] = int(lines[0][lines[0].index('T'):].split()[1])
4863
sa['offset'] = np.genfromtxt([lines[3].split(':')[-1].encode()],
4964
dtype=klass.dtype['offset'])
5065
vals = np.genfromtxt([lines[2].split(':')[-1].encode()],
@@ -56,10 +71,13 @@ def from_string(klass, string):
5671

5772
@classmethod
5873
def from_fileobj(klass, fileobj, check=True):
74+
"""Read the struct from a file object."""
5975
return klass.from_string(fileobj.read())
6076

6177

6278
class ITKLinearTransformArray(StringBasedStruct):
79+
"""A string-based structure for series of ITK linear transforms."""
80+
6381
template_dtype = np.dtype([('nxforms', 'i4')])
6482
dtype = template_dtype
6583
_xforms = None
@@ -69,6 +87,7 @@ def __init__(self,
6987
binaryblock=None,
7088
endianness=None,
7189
check=True):
90+
"""Initialize with (optionally) a list of transforms."""
7291
super().__init__(binaryblock, endianness, check)
7392
self._xforms = []
7493
for mat in xforms or []:
@@ -77,25 +96,25 @@ def __init__(self,
7796
self._xforms.append(xfm)
7897

7998
def __getitem__(self, idx):
99+
"""Allow dictionary access to the transforms."""
80100
if idx == 'xforms':
81101
return self._xforms
82102
if idx == 'nxforms':
83103
return len(self._xforms)
84104
return super().__getitem__(idx)
85105

86106
def to_string(self):
107+
"""Convert to a string directly writeable to file."""
87108
strings = []
88109
for i, xfm in enumerate(self._xforms):
89-
xfm.structarr['id'] = i + 1
90-
strings.append(xfm.to_string(banner=False))
91-
strings.insert(0, '#Insight Transform File V1.0')
110+
xfm.structarr['index'] = i + 1
111+
strings.append(xfm.to_string())
92112
return '\n'.join(strings)
93113

94114
@classmethod
95115
def from_string(klass, string):
116+
"""Read the struct from string."""
96117
_self = klass()
97-
sa = _self.structarr
98-
99118
lines = [l.strip() for l in string.splitlines()
100119
if l.strip()]
101120

@@ -110,4 +129,5 @@ def from_string(klass, string):
110129

111130
@classmethod
112131
def from_fileobj(klass, fileobj, check=True):
132+
"""Read the struct from a file object."""
113133
return klass.from_string(fileobj.read())

0 commit comments

Comments
 (0)