Skip to content

Spatial

Bases: SpatialTransform

Apply resampling, affine motion, and elastic deformation together.

This transform can:

  1. resample to a new space,
  2. apply a global affine mapping, and
  3. apply a dense elastic field,

using a single sampling grid.

The convenience wrappers Resample, Affine, and ElasticDeformation expose subsets of these parameters with sensible defaults.

Parameters:

Name Type Description Default
target TypeTarget

Output space. Can be one of:

  • A scalar or 3-tuple of floats: output voxel spacing in mm. E.g., 1 for 1 mm isotropic, (0.5, 0.5, 2.0) for anisotropic.
  • A random spacing spec, sampled once per call at apply time: a 2-tuple (lo, hi) (uniform, per axis), a 6-tuple (lo1, hi1, lo2, hi2, lo3, hi3) (per-axis ranges), a Choice, or a torch.distributions.Distribution. E.g., target=(1, 2) or target=(2, 4, 2, 4, 3, 6).
  • A str: either a path to an image file, or the name of an image in the subject (e.g., "t1").
  • An Image instance.
  • A (spatial_shape, affine) pair.
  • None (default): the output grid matches the input grid.
None
scales TypeParameterValue

Scale factors \((s_1, s_2, s_3)\) for each axis. If a single value \(x\) is given, all axes use \(x\). If two values \((a, b)\) are given, \(s_i \sim \mathcal{U}(a, b)\). If six values \((a_1, b_1, a_2, b_2, a_3, b_3)\) are given, \(s_i \sim \mathcal{U}(a_i, b_i)\) independently. A torch.distributions.Distribution may also be passed. For example, scales=0.5 halves the apparent object size (zoom out), and scales=2 doubles it (zoom in).

1.0
degrees TypeParameterValue

Euler rotation angles \((\theta_1, \theta_2, \theta_3)\) in degrees, following the same value/range/distribution convention as scales.

0.0
translation TypeParameterValue

Translation \((t_1, t_2, t_3)\) in mm, following the same convention. The direction depends on the image orientation: in RAS+, translation=(10, 0, 0) shifts 10 mm to the right.

0.0
isotropic bool

If True, sample a single scale factor and reuse it for all three axes. scales must then be a scalar or 2-value range.

False
center TypeCenter

Pivot point for rotation and scaling. "image" (default) uses the image center; "origin" uses the world-coordinate origin.

'image'
control_points TypeControlPoints | None

Optional pre-computed coarse displacement field with shape (n_i, n_j, n_k, 3) in mm. If given, num_control_points, max_displacement, and locked_borders are ignored.

None
num_control_points int | TypeThreeInts

Number of control points along each dimension of the coarse grid. Can be a single int (isotropic) or a 3-tuple. Minimum is 4. Smaller values produce smoother deformations.

7
max_displacement TypeParameterValue

Maximum displacement at each control point, in mm. Follows the same value/range/distribution convention as scales. Zero (default) disables elastic deformation.

0.0
locked_borders int

Number of outer control-point layers whose displacement is forced to zero. 0 keeps all displacements; 1 zeros the outermost layer; 2 (default) zeros the two outermost layers.

2
affine_first bool

If True (default), apply the affine mapping before the elastic field. If False, apply the elastic field first. The difference is significant for large transforms.

True
image_interpolation TypeInterpolation

"linear" (default) or "nearest". Used for ScalarImage instances.

'linear'
label_interpolation TypeInterpolation

"nearest" (default) or "linear". Used for LabelMap instances.

'nearest'
antialias bool

If True, apply Gaussian smoothing before downsampling intensity images. Label maps are never smoothed. The standard deviations follow Cardoso et al., MICCAI 2015.

False
default_pad_value TypePadValue | float

Fill rule for out-of-bounds intensity voxels. "minimum" (default), "mean", "otsu", or a numeric value.

'minimum'
default_pad_label int | float

Numeric fill value for out-of-bounds label voxels.

0
**kwargs Any

See Transform.

{}
Note

The randomizable parameters (scales, degrees, translation, max_displacement, and the spacing form of target) follow a common value/range/distribution convention: a scalar is deterministic, a 2-tuple \((a, b)\) samples uniformly, a 3-tuple sets per-axis values, a 6-tuple sets per-axis ranges, and a Choice or torch.distributions.Distribution samples from a discrete set or a distribution. Structural parameters (center, interpolation, padding) are not randomizable.

Examples:

>>> import torchio as tio
>>> # Resample to 1 mm isotropic with a random rotation
>>> transform = tio.Spatial(
...     target=1,
...     degrees=(-10, 10),
...     translation=(-5, 5),
... )
>>> # Elastic deformation only
>>> transform = tio.Spatial(
...     max_displacement=7.5,
...     num_control_points=7,
... )
>>> transformed = transform(subject)
Source code in src/torchio/transforms/spatial/spatial.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
class Spatial(SpatialTransform):
    r"""Apply resampling, affine motion, and elastic deformation together.

    This transform can:

    1. resample to a new space,
    2. apply a global affine mapping, and
    3. apply a dense elastic field,

    using a single sampling grid.

    The convenience wrappers [`Resample`][torchio.Resample],
    [`Affine`][torchio.Affine], and
    [`ElasticDeformation`][torchio.ElasticDeformation] expose subsets
    of these parameters with sensible defaults.

    Args:
        target: Output space.  Can be one of:

            - A scalar or 3-tuple of floats: output voxel spacing in mm.
              E.g., `1` for 1 mm isotropic, `(0.5, 0.5, 2.0)` for
              anisotropic.
            - A random spacing spec, sampled once per call at apply time: a
              2-tuple `(lo, hi)` (uniform, per axis), a 6-tuple
              `(lo1, hi1, lo2, hi2, lo3, hi3)` (per-axis ranges), a `Choice`,
              or a `torch.distributions.Distribution`. E.g.,
              `target=(1, 2)` or `target=(2, 4, 2, 4, 3, 6)`.
            - A `str`: either a path to an image file, or the name of
              an image in the subject (e.g., `"t1"`).
            - An [`Image`][torchio.Image] instance.
            - A `(spatial_shape, affine)` pair.
            - `None` (default): the output grid matches the input grid.
        scales: Scale factors $(s_1, s_2, s_3)$ for each axis.
            If a single value $x$ is given, all axes use $x$.
            If two values $(a, b)$ are given,
            $s_i \sim \mathcal{U}(a, b)$.
            If six values $(a_1, b_1, a_2, b_2, a_3, b_3)$ are given,
            $s_i \sim \mathcal{U}(a_i, b_i)$ independently.
            A `torch.distributions.Distribution` may also be passed.
            For example, `scales=0.5` halves the apparent object
            size (zoom out), and `scales=2` doubles it (zoom in).
        degrees: Euler rotation angles $(\theta_1, \theta_2, \theta_3)$
            in degrees, following the same value/range/distribution
            convention as *scales*.
        translation: Translation $(t_1, t_2, t_3)$ in mm, following
            the same convention.  The direction depends on the image
            orientation: in RAS+, `translation=(10, 0, 0)` shifts
            10 mm to the right.
        isotropic: If `True`, sample a single scale factor and
            reuse it for all three axes.  *scales* must then be a
            scalar or 2-value range.
        center: Pivot point for rotation and scaling.
            `"image"` (default) uses the image center;
            `"origin"` uses the world-coordinate origin.
        control_points: Optional pre-computed coarse displacement
            field with shape `(n_i, n_j, n_k, 3)` in mm.  If given,
            *num_control_points*, *max_displacement*, and
            *locked_borders* are ignored.
        num_control_points: Number of control points along each
            dimension of the coarse grid.  Can be a single `int`
            (isotropic) or a 3-tuple.  Minimum is 4.  Smaller values
            produce smoother deformations.
        max_displacement: Maximum displacement at each control point,
            in mm.  Follows the same value/range/distribution
            convention as *scales*.  Zero (default) disables elastic
            deformation.
        locked_borders: Number of outer control-point layers whose
            displacement is forced to zero.  `0` keeps all
            displacements; `1` zeros the outermost layer; `2`
            (default) zeros the two outermost layers.
        affine_first: If `True` (default), apply the affine mapping
            before the elastic field.  If `False`, apply the elastic
            field first.  The difference is significant for large
            transforms.
        image_interpolation: `"linear"` (default) or `"nearest"`.
            Used for [`ScalarImage`][torchio.ScalarImage] instances.
        label_interpolation: `"nearest"` (default) or `"linear"`.
            Used for [`LabelMap`][torchio.LabelMap] instances.
        antialias: If `True`, apply Gaussian smoothing before
            downsampling intensity images.  Label maps are never
            smoothed.  The standard deviations follow
            [Cardoso et al., MICCAI 2015](https://link.springer.com/chapter/10.1007/978-3-319-24571-3_81).
        default_pad_value: Fill rule for out-of-bounds intensity
            voxels.  `"minimum"` (default), `"mean"`, `"otsu"`,
            or a numeric value.
        default_pad_label: Numeric fill value for out-of-bounds label
            voxels.
        **kwargs: See [`Transform`][torchio.Transform].

    Note:
        The randomizable parameters (`scales`, `degrees`, `translation`,
        `max_displacement`, and the spacing form of `target`) follow a common
        value/range/distribution convention: a scalar is deterministic, a
        2-tuple $(a, b)$ samples uniformly, a 3-tuple sets per-axis values, a
        6-tuple sets per-axis ranges, and a `Choice` or
        `torch.distributions.Distribution` samples from a discrete set or a
        distribution. Structural parameters (`center`, interpolation, padding)
        are not randomizable.

    Examples:
        >>> import torchio as tio
        >>> # Resample to 1 mm isotropic with a random rotation
        >>> transform = tio.Spatial(
        ...     target=1,
        ...     degrees=(-10, 10),
        ...     translation=(-5, 5),
        ... )
        >>> # Elastic deformation only
        >>> transform = tio.Spatial(
        ...     max_displacement=7.5,
        ...     num_control_points=7,
        ... )
        >>> transformed = transform(subject)
    """

    def __init__(
        self,
        *,
        target: TypeTarget = None,
        scales: TypeParameterValue = 1.0,
        degrees: TypeParameterValue = 0.0,
        translation: TypeParameterValue = 0.0,
        isotropic: bool = False,
        center: TypeCenter = "image",
        control_points: TypeControlPoints | None = None,
        num_control_points: int | TypeThreeInts = 7,
        max_displacement: TypeParameterValue = 0.0,
        locked_borders: int = 2,
        affine_first: bool = True,
        image_interpolation: TypeInterpolation = "linear",
        label_interpolation: TypeInterpolation = "nearest",
        antialias: bool = False,
        default_pad_value: TypePadValue | float = "minimum",
        default_pad_label: int | float = 0,
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)
        self.target = target
        _validate_isotropic(scales, isotropic)
        self.scales = _to_positive_range(scales)
        self.degrees = _to_parameter_range(degrees)
        self.translation = _to_parameter_range(translation)
        self.isotropic = isotropic
        self.center = _parse_center(center)
        self.control_points = (
            _parse_control_points(control_points)
            if control_points is not None
            else None
        )
        self.num_control_points = _parse_num_control_points(num_control_points)
        self.max_displacement = _to_nonnegative_parameter_range(max_displacement)
        self.locked_borders = _parse_locked_borders(locked_borders)
        if self.locked_borders == 2 and 4 in self.num_control_points:
            msg = (
                "locked_borders=2 with 4 control points along any axis yields an"
                " identity elastic field"
            )
            raise ValueError(msg)
        self.affine_first = affine_first
        self.image_interpolation = _parse_interpolation(image_interpolation)
        self.label_interpolation = _parse_interpolation(label_interpolation)
        self.antialias = antialias
        self.default_pad_value = _parse_default_pad_value(default_pad_value)
        if not isinstance(default_pad_label, Number):
            msg = f"default_pad_label must be numeric, got {type(default_pad_label)}"
            raise TypeError(msg)
        self.default_pad_label = float(default_pad_label)

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

    @property
    def supports_per_instance_p(self) -> bool:
        # Per-element gating requires a shape-preserving transform so the
        # gated-out element is a true no-op. A resampling target changes
        # the grid, so keep batch-wide gating in that case.
        return self.target is None

    def _sample_one(
        self,
        shape: TypeThreeInts,
        affine: AffineMatrix,
    ) -> tuple[
        np.ndarray | None,
        Tensor | None,
        tuple[float, float, float] | None,
        bool,
    ]:
        """Sample one set of affine and elastic parameters.

        Args:
            shape: Spatial shape used to build the affine and to suppress
                out-of-plane components for 2D inputs.
            affine: Affine of the reference image.

        Returns:
            A tuple `(forward_affine, control_points, max_displacement,
            has_geometry)` where `has_geometry` is `True` when either an
            affine or an elastic component is present.
        """
        sampled_scales = _sample_scales(self.scales, self.isotropic)
        sampled_degrees = self.degrees.sample()
        sampled_translation = self.translation.sample()
        has_affine = _has_affine_component(
            sampled_scales,
            sampled_degrees,
            sampled_translation,
        )
        control_points, max_displacement = _resolve_control_points(
            self.control_points,
            self.num_control_points,
            self.max_displacement,
            self.locked_borders,
        )
        has_elastic = control_points is not None
        forward_affine = None
        if has_affine:
            forward_affine = _build_forward_affine(
                scales=sampled_scales,
                degrees=sampled_degrees,
                translation=sampled_translation,
                center=self.center,
                shape=shape,
                affine=affine,
            )
        return (
            forward_affine,
            control_points,
            max_displacement,
            (has_affine or has_elastic),
        )

    def make_params(self, batch: SubjectsBatch) -> dict[str, Any]:
        """Sample random parameters and resolve the output space.

        Scales, degrees, translation, and control-point displacements are
        sampled per batch element when per-instance augmentation is
        active (the default for batches), and once otherwise.

        Returns:
            Dict of serializable parameters for `apply_transform` and
            history replay.
        """
        images = self._get_images(batch)
        if not images:
            return {"selected_images": []}

        _, first_batch = next(iter(images.items()))
        first_shape = _get_spatial_shape(first_batch)
        first_affine = first_batch.affines[0]

        params: dict[str, Any] = {
            "selected_images": list(images.keys()),
            "original": _serialize_space((first_shape, first_affine)),
            "affine_first": self.affine_first,
            "image_interpolation": self.image_interpolation,
            "label_interpolation": self.label_interpolation,
            "antialias": self.antialias,
            "default_pad_value": self.default_pad_value,
            "default_pad_label": self.default_pad_label,
        }

        n = self._resolve_n(batch)
        if n is None:
            forward_affine, control_points, max_displacement, has_geometry = (
                self._sample_one(first_shape, first_affine)
            )
            if has_geometry:
                _check_shared_space(images, first_shape, first_affine)
            # Resolve the (possibly random) target after sampling the
            # geometry so the RNG stream matches the batch-shared path.
            target_space = _resolve_target_space(
                self.target,
                batch,
                first_shape,
                first_affine,
            )
            params["target"] = _serialize_space(target_space)
            params["affine_matrix"] = _serialize_matrix(forward_affine)
            params["control_points"] = _serialize_control_points(control_points)
            params["max_displacement"] = (
                list(max_displacement) if max_displacement else None
            )
            return params

        keep = self._keep_mask(batch, n)
        affine_list, control_points_list, displacement_list, any_geometry = (
            self._sample_per_element_geometry(n, first_shape, first_affine, keep)
        )
        if any_geometry:
            _check_shared_space(images, first_shape, first_affine)
        target_space = _resolve_target_space(
            self.target,
            batch,
            first_shape,
            first_affine,
        )
        params["target"] = _serialize_space(target_space)
        params["affine_matrix"] = affine_list
        params["control_points"] = control_points_list
        params["max_displacement"] = displacement_list
        self._tag_batched(
            params,
            batch,
            n,
            keep,
            ["affine_matrix", "control_points", "max_displacement"],
        )
        return params

    def _sample_per_element_geometry(
        self,
        n: int,
        first_shape: TypeThreeInts,
        first_affine: AffineMatrix,
        keep: Tensor | None,
    ) -> tuple[list[Any], list[Any], list[Any], bool]:
        """Sample serializable geometry for each batch element.

        Gated-out elements (``keep[index]`` is false) contribute ``None``
        placeholders so the per-element lists stay aligned with the batch.

        Args:
            n: Number of batch elements.
            first_shape: Spatial shape of the first image.
            first_affine: Affine of the first image.
            keep: Per-element keep mask, or ``None`` to keep all elements.

        Returns:
            The affine, control-point and max-displacement lists plus a
            flag indicating whether any element produced a geometry
            transform.
        """
        affine_list: list[Any] = []
        control_points_list: list[Any] = []
        displacement_list: list[Any] = []
        any_geometry = False
        for index in range(n):
            kept = keep is None or bool(keep[index])
            if not kept:
                affine_list.append(None)
                control_points_list.append(None)
                displacement_list.append(None)
                continue
            forward_affine, control_points, max_displacement, has_geometry = (
                self._sample_one(first_shape, first_affine)
            )
            any_geometry = any_geometry or has_geometry
            affine_list.append(_serialize_matrix(forward_affine))
            control_points_list.append(_serialize_control_points(control_points))
            displacement_list.append(
                list(max_displacement) if max_displacement else None
            )
        return affine_list, control_points_list, displacement_list, any_geometry

    def apply_transform(
        self,
        batch: SubjectsBatch,
        params: dict[str, Any],
    ) -> SubjectsBatch:
        """Apply the spatial mapping to every selected image in *batch*.

        One sampling grid is built per batch element when per-instance
        parameters are present, and a single shared grid otherwise.
        """
        selected_images = params.get("selected_images", [])
        if not selected_images:
            return batch

        target_space = _deserialize_space(params["target"])

        affine_matrix, control_points, max_displacement, per_sample = (
            _resolve_spatial_params(params)
        )
        is_noop = (
            target_space is None
            and affine_matrix is None
            and control_points is None
            and max_displacement is None
            and per_sample is None
        )
        if is_noop:
            # A true no-op (no resampling and no geometry, e.g. every
            # element gated out) must leave the data and the per-sample
            # affines untouched instead of rebuilding an identity grid.
            return batch
        _apply_spatial_to_batch(
            batch=batch,
            image_names=selected_images,
            target_space=target_space,
            affine_matrix=affine_matrix,
            control_points=control_points,
            max_displacement=max_displacement,
            affine_first=params["affine_first"],
            image_interpolation=params["image_interpolation"],
            label_interpolation=params["label_interpolation"],
            antialias=params.get("antialias", False),
            default_pad_value=params["default_pad_value"],
            default_pad_label=float(params["default_pad_label"]),
            per_sample=per_sample,
        )
        return batch

    @property
    def invertible(self) -> bool:
        """Whether this transform can be inverted."""
        return True

    def inverse(self, params: dict[str, Any]) -> _SpatialInverse:
        """Build the inverse transform from recorded parameters.

        The affine component is inverted exactly.  The elastic component
        is approximated by negating the sampled displacement field.  The
        `affine_first` flag is flipped so that the inverse operations
        run in the opposite order. Per-instance parameters are inverted
        element by element.

        Args:
            params: The parameter dict produced by `make_params`.

        Returns:
            A `_SpatialInverse` that resamples back to the original grid.
        """
        original_space = _deserialize_space(params["original"])
        if original_space is None:
            msg = "Spatial inverse needs the original output space"
            raise RuntimeError(msg)

        common: dict[str, Any] = {
            "target": original_space,
            "affine_first": not params["affine_first"],
            "image_interpolation": params["image_interpolation"],
            "label_interpolation": params["label_interpolation"],
            "default_pad_value": params["default_pad_value"],
            "default_pad_label": float(params["default_pad_label"]),
            "copy": False,
            # Invert only the images the forward pass actually transformed,
            # so excluded images (e.g. label maps) are not resampled.
            "include": params["selected_images"],
        }

        batched_keys = params.get("_batched_keys") or []
        if "affine_matrix" in batched_keys:
            per_sample = _invert_per_sample(params)
            return _SpatialInverse(
                affine_matrix=None,
                control_points=None,
                per_sample=per_sample,
                **common,
            )

        affine_matrix = _deserialize_matrix(params["affine_matrix"])
        inverse_affine = None
        if affine_matrix is not None:
            inverse_affine = np.linalg.inv(affine_matrix)
        control_points = _deserialize_control_points(params["control_points"])
        inverse_control_points = None
        if control_points is not None:
            inverse_control_points = -control_points
        return _SpatialInverse(
            affine_matrix=inverse_affine,
            control_points=inverse_control_points,
            **common,
        )

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

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 random parameters and resolve the output space.

Scales, degrees, translation, and control-point displacements are sampled per batch element when per-instance augmentation is active (the default for batches), and once otherwise.

Returns:

Type Description
dict[str, Any]

Dict of serializable parameters for apply_transform and

dict[str, Any]

history replay.

Source code in src/torchio/transforms/spatial/spatial.py
def make_params(self, batch: SubjectsBatch) -> dict[str, Any]:
    """Sample random parameters and resolve the output space.

    Scales, degrees, translation, and control-point displacements are
    sampled per batch element when per-instance augmentation is
    active (the default for batches), and once otherwise.

    Returns:
        Dict of serializable parameters for `apply_transform` and
        history replay.
    """
    images = self._get_images(batch)
    if not images:
        return {"selected_images": []}

    _, first_batch = next(iter(images.items()))
    first_shape = _get_spatial_shape(first_batch)
    first_affine = first_batch.affines[0]

    params: dict[str, Any] = {
        "selected_images": list(images.keys()),
        "original": _serialize_space((first_shape, first_affine)),
        "affine_first": self.affine_first,
        "image_interpolation": self.image_interpolation,
        "label_interpolation": self.label_interpolation,
        "antialias": self.antialias,
        "default_pad_value": self.default_pad_value,
        "default_pad_label": self.default_pad_label,
    }

    n = self._resolve_n(batch)
    if n is None:
        forward_affine, control_points, max_displacement, has_geometry = (
            self._sample_one(first_shape, first_affine)
        )
        if has_geometry:
            _check_shared_space(images, first_shape, first_affine)
        # Resolve the (possibly random) target after sampling the
        # geometry so the RNG stream matches the batch-shared path.
        target_space = _resolve_target_space(
            self.target,
            batch,
            first_shape,
            first_affine,
        )
        params["target"] = _serialize_space(target_space)
        params["affine_matrix"] = _serialize_matrix(forward_affine)
        params["control_points"] = _serialize_control_points(control_points)
        params["max_displacement"] = (
            list(max_displacement) if max_displacement else None
        )
        return params

    keep = self._keep_mask(batch, n)
    affine_list, control_points_list, displacement_list, any_geometry = (
        self._sample_per_element_geometry(n, first_shape, first_affine, keep)
    )
    if any_geometry:
        _check_shared_space(images, first_shape, first_affine)
    target_space = _resolve_target_space(
        self.target,
        batch,
        first_shape,
        first_affine,
    )
    params["target"] = _serialize_space(target_space)
    params["affine_matrix"] = affine_list
    params["control_points"] = control_points_list
    params["max_displacement"] = displacement_list
    self._tag_batched(
        params,
        batch,
        n,
        keep,
        ["affine_matrix", "control_points", "max_displacement"],
    )
    return params

apply_transform(batch, params)

Apply the spatial mapping to every selected image in batch.

One sampling grid is built per batch element when per-instance parameters are present, and a single shared grid otherwise.

Source code in src/torchio/transforms/spatial/spatial.py
def apply_transform(
    self,
    batch: SubjectsBatch,
    params: dict[str, Any],
) -> SubjectsBatch:
    """Apply the spatial mapping to every selected image in *batch*.

    One sampling grid is built per batch element when per-instance
    parameters are present, and a single shared grid otherwise.
    """
    selected_images = params.get("selected_images", [])
    if not selected_images:
        return batch

    target_space = _deserialize_space(params["target"])

    affine_matrix, control_points, max_displacement, per_sample = (
        _resolve_spatial_params(params)
    )
    is_noop = (
        target_space is None
        and affine_matrix is None
        and control_points is None
        and max_displacement is None
        and per_sample is None
    )
    if is_noop:
        # A true no-op (no resampling and no geometry, e.g. every
        # element gated out) must leave the data and the per-sample
        # affines untouched instead of rebuilding an identity grid.
        return batch
    _apply_spatial_to_batch(
        batch=batch,
        image_names=selected_images,
        target_space=target_space,
        affine_matrix=affine_matrix,
        control_points=control_points,
        max_displacement=max_displacement,
        affine_first=params["affine_first"],
        image_interpolation=params["image_interpolation"],
        label_interpolation=params["label_interpolation"],
        antialias=params.get("antialias", False),
        default_pad_value=params["default_pad_value"],
        default_pad_label=float(params["default_pad_label"]),
        per_sample=per_sample,
    )
    return batch

inverse(params)

Build the inverse transform from recorded parameters.

The affine component is inverted exactly. The elastic component is approximated by negating the sampled displacement field. The affine_first flag is flipped so that the inverse operations run in the opposite order. Per-instance parameters are inverted element by element.

Parameters:

Name Type Description Default
params dict[str, Any]

The parameter dict produced by make_params.

required

Returns:

Type Description
_SpatialInverse

A _SpatialInverse that resamples back to the original grid.

Source code in src/torchio/transforms/spatial/spatial.py
def inverse(self, params: dict[str, Any]) -> _SpatialInverse:
    """Build the inverse transform from recorded parameters.

    The affine component is inverted exactly.  The elastic component
    is approximated by negating the sampled displacement field.  The
    `affine_first` flag is flipped so that the inverse operations
    run in the opposite order. Per-instance parameters are inverted
    element by element.

    Args:
        params: The parameter dict produced by `make_params`.

    Returns:
        A `_SpatialInverse` that resamples back to the original grid.
    """
    original_space = _deserialize_space(params["original"])
    if original_space is None:
        msg = "Spatial inverse needs the original output space"
        raise RuntimeError(msg)

    common: dict[str, Any] = {
        "target": original_space,
        "affine_first": not params["affine_first"],
        "image_interpolation": params["image_interpolation"],
        "label_interpolation": params["label_interpolation"],
        "default_pad_value": params["default_pad_value"],
        "default_pad_label": float(params["default_pad_label"]),
        "copy": False,
        # Invert only the images the forward pass actually transformed,
        # so excluded images (e.g. label maps) are not resampled.
        "include": params["selected_images"],
    }

    batched_keys = params.get("_batched_keys") or []
    if "affine_matrix" in batched_keys:
        per_sample = _invert_per_sample(params)
        return _SpatialInverse(
            affine_matrix=None,
            control_points=None,
            per_sample=per_sample,
            **common,
        )

    affine_matrix = _deserialize_matrix(params["affine_matrix"])
    inverse_affine = None
    if affine_matrix is not None:
        inverse_affine = np.linalg.inv(affine_matrix)
    control_points = _deserialize_control_points(params["control_points"])
    inverse_control_points = None
    if control_points is not None:
        inverse_control_points = -control_points
    return _SpatialInverse(
        affine_matrix=inverse_affine,
        control_points=inverse_control_points,
        **common,
    )