Skip to content

Motion

Bases: IntensityTransform

Simulate MRI motion artifacts.

Motion during MR acquisition corrupts different segments of k-space with different rigid-body transforms, producing characteristic ringing and blurring. This implementation follows Shaw et al., 2019.

The simulation:

  1. Splits k-space into num_transforms + 1 segments along a random axis.
  2. For each segment, applies a random rigid-body transform to the image and fills the corresponding k-space lines from the transformed image.
  3. Reconstructs the corrupted image via inverse FFT.

Parameters:

Name Type Description Default
degrees float | tuple[float, float]

Rotation range in degrees. A scalar \(d\) means \(\theta_i \sim \mathcal{U}(-d, d)\). A 2-tuple \((a, b)\) means \(\theta_i \sim \mathcal{U}(a, b)\).

10.0
translation float | tuple[float, float]

Translation range in voxels, same convention as degrees. The translation is applied in normalized grid coordinates (a voxel-space approximation), not in millimeters.

10.0
num_transforms int

Number of inter-segment motion events. More transforms produce more distortion.

2
**kwargs Any

See Transform.

{}
Warning

Large numbers of transforms increase execution time significantly for 3D volumes.

Examples:

>>> import torchio as tio
>>> transform = tio.Motion()
>>> transform = tio.Motion(degrees=15, translation=10, num_transforms=4)
Source code in src/torchio/transforms/intensity/motion.py
class Motion(IntensityTransform):
    r"""Simulate MRI motion artifacts.

    Motion during MR acquisition corrupts different segments of
    k-space with different rigid-body transforms, producing
    characteristic ringing and blurring.  This implementation follows
    [Shaw et al., 2019](http://proceedings.mlr.press/v102/shaw19a.html).

    The simulation:

    1. Splits k-space into *num_transforms* + 1 segments along a
       random axis.
    2. For each segment, applies a random rigid-body transform to
       the image and fills the corresponding k-space lines from the
       transformed image.
    3. Reconstructs the corrupted image via inverse FFT.

    Args:
        degrees: Rotation range in degrees.  A scalar $d$ means
            $\theta_i \sim \mathcal{U}(-d, d)$.  A 2-tuple $(a, b)$
            means $\theta_i \sim \mathcal{U}(a, b)$.
        translation: Translation range in voxels, same convention as
            *degrees*. The translation is applied in normalized grid
            coordinates (a voxel-space approximation), not in millimeters.
        num_transforms: Number of inter-segment motion events.
            More transforms produce more distortion.
        **kwargs: See [`Transform`][torchio.Transform].

    Warning:
        Large numbers of transforms increase execution time
        significantly for 3D volumes.

    Examples:
        >>> import torchio as tio
        >>> transform = tio.Motion()
        >>> transform = tio.Motion(degrees=15, translation=10, num_transforms=4)
    """

    def __init__(
        self,
        *,
        degrees: float | tuple[float, float] = 10.0,
        translation: float | tuple[float, float] = 10.0,
        num_transforms: int = 2,
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)
        self.degrees = to_range(degrees)
        self.translation = to_range(translation)
        if not isinstance(num_transforms, int) or num_transforms < 1:
            msg = f"num_transforms must be a positive int, got {num_transforms}"
            raise ValueError(msg)
        self.num_transforms = num_transforms

    def make_params(self, batch: SubjectsBatch) -> dict[str, Any]:
        """Sample motion parameters (per element when batched)."""
        n = self._resolve_n(batch)
        if n is None:
            transforms = self._sample_transforms()
            return {"transforms": transforms}
        keep = self._keep_mask(batch, n)
        transforms_list: list[Any] = []
        for index in range(n):
            if keep is not None and not keep[index]:
                transforms_list.append([])
                continue
            transforms_list.append(self._sample_transforms())
        params = {"transforms": transforms_list}
        self._tag_batched(params, batch, n, keep, ["transforms"])
        return params

    def _sample_transforms(self) -> MotionTransforms:
        """Sample one list of rigid sub-transforms."""
        return [
            {
                "degrees": self.degrees.sample(),
                "translation": self.translation.sample(),
            }
            for _ in range(self.num_transforms)
        ]

    @property
    def supports_per_instance_params(self) -> bool:
        return True

    @property
    def supports_per_instance_p(self) -> bool:
        return True

    def apply_transform(
        self,
        batch: SubjectsBatch,
        params: dict[str, Any],
    ) -> SubjectsBatch:
        """Corrupt each selected image with simulated motion."""
        per_instance = self._is_per_instance_params(params)
        for _name, img_batch in self._get_images(batch).items():
            if per_instance:
                img_batch.data = _apply_motion_per_instance(
                    img_batch.data,
                    params["transforms"],
                )
            else:
                img_batch.data = _apply_motion(
                    img_batch.data,
                    params["transforms"],
                )
        return batch

invertible property

Whether this transform can be inverted.

forward(data)

forward(data: Subject) -> Subject
forward(data: Image) -> Image
forward(data: Tensor) -> Tensor
forward(data: np.ndarray) -> np.ndarray
forward(data: sitk.Image) -> sitk.Image
forward(data: nib.Nifti1Image) -> nib.Nifti1Image
forward(data: dict) -> dict
forward(data: ImagesBatch) -> ImagesBatch
forward(data: SubjectsBatch) -> SubjectsBatch

Apply the transform.

The output type always matches the input type.

Parameters:

Name Type Description Default
data Any

Input data to transform.

required
Source code in src/torchio/transforms/transform.py
def forward(self, data: Any) -> Any:
    """Apply the transform.

    The output type always matches the input type.

    Args:
        data: Input data to transform.
    """
    if self.copy:
        data = _copy.deepcopy(data)
    batch, unwrap = self._wrap(data)
    # When per-element gating is active, the transform handles the
    # probability itself (masked-out elements get identity params),
    # so skip the batch-wide coin flip here. Apply iff rand < p, so
    # p=0 is always a no-op and p=1 always applies.
    if not self._per_instance_p_active(batch) and torch.rand(1).item() >= self.p:
        return unwrap(batch)
    params = self.make_params(batch)
    batch = self.apply_transform(batch, params)
    # Record history on the batch, unless every element was gated out by
    # per-element probability: that is an exact no-op, and recording it
    # would let history replay (e.g. an invertible spatial transform)
    # trigger an unnecessary identity resample.
    if not _all_elements_gated_out(params):
        trace = AppliedTransform(name=type(self).__name__, params=params)
        if not hasattr(batch, "applied_transforms"):
            batch.applied_transforms = []
        batch.applied_transforms.append(trace)
    result = unwrap(batch)
    # Propagate history to outputs that can carry it
    if (
        hasattr(batch, "applied_transforms")
        and not isinstance(result, (SubjectsBatch, Tensor, np.ndarray))
        and not isinstance(result, dict)
    ):
        with contextlib.suppress(AttributeError):
            result.applied_transforms = list(batch.applied_transforms)
    return result

inverse(params)

Return a transform that undoes this one.

Override in invertible subclasses. The returned transform, when applied, reverses the effect of the forward pass with the given parameters.

Parameters:

Name Type Description Default
params dict[str, Any]

The parameters recorded in the forward pass.

required

Returns:

Type Description
Transform

A new Transform instance that inverts this one.

Source code in src/torchio/transforms/transform.py
def inverse(self, params: dict[str, Any]) -> Transform:
    """Return a transform that undoes this one.

    Override in invertible subclasses. The returned transform,
    when applied, reverses the effect of the forward pass with
    the given parameters.

    Args:
        params: The parameters recorded in the forward pass.

    Returns:
        A new `Transform` instance that inverts this one.
    """
    msg = f"{type(self).__name__} is not invertible"
    raise NotImplementedError(msg)

to_hydra()

Export as a Hydra-compatible config dict.

Returns a dict with _target_ set to the fully qualified class name and only non-default field values included.

Returns:

Type Description
dict[str, Any]

Dict suitable for hydra.utils.instantiate().

Source code in src/torchio/transforms/transform.py
def to_hydra(self) -> dict[str, Any]:
    """Export as a Hydra-compatible config dict.

    Returns a dict with `_target_` set to the fully qualified
    class name and only non-default field values included.

    Returns:
        Dict suitable for `hydra.utils.instantiate()`.
    """
    from .parameter_range import _ParameterRange

    cls = type(self)
    target = f"torchio.{cls.__qualname__}"
    cfg: dict[str, Any] = {"_target_": target}

    for name, default in _collect_init_params(cls).items():
        value = getattr(self, name, default)
        if isinstance(value, _ParameterRange):
            if value._original == default:
                continue
            value = _hydra_value(value._original)
        elif value == default:
            continue
        else:
            value = _hydra_value(value)
        cfg[name] = value
    return cfg

make_params(batch)

Sample motion parameters (per element when batched).

Source code in src/torchio/transforms/intensity/motion.py
def make_params(self, batch: SubjectsBatch) -> dict[str, Any]:
    """Sample motion parameters (per element when batched)."""
    n = self._resolve_n(batch)
    if n is None:
        transforms = self._sample_transforms()
        return {"transforms": transforms}
    keep = self._keep_mask(batch, n)
    transforms_list: list[Any] = []
    for index in range(n):
        if keep is not None and not keep[index]:
            transforms_list.append([])
            continue
        transforms_list.append(self._sample_transforms())
    params = {"transforms": transforms_list}
    self._tag_batched(params, batch, n, keep, ["transforms"])
    return params

apply_transform(batch, params)

Corrupt each selected image with simulated motion.

Source code in src/torchio/transforms/intensity/motion.py
def apply_transform(
    self,
    batch: SubjectsBatch,
    params: dict[str, Any],
) -> SubjectsBatch:
    """Corrupt each selected image with simulated motion."""
    per_instance = self._is_per_instance_params(params)
    for _name, img_batch in self._get_images(batch).items():
        if per_instance:
            img_batch.data = _apply_motion_per_instance(
                img_batch.data,
                params["transforms"],
            )
        else:
            img_batch.data = _apply_motion(
                img_batch.data,
                params["transforms"],
            )
    return batch