Skip to content

Commit e4cc7ed

Browse files
committed
enh: minimize memory fingerprint after optimization
1 parent 984e4ed commit e4cc7ed

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

sdcflows/interfaces/bspline.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ def bspline_grid(img, control_zooms_mm=DEFAULT_ZOOMS_MM):
404404

405405
def grid_bspline_weights(target_nii, ctrl_nii):
406406
"""Fast, gridded evaluation."""
407-
from scipy.sparse import csr_matrix
407+
from scipy.sparse import csr_matrix, vstack
408408

409409
if isinstance(target_nii, (str, bytes, Path)):
410410
target_nii = nb.load(target_nii)
@@ -426,7 +426,7 @@ def grid_bspline_weights(target_nii, ctrl_nii):
426426
"float32"
427427
)
428428
weights = np.zeros_like(distance, dtype="float32")
429-
within_support = np.abs(distance) < BSPLINE_SUPPORT
429+
within_support = np.abs(distance) < 2.0
430430
d = np.abs(distance[within_support])
431431
weights[within_support] = np.piecewise(
432432
d,
@@ -438,14 +438,22 @@ def grid_bspline_weights(target_nii, ctrl_nii):
438438
)
439439
wd.append(weights)
440440

441-
wmat = csr_matrix(
442-
(
443-
wd[0][:, np.newaxis, np.newaxis, :, np.newaxis, np.newaxis]
441+
ctrl_shape = ctrl_nii.shape[:3]
442+
data_size = np.prod(shape)
443+
wmat = None
444+
for i in range(ctrl_shape[0]):
445+
sparse_mat = (
446+
wd[0][i, np.newaxis, np.newaxis, :, np.newaxis, np.newaxis]
444447
* wd[1][np.newaxis, :, np.newaxis, np.newaxis, :, np.newaxis]
445448
* wd[2][np.newaxis, np.newaxis, :, np.newaxis, np.newaxis, :]
446-
).reshape((np.prod(ctrl_nii.shape[:3]), np.prod(shape))),
447-
dtype="float32",
448-
)
449+
).reshape((-1, data_size))
450+
sparse_mat[sparse_mat < 1e-9] = 0
451+
452+
if wmat is None:
453+
wmat = csr_matrix(sparse_mat)
454+
else:
455+
wmat = vstack((wmat, csr_matrix(sparse_mat)))
456+
449457
return wmat
450458

451459

0 commit comments

Comments
 (0)