Skip to content

Commit

Permalink
Merge remote-tracking branch 'jmarabotto/patch/oesteban-pr' into enh/…
Browse files Browse the repository at this point in the history
…reenable-parallelization-apply-214
  • Loading branch information
oesteban committed Jul 29, 2024
2 parents 86b3d11 + 6292daf commit 23daabb
Showing 1 changed file with 70 additions and 31 deletions.
101 changes: 70 additions & 31 deletions nitransforms/resampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
from pathlib import Path
import numpy as np
from nibabel.loadsave import load as _nbload
from nibabel.arrayproxy import get_obj_dtype
from scipy import ndimage as ndi

from nitransforms.linear import Affine, LinearTransformsMapping
from nitransforms.base import (
ImageGrid,
TransformError,
Expand All @@ -23,9 +25,6 @@
SERIALIZE_VOLUME_WINDOW_WIDTH : int = 8
"""Minimum number of volumes to automatically serialize 4D transforms."""

class NotImplementedWarning(UserWarning):
"""A custom class for warnings."""


def apply(
transform,
Expand Down Expand Up @@ -99,49 +98,89 @@ def apply(

data = np.asanyarray(spatialimage.dataobj)
data_nvols = 1 if data.ndim < 4 else data.shape[-1]

xfm_nvols = len(transform)

if data_nvols == 1 and xfm_nvols > 1:
data = data[..., np.newaxis]
elif data_nvols != xfm_nvols:
raise ValueError(
"The fourth dimension of the data does not match the tranform's shape."
"The fourth dimension of the data does not match the transform's shape."
)

serialize_nvols = serialize_nvols if serialize_nvols and serialize_nvols > 1 else np.inf
serialize_4d = max(data_nvols, xfm_nvols) > serialize_nvols
serialize_4d = max(data_nvols, xfm_nvols) >= serialize_nvols

if serialize_4d:
warn(
"4D transforms serialization into 3D+t not implemented",
NotImplementedWarning,
stacklevel=2,
# Avoid opening the data array just yet
input_dtype = get_obj_dtype(spatialimage.dataobj)
output_dtype = output_dtype or input_dtype

# Prepare physical coordinates of input (grid, points)
xcoords = _ref.ndcoords.astype("f4").T

# Invert target's (moving) affine once
ras2vox = ~Affine(spatialimage.affine)
dataobj = (
np.asanyarray(spatialimage.dataobj, dtype=input_dtype)
if spatialimage.ndim in (2, 3)
else None
)

# For model-based nonlinear transforms, generate the corresponding dense field
if hasattr(transform, "to_field") and callable(transform.to_field):
targets = ImageGrid(spatialimage).index(
_as_homogeneous(
transform.to_field(reference=reference).map(_ref.ndcoords.T),
dim=_ref.ndim,
)
# Order F ensures individual volumes are contiguous in memory
# Also matches NIfTI, making final save more efficient
resampled = np.zeros(
(xcoords.shape[0], len(transform)), dtype=output_dtype, order="F"
)

for t, xfm_t in enumerate(transform):
# Map the input coordinates on to timepoint t of the target (moving)
ycoords = xfm_t.map(xcoords)[..., : _ref.ndim]

# Calculate corresponding voxel coordinates
yvoxels = ras2vox.map(ycoords)[..., : _ref.ndim]

# Interpolate
resampled[..., t] = ndi.map_coordinates(
(
dataobj
if dataobj is not None
else spatialimage.dataobj[..., t].astype(input_dtype, copy=False)
),
yvoxels.T,
output=output_dtype,
order=order,
mode=mode,
cval=cval,
prefilter=prefilter,
)

else:
targets = ImageGrid(spatialimage).index( # data should be an image
_as_homogeneous(transform.map(_ref.ndcoords.T), dim=_ref.ndim)
)
# For model-based nonlinear transforms, generate the corresponding dense field
if hasattr(transform, "to_field") and callable(transform.to_field):
targets = ImageGrid(spatialimage).index(
_as_homogeneous(
transform.to_field(reference=reference).map(_ref.ndcoords.T),
dim=_ref.ndim,
)
)
else:
targets = ImageGrid(spatialimage).index( # data should be an image
_as_homogeneous(transform.map(_ref.ndcoords.T), dim=_ref.ndim)
)

if transform.ndim == 4:
targets = _as_homogeneous(targets.reshape(-2, targets.shape[0])).T

resampled = ndi.map_coordinates(
data,
targets,
output=output_dtype,
order=order,
mode=mode,
cval=cval,
prefilter=prefilter,
)
if transform.ndim == 4:
targets = _as_homogeneous(targets.reshape(-2, targets.shape[0])).T

resampled = ndi.map_coordinates(
data,
targets,
output=output_dtype,
order=order,
mode=mode,
cval=cval,
prefilter=prefilter,
)

if isinstance(_ref, ImageGrid): # If reference is grid, reshape
hdr = None
Expand Down

0 comments on commit 23daabb

Please sign in to comment.