Skip to content

Commit 755e8d1

Browse files
committed
fix: inefficient iterative reloading of reference and moving images
The list comprehension had ``nb.loads`` and other method calls continously happening when converting the affine array into RAS.
1 parent 1674e86 commit 755e8d1

File tree

1 file changed

+29
-10
lines changed

1 file changed

+29
-10
lines changed

nitransforms/io/afni.py

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -108,17 +108,24 @@ def from_string(cls, string):
108108
sa["parameters"] = parameters
109109
return tf
110110

111-
def to_ras(self, moving=None, reference=None):
111+
def to_ras(self, moving=None, reference=None, pre_rotation=None, post_rotation=None):
112112
"""Return a nitransforms internal RAS+ matrix."""
113113
# swapaxes is necessary, as axis 0 encodes series of transforms
114114
retval = LPS @ np.swapaxes(self.structarr["parameters"].T, 0, 1) @ LPS
115-
reference = _ensure_image(reference)
116-
if reference is not None and _is_oblique(reference.affine):
117-
retval = retval @ _cardinal_rotation(reference.affine, True)
118115

119-
moving = _ensure_image(moving)
120-
if moving is not None and _is_oblique(moving.affine):
121-
retval = _cardinal_rotation(moving.affine, False) @ retval
116+
if pre_rotation is None and reference is not None:
117+
ref_aff = _ensure_image(reference).affine
118+
pre_rotation = _cardinal_rotation(ref_aff, True) if _is_oblique(ref_aff) else None
119+
120+
if pre_rotation is not None:
121+
retval = retval @ pre_rotation
122+
123+
if post_rotation is None and reference is not None:
124+
mov_aff = _ensure_image(moving).affine
125+
post_rotation = _cardinal_rotation(mov_aff, True) if _is_oblique(mov_aff) else None
126+
127+
if post_rotation is not None:
128+
retval = post_rotation @ retval
122129

123130
return retval
124131

@@ -130,9 +137,21 @@ class AFNILinearTransformArray(BaseLinearTransformList):
130137

131138
def to_ras(self, moving=None, reference=None):
132139
"""Return a nitransforms' internal RAS matrix."""
133-
return np.stack(
134-
[xfm.to_ras(moving=moving, reference=reference) for xfm in self.xforms]
135-
)
140+
141+
pre_rotation = None
142+
if reference is not None:
143+
ref_aff = _ensure_image(reference).affine
144+
pre_rotation = _cardinal_rotation(ref_aff, True) if _is_oblique(ref_aff) else None
145+
146+
post_rotation = None
147+
if moving is not None:
148+
mov_aff = _ensure_image(moving).affine
149+
post_rotation = _cardinal_rotation(mov_aff, True) if _is_oblique(mov_aff) else None
150+
151+
return np.stack([
152+
xfm.to_ras(pre_rotation=pre_rotation, post_rotation=post_rotation)
153+
for xfm in self.xforms
154+
])
136155

137156
def to_string(self):
138157
"""Convert to a string directly writeable to file."""

0 commit comments

Comments
 (0)