U Phc@s0ddlmZddlmZddlZddlmZddlZddlm Z ddl m Z m Z m Z mZmZmZed\ZZddd d d gZGd d d ejjZd!dddddddZGdddejjZd"dddddd ZGdddejjZd#ddddd ZGdddejjZd$dddddd ZGd ddejZdS)%) annotations)SequenceN)to_norm_affine)GridSampleModeGridSamplePadModeconvert_to_dst_type ensure_tuplelook_up_optionoptional_importzmonai._CAffineTransform grid_pull grid_push grid_count grid_gradc@s$eZdZeddZeddZdS) _GridPullcCs>|||f}tj||f|}|js(|jr:||_||||SN)_Cr requires_gradoptsave_for_backwardctxinputgrid interpolationbound extrapolateroutputr]/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/networks/layers/spatial_transforms.pyforward%s    z_GridPull.forwardcCs|jds|jdsdS|j}|j}tj|f||}|jdrd|d|jdrX|dnddddfS|jdrd|ddddfSdSNrNNNNN)needs_input_grad saved_tensorsrrZgrid_pull_backwardrgradvarrgradsrrrbackward/s $ z_GridPull.backwardN__name__ __module__ __qualname__ staticmethodr r*rrrrr#s rlinearzeroT torch.Tensorbool)rrrreturncCsXddt|D}ddt|D}t|||||}t|tjjrTt||dd}|S)a Sample an image with respect to a deformation field. `interpolation` can be an int, a string or an InterpolationType. Possible values are:: - 0 or 'nearest' or InterpolationType.nearest - 1 or 'linear' or InterpolationType.linear - 2 or 'quadratic' or InterpolationType.quadratic - 3 or 'cubic' or InterpolationType.cubic - 4 or 'fourth' or InterpolationType.fourth - 5 or 'fifth' or InterpolationType.fifth - 6 or 'sixth' or InterpolationType.sixth - 7 or 'seventh' or InterpolationType.seventh A list of values can be provided, in the order [W, H, D], to specify dimension-specific interpolation orders. `bound` can be an int, a string or a BoundType. Possible values are:: - 0 or 'replicate' or 'nearest' or BoundType.replicate or 'border' - 1 or 'dct1' or 'mirror' or BoundType.dct1 - 2 or 'dct2' or 'reflect' or BoundType.dct2 - 3 or 'dst1' or 'antimirror' or BoundType.dst1 - 4 or 'dst2' or 'antireflect' or BoundType.dst2 - 5 or 'dft' or 'wrap' or BoundType.dft - 7 or 'zero' or 'zeros' or BoundType.zero A list of values can be provided, in the order [W, H, D], to specify dimension-specific boundary conditions. `sliding` is a specific condition than only applies to flow fields (with as many channels as dimensions). It cannot be dimension-specific. Note that: - `dft` corresponds to circular padding - `dct2` corresponds to Neumann boundary conditions (symmetric) - `dst2` corresponds to Dirichlet boundary conditions (antisymmetric) See Also: - https://en.wikipedia.org/wiki/Discrete_cosine_transform - https://en.wikipedia.org/wiki/Discrete_sine_transform - ``help(monai._C.BoundType)`` - ``help(monai._C.InterpolationType)`` Args: input: Input image. `(B, C, Wi, Hi, Di)`. grid: Deformation field. `(B, Wo, Ho, Do, 1|2|3)`. interpolation (int or list[int] , optional): Interpolation order. Defaults to `'linear'`. bound (BoundType, or list[BoundType], optional): Boundary conditions. Defaults to `'zero'`. extrapolate: Extrapolate out-of-bound data. Defaults to `True`. Returns: output (torch.Tensor): Deformed image `(B, C, Wo, Ho, Do)`. cSs,g|]$}t|trtjj|nt|qSr isinstancestrrZ BoundType __members__.0brrr {szgrid_pull..cSs,g|]$}t|trtjj|nt|qSrr6r7rZInterpolationTyper8r:irrrr<|sdstr)rrapplyr6monaidata MetaTensorrrrrrroutrrrr <s?c@s$eZdZeddZeddZdS) _GridPushc Cs@|||f}tj|||f|}|js*|jr<||_||||Sr)rr rrr) rrrshaperrrrrrrrr s    z_GridPush.forwardcCs|jds|jdsdS|j}|j}tj|f||}|jdrf|d|jdrX|dndddddfS|jdrd|dddddfSdS)Nrr")NNNNNN)r$r%rrZgrid_push_backwardr&rrrr*s & z_GridPush.backwardNr+rrrrrHs rH)rrrcCstddt|D}ddt|D}|dkr>t|jdd}t||||||}t|tjjrpt ||dd}|S)a Splat an image with respect to a deformation field (pull adjoint). `interpolation` can be an int, a string or an InterpolationType. Possible values are:: - 0 or 'nearest' or InterpolationType.nearest - 1 or 'linear' or InterpolationType.linear - 2 or 'quadratic' or InterpolationType.quadratic - 3 or 'cubic' or InterpolationType.cubic - 4 or 'fourth' or InterpolationType.fourth - 5 or 'fifth' or InterpolationType.fifth - 6 or 'sixth' or InterpolationType.sixth - 7 or 'seventh' or InterpolationType.seventh A list of values can be provided, in the order `[W, H, D]`, to specify dimension-specific interpolation orders. `bound` can be an int, a string or a BoundType. Possible values are:: - 0 or 'replicate' or 'nearest' or BoundType.replicate - 1 or 'dct1' or 'mirror' or BoundType.dct1 - 2 or 'dct2' or 'reflect' or BoundType.dct2 - 3 or 'dst1' or 'antimirror' or BoundType.dst1 - 4 or 'dst2' or 'antireflect' or BoundType.dst2 - 5 or 'dft' or 'wrap' or BoundType.dft - 7 or 'zero' or BoundType.zero A list of values can be provided, in the order `[W, H, D]`, to specify dimension-specific boundary conditions. `sliding` is a specific condition than only applies to flow fields (with as many channels as dimensions). It cannot be dimension-specific. Note that: - `dft` corresponds to circular padding - `dct2` corresponds to Neumann boundary conditions (symmetric) - `dst2` corresponds to Dirichlet boundary conditions (antisymmetric) See Also: - https://en.wikipedia.org/wiki/Discrete_cosine_transform - https://en.wikipedia.org/wiki/Discrete_sine_transform - ``help(monai._C.BoundType)`` - ``help(monai._C.InterpolationType)`` Args: input: Input image `(B, C, Wi, Hi, Di)`. grid: Deformation field `(B, Wi, Hi, Di, 1|2|3)`. shape: Shape of the source image. interpolation (int or list[int] , optional): Interpolation order. Defaults to `'linear'`. bound (BoundType, or list[BoundType], optional): Boundary conditions. Defaults to `'zero'`. extrapolate: Extrapolate out-of-bound data. Defaults to `True`. Returns: output (torch.Tensor): Splatted image `(B, C, Wo, Ho, Do)`. cSs,g|]$}t|trtjj|nt|qSrr5r9rrrr<szgrid_push..cSs,g|]$}t|trtjj|nt|qSrr=r>rrrr<sNr@r) rtuplerIrHrBr6rCrDrEr)rrrIrrrrGrrrr sAc@s$eZdZeddZeddZdS) _GridCountcCs6|||f}tj||f|}|jr2||_|||Sr)rrrrr)rrrIrrrrrrrrr s   z_GridCount.forwardcCs6|jdr2|j}|j}tj|f||ddddfSdS)Nrr#)r$r%rrZgrid_count_backward)rr'r(rrrrr*s  z_GridCount.backwardNr+rrrrrLs rL)rrcCsrddt|D}ddt|D}|dkr>t|jdd}t|||||}tttjj rnt |tdd}|S)a Splatting weights with respect to a deformation field (pull adjoint). This function is equivalent to applying grid_push to an image of ones. `interpolation` can be an int, a string or an InterpolationType. Possible values are:: - 0 or 'nearest' or InterpolationType.nearest - 1 or 'linear' or InterpolationType.linear - 2 or 'quadratic' or InterpolationType.quadratic - 3 or 'cubic' or InterpolationType.cubic - 4 or 'fourth' or InterpolationType.fourth - 5 or 'fifth' or InterpolationType.fifth - 6 or 'sixth' or InterpolationType.sixth - 7 or 'seventh' or InterpolationType.seventh A list of values can be provided, in the order [W, H, D], to specify dimension-specific interpolation orders. `bound` can be an int, a string or a BoundType. Possible values are:: - 0 or 'replicate' or 'nearest' or BoundType.replicate - 1 or 'dct1' or 'mirror' or BoundType.dct1 - 2 or 'dct2' or 'reflect' or BoundType.dct2 - 3 or 'dst1' or 'antimirror' or BoundType.dst1 - 4 or 'dst2' or 'antireflect' or BoundType.dst2 - 5 or 'dft' or 'wrap' or BoundType.dft - 7 or 'zero' or BoundType.zero A list of values can be provided, in the order [W, H, D], to specify dimension-specific boundary conditions. `sliding` is a specific condition than only applies to flow fields (with as many channels as dimensions). It cannot be dimension-specific. Note that: - `dft` corresponds to circular padding - `dct2` corresponds to Neumann boundary conditions (symmetric) - `dst2` corresponds to Dirichlet boundary conditions (antisymmetric) See Also: - https://en.wikipedia.org/wiki/Discrete_cosine_transform - https://en.wikipedia.org/wiki/Discrete_sine_transform - ``help(monai._C.BoundType)`` - ``help(monai._C.InterpolationType)`` Args: grid: Deformation field `(B, Wi, Hi, Di, 2|3)`. shape: shape of the source image. interpolation (int or list[int] , optional): Interpolation order. Defaults to `'linear'`. bound (BoundType, or list[BoundType], optional): Boundary conditions. Defaults to `'zero'`. extrapolate (bool, optional): Extrapolate out-of-bound data. Defaults to `True`. Returns: output (torch.Tensor): Splat weights `(B, 1, Wo, Ho, Do)`. cSs,g|]$}t|trtjj|nt|qSrr5r9rrrr<Eszgrid_count..cSs,g|]$}t|trtjj|nt|qSrr=r>rrrr<FsNrJr@r) rrKrIrLrBr6rrCrDrEr)rrIrrrrGrrrrs@c@s$eZdZeddZeddZdS) _GridGradcCs>|||f}tj||f|}|js(|jr:||_||||Sr)rrrrrrrrrr Vs    z_GridGrad.forwardcCs|jds|jdsdS|j}|j}tj|f||}|jdrd|d|jdrX|dnddddfS|jdrd|ddddfSdSr!)r$r%rrZgrid_grad_backwardr&rrrr*`s $ z_GridGrad.backwardNr+rrrrrMTs rMcCsXddt|D}ddt|D}t|||||}t|tjjrTt||dd}|S)a Sample an image with respect to a deformation field. `interpolation` can be an int, a string or an InterpolationType. Possible values are:: - 0 or 'nearest' or InterpolationType.nearest - 1 or 'linear' or InterpolationType.linear - 2 or 'quadratic' or InterpolationType.quadratic - 3 or 'cubic' or InterpolationType.cubic - 4 or 'fourth' or InterpolationType.fourth - 5 or 'fifth' or InterpolationType.fifth - 6 or 'sixth' or InterpolationType.sixth - 7 or 'seventh' or InterpolationType.seventh A list of values can be provided, in the order [W, H, D], to specify dimension-specific interpolation orders. `bound` can be an int, a string or a BoundType. Possible values are:: - 0 or 'replicate' or 'nearest' or BoundType.replicate - 1 or 'dct1' or 'mirror' or BoundType.dct1 - 2 or 'dct2' or 'reflect' or BoundType.dct2 - 3 or 'dst1' or 'antimirror' or BoundType.dst1 - 4 or 'dst2' or 'antireflect' or BoundType.dst2 - 5 or 'dft' or 'wrap' or BoundType.dft - 7 or 'zero' or BoundType.zero A list of values can be provided, in the order [W, H, D], to specify dimension-specific boundary conditions. `sliding` is a specific condition than only applies to flow fields (with as many channels as dimensions). It cannot be dimension-specific. Note that: - `dft` corresponds to circular padding - `dct2` corresponds to Neumann boundary conditions (symmetric) - `dst2` corresponds to Dirichlet boundary conditions (antisymmetric) See Also: - https://en.wikipedia.org/wiki/Discrete_cosine_transform - https://en.wikipedia.org/wiki/Discrete_sine_transform - ``help(monai._C.BoundType)`` - ``help(monai._C.InterpolationType)`` Args: input: Input image. `(B, C, Wi, Hi, Di)`. grid: Deformation field. `(B, Wo, Ho, Do, 2|3)`. interpolation (int or list[int] , optional): Interpolation order. Defaults to `'linear'`. bound (BoundType, or list[BoundType], optional): Boundary conditions. Defaults to `'zero'`. extrapolate: Extrapolate out-of-bound data. Defaults to `True`. Returns: output (torch.Tensor): Sampled gradients (B, C, Wo, Ho, Do, 1|2|3). cSs,g|]$}t|trtjj|nt|qSrr5r9rrrr<szgrid_grad..cSs,g|]$}t|trtjj|nt|qSrr=r>rrrr<sr@r)rrMrBr6rCrDrErrFrrrrms>c sZeZdZddejejdddfddddddddd fd d Zdd d dd d ddZZ S)r NFTzSequence[int] | int | Noner3r7z bool | NoneNone) spatial_size normalizedmode padding_mode align_cornersreverse_indexing zero_centeredr4csvt|dk rt|nd|_||_t|t|_t|t|_ ||_ ||_ |dk r`|jr`t d|dk rl|nd|_ dS)a Apply affine transformations with a batch of affine matrices. When `normalized=False` and `reverse_indexing=True`, it does the commonly used resampling in the 'pull' direction following the ``scipy.ndimage.affine_transform`` convention. In this case `theta` is equivalent to (ndim+1, ndim+1) input ``matrix`` of ``scipy.ndimage.affine_transform``, operates on homogeneous coordinates. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.affine_transform.html When `normalized=True` and `reverse_indexing=False`, it applies `theta` to the normalized coordinates (coords. in the range of [-1, 1]) directly. This is often used with `align_corners=False` to achieve resolution-agnostic resampling, thus useful as a part of trainable modules such as the spatial transformer networks. See also: https://pytorch.org/tutorials/intermediate/spatial_transformer_tutorial.html Args: spatial_size: output spatial shape, the full output shape will be `[N, C, *spatial_size]` where N and C are inferred from the `src` input of `self.forward`. normalized: indicating whether the provided affine matrix `theta` is defined for the normalized coordinates. If `normalized=False`, `theta` will be converted to operate on normalized coordinates as pytorch affine_grid works with the normalized coordinates. mode: {``"bilinear"``, ``"nearest"``} Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"zeros"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html align_corners: see also https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html. reverse_indexing: whether to reverse the spatial indexing of image and coordinates. set to `False` if `theta` follows pytorch's default "D, H, W" convention. set to `True` if `theta` follows `scipy.ndimage` default "i, j, k" convention. zero_centered: whether the affine is applied to coordinates in a zero-centered value range. With `zero_centered=True`, for example, the center of rotation will be the spatial center of the input; with `zero_centered=False`, the center of rotation will be the origin of the input. This option is only available when `normalized=False`, where the default behaviour is `False` if unspecified. See also: :py:func:`monai.networks.utils.normalize_transform`. NzD`normalized=True` is not compatible with the `zero_centered` option.F)super__init__rrOrPr rrQrrRrSrT ValueErrorrU)selfrOrPrQrRrSrTrU __class__rrrWs2   zAffineTransform.__init__r2)srcthetarOr4c Cst|tjs"tdt|jd|dkr@td|jd|dkrT|d}| }t |jdd}|dkrt |d dkrd d dgn d d d dg}| |jd dd |}d |_tj||gdd }t |jddd krtd |jdt|std|jt|tjs8tdt|jd|d}|dkr^td|dt |j}|}|jdk r|dd|j}|dk r|ddt|}|jst||dd|ddd |jd}|jrDtjt|ddd|jd} |dd| f|ddd|f<|dddd| f|ddddd|f<|jd dkrt|d dkrt| |d dd}|jd |d krtd|jd d|d dtjj|ddd|ft||jd} tjj |!| |j"|j#|jd} | S)a  ``theta`` must be an affine transformation matrix with shape 3x3 or Nx3x3 or Nx2x3 or 2x3 for spatial 2D transforms, 4x4 or Nx4x4 or Nx3x4 or 3x4 for spatial 3D transforms, where `N` is the batch size. `theta` will be converted into float Tensor for the computation. Args: src (array_like): image in spatial 2D or 3D (N, C, spatial_dims), where N is the batch dim, C is the number of channels. theta (array_like): Nx3x3, Nx2x3, 3x3, 2x3 for spatial 2D inputs, Nx4x4, Nx3x4, 3x4, 4x4 for spatial 3D inputs. When the batch dimension is omitted, `theta` will be repeated N times, N is the batch dim of `src`. spatial_size: output spatial shape, the full output shape will be `[N, C, *spatial_size]` where N and C are inferred from the `src`. Raises: TypeError: When ``theta`` is not a ``torch.Tensor``. ValueError: When ``theta`` is not one of [Nxdxd, dxd]. ValueError: When ``theta`` is not one of [Nx3x3, Nx4x4]. TypeError: When ``src`` is not a ``torch.Tensor``. ValueError: When ``src`` spatially is not one of [2D, 3D]. ValueError: When affine and image batch dimension differ. z"theta must be torch.Tensor but is .rJz theta must be Nxdxd or dxd, got rJNr")r_)r`rF)dim))r`r`)raraz"theta must be Nx3x3 or Nx4x4, got z'theta must be floating point data, got z src must be torch.Tensor but is zUnsupported src dimension: z, available options are [2, 3].)affinesrc_sizedst_sizerSrU)devicez8affine and image batch dimension must match, got affine=z image=)r]sizerS)rrrQrRrS)$r6torchTensor TypeErrortyper,rbrXrIclonerKtensorrepeattorcatis_floating_pointdtyperOrrPrrUrT as_tensorrangergnn functional affine_gridlistrS grid_sample contiguousrQrR) rYr\r]rOZ theta_shapeZ pad_affinesrrdrerev_idxrrArrrr sn   (         ,(zAffineTransform.forward)N) r,r-r.rBILINEARrZEROSrWr __classcell__rrrZrr s">)r0r1T)Nr0r1T)Nr0r1T)r0r1T) __future__rcollections.abcrritorch.nnrvrCZmonai.networksr monai.utilsrrrrr r r___all__autogradFunctionrr rHr rLrrMrModuler rrrr s0     KPOJ