U ˆPÓhXãF@s°dZddlmZddlZddlmZmZmZddlm Z m Z ddl Z ddl Z ddlmZmZmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4ddl5m6Z6ddl7m8Z8m9Z9m:Z:ddl;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEddlFmGZGddlHmIZIeIdƒ\ZJZKdddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZgFZLGd[d„de9ee8ƒZMGd\d„de9ee8ƒZNGd]d„de9ee8ƒZOGd^d„de9ee8ƒZPGd_d„de9ee8ƒZQGd`d„de:e9ee8ƒZRGdad„de9ee8ƒZSGdbd„de9ee8ƒZTGdcd„de:e9ee8ƒZUGddd„de:e9ƒZVGded„de:e9ƒZWGdfd „d e9ee8ƒZXGdgd!„d!e:e9ee8ƒZYGdhd$„d$e:e9ee8ƒZZGdid%„d%e9ee8ƒZ[Gdjd&„d&e:e9ee8ƒZ\Gdkd'„d'e9ee8ƒZ]Gdld(„d(e:e9ee8ƒZ^Gdmd"„d"e9ƒZ_Gdnd#„d#e:e9ƒZ`GdodO„dOe9e6ƒZaGdpdR„dRe9e6ƒZbGdqdU„dUe:e9e6ƒZcGdrdX„dXe:e9ƒZdeMZeZfeNZgZheOZiZjePZkZleQZmZneRZoZpeSZqZreTZsZteUZuZveVZwZxeWZyZzeXZ{Z|eYZ}Z~e_ZZ€e`ZZ‚eZZƒZ„e[Z…Z†e\Z‡Zˆe]Z‰ZŠe^Z‹ZŒeaZZŽebZZecZ‘Z’edZ“Z”dS)szà A collection of dictionary-based wrappers around the "vanilla" transforms for spatial operations defined in :py:class:`monai.transforms.spatial.array`. Class names are ended with 'd' to denote dictionary-based transforms. é)Ú annotationsN)ÚHashableÚMappingÚSequence)ÚAnyÚcast)Ú DtypeLikeÚKeysCollectionÚ SequenceStr)ÚNdarrayOrTensor)Úget_track_meta)Ú MetaTensor)ÚGaussianFilter)ÚCenterSpatialCrop)ÚInvertibleTransform)ÚAffineÚFlipÚGridDistortionÚ GridPatchÚ GridSplitÚ OrientationÚ Rand2DElasticÚ Rand3DElasticÚ RandAffineÚ RandAxisFlipÚRandGridDistortionÚ RandGridPatchÚ RandRotateÚRandSimulateLowResolutionÚRandZoomÚResampleToMatchÚResizeÚRotateÚRotate90ÚSpacingÚSpatialResampleÚZoom)ÚMultiSampleTrait)Ú LazyTransformÚ MapTransformÚRandomizableTransform)Ú create_grid)ÚGridSampleModeÚGridSamplePadModeÚInterpolateModeÚ NumpyPadModeÚconvert_to_tensorÚ ensure_tupleÚensure_tuple_repÚfall_back_tuple)Ú TraceKeys)Úoptional_importÚnibabelÚSpatialResampledÚResampleToMatchdÚSpacingdÚ OrientationdÚ Rotate90dÚ RandRotate90dÚResizedÚAffinedÚ RandAffinedÚRand2DElasticdÚRand3DElasticdÚFlipdÚ RandFlipdÚGridDistortiondÚRandGridDistortiondÚ RandAxisFlipdÚRotatedÚ RandRotatedÚZoomdÚ RandZoomdÚSpatialResampleDÚSpatialResampleDictÚSpacingDÚ SpacingDictÚ OrientationDÚOrientationDictÚ Rotate90DÚ Rotate90DictÚ RandRotate90DÚRandRotate90DictÚResizeDÚ ResizeDictÚAffineDÚ AffineDictÚ RandAffineDÚRandAffineDictÚRand2DElasticDÚRand2DElasticDictÚRand3DElasticDÚRand3DElasticDictÚFlipDÚFlipDictÚ RandFlipDÚ RandFlipDictÚGridDistortionDÚGridDistortionDictÚRandGridDistortionDÚRandGridDistortionDictÚ RandAxisFlipDÚRandAxisFlipDictÚRotateDÚ RotateDictÚ RandRotateDÚRandRotateDictÚZoomDÚZoomDictÚ RandZoomDÚ RandZoomDictÚ GridSplitdÚ GridSplitDÚ GridSplitDictÚ GridPatchdÚ GridPatchDÚ GridPatchDictÚRandGridPatchdÚRandGridPatchDÚRandGridPatchDictÚRandSimulateLowResolutiondÚRandSimulateLowResolutionDÚRandSimulateLowResolutionDictc @s†eZdZdZejZejej de j dddfddddddd d d d œ d d „Z e jjd d dœdd„ƒZdddddœdd„Zdddœdd„ZdS)r7aÅ Dictionary-based wrapper of :py:class:`monai.transforms.SpatialResample`. This transform assumes the ``data`` dictionary has a key for the input data's metadata and contains ``src_affine`` and ``dst_affine`` required by `SpatialResample`. The key is formed by ``key_{meta_key_postfix}``. The transform will swap ``src_affine`` and ``dst_affine`` affine (with potential data type changes) in the dictionary so that ``src_affine`` always refers to the current status of affine. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. See also: :py:class:`monai.transforms.SpatialResample` FÚ dst_affiner r úSequence[bool] | boolúSequence[DtypeLike] | DtypeLikezKeysCollection | NoneÚboolÚNone) ÚkeysÚmodeÚ padding_modeÚ align_cornersÚdtypeÚdst_keysÚallow_missing_keysÚlazyÚreturnc Cs†t |||¡tj||dt|d|_t|t|jƒƒ|_t|t|jƒƒ|_ t|t|jƒƒ|_ t|t|jƒƒ|_ t|t|jƒƒ|_ dS)aN Args: keys: keys of the corresponding items to be transformed. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample It also can be a sequence of bool, each element corresponds to a key in ``keys``. dtype: data type for resampling computation. Defaults to ``float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. It also can be a sequence of dtypes, each element corresponds to a key in ``keys``. dst_keys: the key of the corresponding ``dst_affine`` in the metadata dictionary. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False. ©r‰N) r)Ú__init__r(r%Ú sp_transformr2Úlenr‚rƒr„r…r†r‡) Úselfr‚rƒr„r…r†r‡rˆr‰©rúX/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/transforms/spatial/dictionary.pyrŒªs( zSpatialResampled.__init__©ÚvalrŠcCs||_||j_dS©N)Ú_lazyrr‰©rr“rrr‘r‰ÛszSpatialResampled.lazyNúMapping[Hashable, torch.Tensor]ú bool | Noneúdict[Hashable, torch.Tensor]©Údatar‰rŠc Cst|dkr|jn|}t|ƒ}| ||j|j|j|j|j¡D]6\}}}}} } |j|||| d|||| |d||<q8|S)á Args: data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified in this dictionary must be tensor like arrays that are channel first and have at most three spatial dimensions lazy: a flag to indicate whether this transform should execute lazily or not during this call. Setting this to False or True overrides the ``lazy`` flag set during initialization for this call. Defaults to None. Returns: a dictionary containing the transformed data, as well as any other data present in the dictionary N)Úimgr}Ú spatial_sizerƒr„r…r†r‰) r‰ÚdictÚ key_iteratorrƒr„r…r†r‡r) rr›r‰Úlazy_ÚdÚkeyrƒr„r…r†Údst_keyrrr‘Ú__call__às* ÿø zSpatialResampled.__call__©r›rŠcCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”)rŸr rÚinverse©rr›r¢r£rrr‘r§þszSpatialResampled.inverse)N)Ú__name__Ú __module__Ú __qualname__Ú__doc__r%Úbackendr,ÚBILINEARr-ÚBORDERÚnpÚfloat64rŒr(r‰Úsetterr¥r§rrrr‘r7–s÷ 1c @s‚eZdZdZejZejej de j ddfddddddddd œd d „Z e jjdd d œdd„ƒZdddddœdd„Zdddœdd„ZdS)r8zÖ Dictionary-based wrapper of :py:class:`monai.transforms.ResampleToMatch`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Fr Ústrr r~rr€)r‚Úkey_dstrƒr„r…r†rˆr‰c Cszt |||¡tj||d||_t|t|jƒƒ|_t|t|jƒƒ|_t|t|jƒƒ|_ t|t|jƒƒ|_ t |d|_ dS)a' Args: keys: keys of the corresponding items to be transformed. key_dst: key of image to resample to match. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/nn.functional.html#grid-sample It also can be a sequence of bool, each element corresponds to a key in ``keys``. dtype: data type for resampling computation. Defaults to ``float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. It also can be a sequence of dtypes, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False r‹N) r)rŒr(r´r2rŽr‚rƒr„r…r†r Ú resampler) rr‚r´rƒr„r…r†rˆr‰rrr‘rŒs(zResampleToMatchd.__init__rr’cCs||_||j_dSr”)r•rµr‰r–rrr‘r‰AszResampleToMatchd.lazyNr—r˜r™ršc Csn|dkr|jn|}t|ƒ}| ||j|j|j|j¡D]4\}}}}} |j||||j|||| |d||<q4|S)rœN)rÚimg_dstrƒr„r…r†r‰) r‰rŸr rƒr„r…r†rµr´) rr›r‰r¡r¢r£rƒr„r…r†rrr‘r¥Fs& ÿù zResampleToMatchd.__call__r¦cCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”)rŸr rµr§r¨rrr‘r§cszResampleToMatchd.inverse)N)r©rªr«r¬r r­r,r®r-r¯r°r±rŒr(r‰r²r¥r§rrrr‘r8s÷1c@sœeZdZdZejZdejej de j dddddddf dddddd d ddd d dddd d œdd„Z e jjdd dœdd„ƒZdddddœdd„Zdddœdd„ZdS)r9a] Dictionary-based wrapper of :py:class:`monai.transforms.Spacing`. This transform assumes the ``data`` dictionary has a key for the input data's metadata and contains `affine` field. The key is formed by ``key_{meta_key_postfix}``. After resampling the input array, this transform will write the new affine to the `affine` field of metadata which is formed by ``key_{meta_key_postfix}``. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. see also: :py:class:`monai.transforms.Spacing` FNTr úSequence[float] | floatr€r r~rúSequence[float] | float | Noner)r‚ÚpixdimÚdiagonalrƒr„r…r†Ú scale_extentÚrecompute_affineÚ min_pixdimÚ max_pixdimÚensure_same_shaperˆr‰rŠcCs–t ||| ¡tj||dt||| | | |d|_t|t|jƒƒ|_t|t|jƒƒ|_ t|t|jƒƒ|_ t|t|jƒƒ|_ t|t|jƒƒ|_ | |_ dS)aå Args: pixdim: output voxel spacing. if providing a single number, will use it for the first dimension. items of the pixdim sequence map to the spatial dimensions of input image, if length of pixdim sequence is longer than image spatial dimensions, will ignore the longer part, if shorter, will pad with `1.0`. if the components of the `pixdim` are non-positive values, the transform will use the corresponding components of the original pixdim, which is computed from the `affine` matrix of input image. diagonal: whether to resample the input to have a diagonal affine matrix. If True, the input data is resampled to the following affine:: np.diag((pixdim_0, pixdim_1, pixdim_2, 1)) This effectively resets the volume to the world coordinate system (RAS+ in nibabel). The original orientation, rotation, shearing are not preserved. If False, the axes orientation, orthogonal rotation and translations components from the original affine will be preserved in the target affine. This option will not flip/swap axes against the original ones. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. align_corners: Geometrically, we consider the pixels of the input as squares rather than points. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html It also can be a sequence of bool, each element corresponds to a key in ``keys``. dtype: data type for resampling computation. Defaults to ``float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. It also can be a sequence of dtypes, each element corresponds to a key in ``keys``. scale_extent: whether the scale is computed based on the spacing or the full extent of voxels, default False. The option is ignored if output spatial size is specified when calling this transform. See also: :py:func:`monai.data.utils.compute_shape_offset`. When this is True, `align_corners` should be `True` because `compute_shape_offset` already provides the corner alignment shift/scaling. recompute_affine: whether to recompute affine based on the output shape. The affine computed analytically does not reflect the potential quantization errors in terms of the output shape. Set this flag to True to recompute the output affine based on the actual pixdim. Default to ``False``. min_pixdim: minimal input spacing to be resampled. If provided, input image with a larger spacing than this value will be kept in its original spacing (not be resampled to `pixdim`). Set it to `None` to use the value of `pixdim`. Default to `None`. max_pixdim: maximal input spacing to be resampled. If provided, input image with a smaller spacing than this value will be kept in its original spacing (not be resampled to `pixdim`). Set it to `None` to use the value of `pixdim`. Default to `None`. ensure_same_shape: when the inputs have the same spatial shape, and almost the same pixdim, whether to ensure exactly the same output spatial shape. Default to True. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False r‹)rºr¼r½r¾r‰N)r)rŒr(r$Úspacing_transformr2rŽr‚rƒr„r…r†r»r¿)rr‚r¹rºrƒr„r…r†r»r¼r½r¾r¿rˆr‰rrr‘rŒ}s NúzSpacingd.__init__r’cCs||_||j_dSr”)r•rÀr‰r–rrr‘r‰Üsz Spacingd.lazyr—r˜r™ršc Cs$t|ƒ}d\}}}d}|dkr$|jn|}| ||j|j|j|j|j¡D]Ø\} } } } } }|jr¾t || t ƒr¾|dkr”|dkr”||   ¡|| j }}n*t  |||   ¡¡o¼t j||| j dd}|j|| | | | | ||rÚ|nd|d|| <|dkrFt || t ƒr ||   ¡n|| jdd…}qF|S)rœ)NNFNgü©ñÒMbP?)Úatol)Ú data_arrayrƒr„r…r†r»Úoutput_spatial_shaper‰é)rŸr‰r rƒr„r…r†r»r¿Ú isinstancer Úpeek_pending_shaper¹r°ÚallcloserÀÚshape)rr›r‰r¢Ú _init_shapeÚ_pixdimZ should_matchZoutput_shape_kr¡r£rƒr„r…r†r»rrr‘r¥ásB  ÿÿ ø 0zSpacingd.__call__ú"Mapping[Hashable, NdarrayOrTensor]údict[Hashable, NdarrayOrTensor]r¦cCs8t|ƒ}| |¡D] }|j ttj||ƒ¡||<q|Sr”)rŸr rÀr§rÚtorchÚTensorr¨rrr‘r§ szSpacingd.inverse)N)r©rªr«r¬r$r­r,r®r-r¯r°r±rŒr(r‰r²r¥r§rrrr‘r9js&ñ,_+c @sneZdZdZejZdddddddd d œd d „Zejj dd d œdd„ƒZdddddœdd„Z dddœdd„Z dS)r:a¢ Dictionary-based wrapper of :py:class:`monai.transforms.Orientation`. This transform assumes the channel-first input format. In the case of using this transform for normalizing the orientations of images, it should be used before any anisotropic spatial transforms. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. NF©)ÚLÚR)ÚPÚA)ÚIÚSr ú str | Noner€z Sequence[tuple[str, str]] | Noner)r‚ÚaxcodesÚas_closest_canonicalÚlabelsrˆr‰rŠcCs2t |||¡tj||dt||||d|_dS)aÑ Args: axcodes: N elements sequence for spatial ND input's orientation. e.g. axcodes='RAS' represents 3D orientation: (Left, Right), (Posterior, Anterior), (Inferior, Superior). default orientation labels options are: 'L' and 'R' for the first dimension, 'P' and 'A' for the second, 'I' and 'S' for the third. as_closest_canonical: if True, load the image as closest to canonical axis format. labels: optional, None or sequence of (2,) sequences (2,) sequences are labels for (beginning, end) of output axis. Defaults to ``(('L', 'R'), ('P', 'A'), ('I', 'S'))``. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False See Also: `nibabel.orientations.ornt2axcodes`. r‹)r×rØrÙr‰N)r)rŒr(rÚornt_transform)rr‚r×rØrÙrˆr‰rrr‘rŒ!sÿzOrientationd.__init__r’cCs||_||j_dSr”)r•rÚr‰r–rrr‘r‰CszOrientationd.lazyr—r˜r™ršcCsDt|ƒ}|dkr|jn|}| |¡D]}|j|||d||<q$|S©rœNr‹)rŸr‰r rÚ©rr›r‰r¢r¡r£rrr‘r¥Hs zOrientationd.__call__r¦cCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”)rŸr rÚr§r¨rrr‘r§[szOrientationd.inverse)NFrÏFF)N) r©rªr«r¬rr­rŒr(r‰r²r¥r§rrrr‘r:s ù"c@sleZdZdZejZddddddd d œd d „Zejj dd d œdd„ƒZdddddœdd„Z dddœdd„Z dS)r;zÎ Dictionary-based wrapper of :py:class:`monai.transforms.Rotate90`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. rÄ©rrÄFr Úintútuple[int, int]r€r)r‚ÚkÚ spatial_axesrˆr‰rŠcCs0t |||¡tj||dt|||d|_dS)aÁ Args: k: number of times to rotate by 90 degrees. spatial_axes: 2 int numbers, defines the plane to rotate with 2 spatial axes. Default: (0, 1), this is the first two axis in spatial dimensions. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False r‹N)r)rŒr(r#Úrotator)rr‚ràrárˆr‰rrr‘rŒlszRotate90d.__init__r’cCs||_||j_dSr”)r•râr‰r–rrr‘r‰szRotate90d.lazyNr—r˜r™ršcCsDt|ƒ}|dkr|jn|}| |¡D]}|j|||d||<q$|SrÛ)rŸr‰r rârÜrrr‘r¥†s zRotate90d.__call__r¦cCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”©rŸr râr§r¨rrr‘r§™szRotate90d.inverse)rÄrÝFF)N) r©rªr«r¬r#r­rŒr(r‰r²r¥r§rrrr‘r;bsúc speZdZdZejZddddd d d d d œd d„Zddd dœ‡fdd„ Zdddddœdd„Zdddœdd„Z ‡Z S)r<aA Dictionary-based version :py:class:`monai.transforms.RandRotate90`. With probability `prob`, input arrays are rotated by 90 degrees in the plane specified by `spatial_axes`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. çš™™™™™¹?érÝFr ÚfloatrÞrßr€r)r‚ÚprobÚmax_krárˆr‰rŠcCs>t |||¡t ||¡tj||d||_||_d|_dS)a  Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` prob: probability of rotating. (Default 0.1, with 10% probability it returns a rotated array.) max_k: number of rotations will be sampled from `np.random.randint(max_k) + 1`. (Default 3) spatial_axes: 2 int numbers, defines the plane to rotate with 2 spatial axes. Default: (0, 1), this is the first two axis in spatial dimensions. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False r‹rN)r)rŒr*r(rèráÚ_rand_k)rr‚rçrèrárˆr‰rrr‘rŒ¬s  zRandRotate90d.__init__Nz Any | Noner¦cs$|j |j¡d|_tƒ d¡dS)NrÄ)rÑÚrandintrèréÚsuperÚ randomize)rr›©Ú __class__rr‘rìÌszRandRotate90d.randomizer—r˜ršcCs„| ¡t|ƒ}|dkr|jn|}t|j|j|d}| |¡D]@}|jrT|||ƒnt||t ƒd||<|j ||d|dq>|S©rœNr‹©Ú track_metaT©Úreplacer‰) rìrŸr‰r#rérár Ú _do_transformr0r Úpush_transform)rr›r‰r¢r¡râr£rrr‘r¥Ðs(zRandRotate90d.__call__r™cCs`t|ƒ}| |¡D]H}t||tƒs&q| ||¡}|tjrtƒ |||tj ¡||<q|Sr”) rŸr rÅr Ú pop_transformr4Ú DO_TRANSFORMr#Úinverse_transformÚ EXTRA_INFO©rr›r¢r£Úxformrrr‘r§ës zRandRotate90d.inverse)rärårÝFF)N)N) r©rªr«r¬r#r­rŒrìr¥r§Ú __classcell__rrrír‘r< s ù ÿc @sŠeZdZdZejZdejdddej ddfddddd d d d d d ddœ dd„Z e j j d ddœdd„ƒZ dddddœdd„Zdddœdd„ZdS)r=a7 Dictionary-based wrapper of :py:class:`monai.transforms.Resize`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` spatial_size: expected shape of spatial dimensions after resize operation. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. size_mode: should be "all" or "longest", if "all", will use `spatial_size` for all the spatial dims, if "longest", rescale the image so that only the longest side is equal to specified `spatial_size`, which must be an int number in this case, keeping the aspect ratio of the initial image, refer to: https://albumentations.ai/docs/api_reference/augmentations/geometric/resize/ #albumentations.augmentations.geometric.resize.LongestMaxSize. mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. Defaults to ``"area"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html It also can be a sequence of string, each element corresponds to a key in ``keys``. align_corners: This only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html It also can be a sequence of bool or None, each element corresponds to a key in ``keys``. anti_aliasing: bool Whether to apply a Gaussian filter to smooth the image prior to downsampling. It is crucial to filter when downsampling the image to avoid aliasing artifacts. See also ``skimage.transform.resize`` anti_aliasing_sigma: {float, tuple of floats}, optional Standard deviation for Gaussian filtering used when anti-aliasing. By default, this value is chosen as (s - 1) / 2 where s is the downsampling factor, where s > 1. For the up-size case, s < 1, no anti-aliasing is performed prior to rescaling. dtype: data type for resampling computation. Defaults to ``float32``. If None, use the data type of input data. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False ÚallNFr zSequence[int] | intr³r ú#Sequence[bool | None] | bool | Noner~zISequence[Sequence[float] | float | None] | Sequence[float] | float | Noneú;Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtyper€r) r‚ržÚ size_moderƒr…Ú anti_aliasingÚanti_aliasing_sigmar†rˆr‰rŠc CsŠt ||| ¡tj|| dt|t|jƒƒ|_t|t|jƒƒ|_t|t|jƒƒ|_t|t|jƒƒ|_ t|t|jƒƒ|_ t ||| d|_ dS)Nr‹)ržrr‰) r)rŒr(r2rŽr‚rƒr…r†rrr!Úresizer) rr‚ržrrƒr…rrr†rˆr‰rrr‘rŒ#s zResized.__init__r’cCs||_||j_dSr”)r•rr‰r–rrr‘r‰9sz Resized.lazyr—r˜r™ršc Csnt|ƒ}|dkr|jn|}| ||j|j|j|j|j¡D]0\}}}}} } |j|||||| | |d||<q8|S)rœN)rƒr…rrr†r‰) rŸr‰r rƒr…rrr†r) rr›r‰r¢r¡r£rƒr…rrr†rrr‘r¥>s( ÿù zResized.__call__r¦cCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”)rŸr rr§r¨rrr‘r§[szResized.inverse)N)r©rªr«r¬r!r­r.ÚAREAr°Úfloat32rŒr(r‰r²r¥r§rrrr‘r=ös*õ$c@sžeZdZdZejZddddddejej de j dddf dddddddddd d d d d d d œdd„Z e jjd d dœdd„ƒZdddddœdd„Zdddœdd„ZdS)r>zÌ Dictionary-based wrapper of :py:class:`monai.transforms.Affine`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. NFr r¸zNdarrayOrTensor | NoneúSequence[int] | int | Noner útorch.device | NonezDtypeLike | torch.dtyper€r)r‚Ú rotate_paramsÚ shear_paramsÚtranslate_paramsÚ scale_paramsÚaffineržrƒr„Údevicer†r…rˆr‰rŠc Csbt ||| ¡tj||dt||||||| | | |d |_t|t|jƒƒ|_t| t|jƒƒ|_ dS)aS Args: keys: keys of the corresponding items to be transformed. rotate_params: a rotation angle in radians, a scalar for 2D image, a tuple of 3 floats for 3D. Defaults to no rotation. shear_params: shearing factors for affine matrix, take a 3D affine as example:: [ [1.0, params[0], params[1], 0.0], [params[2], 1.0, params[3], 0.0], [params[4], params[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] a tuple of 2 floats for 2D, a tuple of 6 floats for 3D. Defaults to no shearing. translate_params: a tuple of 2 floats for 2D, a tuple of 3 floats for 3D. Translation is in pixel/voxel relative to the center of the input image. Defaults to no translation. scale_params: scale factor for every spatial dims. a tuple of 2 floats for 2D, a tuple of 3 floats for 3D. Defaults to `1.0`. affine: if applied, ignore the params (`rotate_params`, etc.) and use the supplied matrix. Should be square with each side = num of image spatial dimensions + 1. spatial_size: output image spatial size. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"reflection"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. device: device on which the tensor will be allocated. dtype: data type for resampling computation. Defaults to ``float32``. If ``None``, use the data type of input data. To be compatible with other modules, the output data type is always `float32`. align_corners: Defaults to False. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False See also: - :py:class:`monai.transforms.compose.MapTransform` - :py:class:`RandAffineGrid` for the random affine parameters configurations. r‹) rr r r r ržr r†r…r‰N) r)rŒr(rr r2rŽr‚rƒr„)rr‚rr r r r ržrƒr„r r†r…rˆr‰rrr‘rŒls Jö zAffined.__init__r’cCs||_||j_dSr”)r•r r‰r–rrr‘r‰Çsz Affined.lazyr—r˜r™ršc CsZ|dkr|jn|}t|ƒ}| ||j|j¡D](\}}}|j|||||d\||<}q,|S)rœN)rƒr„r‰)r‰rŸr rƒr„r ) rr›r‰r¡r¢r£rƒr„Ú_rrr‘r¥Ìs  zAffined.__call__r¦cCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”)rŸr r r§r¨rrr‘r§ßszAffined.inverse)N)r©rªr«r¬rr­r,r®r-Ú REFLECTIONr°rrŒr(r‰r²r¥r§rrrr‘r>bs(ñ,[cs´eZdZdZejZddddddejej ddddf dddddddd d d d d d d d œdd„Z e j j d d dœdd„ƒZ d!ddddœ‡fdd„ Zd"ddddœdd„Zdddœdd „Z‡ZS)#r?zÐ Dictionary-based wrapper of :py:class:`monai.transforms.RandAffine`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. NräFr rræú4Sequence[tuple[float, float] | float] | float | Noner r€rr)r‚ržrçÚ rotate_rangeÚ shear_rangeÚtranslate_rangeÚ scale_rangerƒr„Ú cache_gridr rˆr‰rŠc Cslt ||| ¡t ||¡tj|| dtd|||||| | | d |_t|t|jƒƒ|_ t| t|jƒƒ|_ dS)a: Args: keys: keys of the corresponding items to be transformed. spatial_size: output image spatial size. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. prob: probability of returning a randomized affine grid. defaults to 0.1, with 10% chance returns a randomized grid. rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then `uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used. This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]` for dim0 and nothing for the remaining dimensions. shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select shearing factors(a tuple of 2 floats for 2D, a tuple of 6 floats for 3D) for affine matrix, take a 3D affine as example:: [ [1.0, params[0], params[1], 0.0], [params[2], 1.0, params[3], 0.0], [params[4], params[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] translate_range: translate range with format matching `rotate_range`, it defines the range to randomly select pixel/voxel to translate for every spatial dims. scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select the scale factor to translate for every spatial dims. A value of 1.0 is added to the result. This allows 0 to correspond to no change (i.e., a scaling of 1.0). mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"reflection"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. cache_grid: whether to cache the identity sampling grid. If the spatial size is not dynamically defined by input image, enabling this option could accelerate the transform. device: device on which the tensor will be allocated. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False See also: - :py:class:`monai.transforms.compose.MapTransform` - :py:class:`RandAffineGrid` for the random affine parameters configurations. r‹çð?) rçrrrrržrr r‰N) r)rŒr*r(rÚ rand_affiner2rŽr‚rƒr„)rr‚ržrçrrrrrƒr„rr rˆr‰rrr‘rŒðs L ÷ zRandAffined.__init__r’cCs||_||j_dSr”)r•rr‰r–rrr‘r‰MszRandAffined.lazyú int | Noneúnp.random.RandomState | None©ÚseedÚstaterŠcs |j ||¡tƒ ||¡|Sr”)rÚset_random_staterë©rrrrírr‘rRszRandAffined.set_random_staterËr˜rÌršc CsXt|ƒ}| |¡}|dkr,t|tƒd}|S| d¡|j ¡||}t|tƒrZ| ¡n |j dd…}|dkrv|j n|}t |jj |ƒ} |j p˜| t|ƒk} d} | rÊ|jj| |d} |j rÊ|jj| | |d} | dkrÖdn| } | ||j|j¡D]f\} } }| r|j|| d| |d| |d|| <nt|| tƒtjd || <| |_ |j|| d|d qì|S) rœrrðNrÄr‹)Úgridr‰rT©rñr†rò)rŸÚ first_keyr0r rìrrÅr rÆrÈr‰r3ržrôr1Úget_identity_gridÚrand_affine_gridr rƒr„rÍrrõ)rr›r‰r¢r!ÚoutÚitemržr¡Úsp_sizeÚ do_resamplingrr£rƒr„rrr‘r¥Ws2    "zRandAffined.__call__r¦cCs~t|ƒ}| |¡D]f}| ||¡}tj|tjkr6q|tjtjd}|r||j |tj¡|j ||¡||<q|S)Nr') rŸr rör4rùÚapplied_operationsÚappendrr§)rr›r¢r£Útrr'rrr‘r§‰szRandAffined.inverse)NN)N)r©rªr«r¬rr­r,r®r-rrŒr(r‰r²rr¥r§rürrrír‘r?æs*ò*]ÿ2cs„eZdZdZejZddddddejej ddf ddddd d d d d d d d d ddœdd„Z dddddœ‡fdd„ Z dddœdd„Z ‡Z S)r@zQ Dictionary-based wrapper of :py:class:`monai.transforms.Rand2DElastic`. NräFr útuple[float, float] | floatútuple[float, float]ztuple[int, int] | int | Nonerærr rr€r)r‚ÚspacingÚmagnitude_rangeržrçrrrrrƒr„r rˆrŠc Cs^t ||| ¡t ||¡t||d|||| || d |_t| t|jƒƒ|_t| t|jƒƒ|_ dS)a¹ Args: keys: keys of the corresponding items to be transformed. spacing: distance in between the control points. magnitude_range: 2 int numbers, the random offsets will be generated from ``uniform[magnitude[0], magnitude[1])``. spatial_size: specifying output image spatial size [h, w]. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. prob: probability of returning a randomized affine grid. defaults to 0.1, with 10% chance returns a randomized grid, otherwise returns a ``spatial_size`` centered area extracted from the input image. rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then `uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used. This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]` for dim0 and nothing for the remaining dimensions. shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select shearing factors(a tuple of 2 floats for 2D) for affine matrix, take a 2D affine as example:: [ [1.0, params[0], 0.0], [params[1], 1.0, 0.0], [0.0, 0.0, 1.0], ] translate_range: translate range with format matching `rotate_range`, it defines the range to randomly select pixel to translate for every spatial dims. scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select the scale factor to translate for every spatial dims. A value of 1.0 is added to the result. This allows 0 to correspond to no change (i.e., a scaling of 1.0). mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"reflection"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. device: device on which the tensor will be allocated. allow_missing_keys: don't raise exception if key is missing. See also: - :py:class:`RandAffineGrid` for the random affine parameters configurations. - :py:class:`Affine` for the affine transformation parameters configurations. r) r-r.rçrrrrržr N) r)rŒr*rÚrand_2d_elasticr2rŽr‚rƒr„)rr‚r-r.ržrçrrrrrƒr„r rˆrrr‘rŒžsI ÷ zRand2DElasticd.__init__rrrcs |j ||¡tƒ ||¡|Sr”)r/rrërrírr‘r÷szRand2DElasticd.set_random_staterËrÌr¦c Cszt|ƒ}| |¡}|dkr,t|tƒd}|S| d¡|jj}|dkrlt||tj ƒrl||j}|j  |¡t||t ƒr–||j r–t  d|›d¡t|jj||jdd…ƒ}|j |¡|jr$|jj|d}|jj|d}tjjjd | d ¡t|jjjd ƒtjjd d }t|d|d ƒ}nttj t ||ddƒ}| !||j"|j#¡D](\}} } |jj$|||| | d||<qL|S)á Args: data: a dictionary containing the tensor-like data to be processed. The ``keys`` specified in this dictionary must be tensor like arrays that are channel first and have at most three spatial dimensions Returns: a dictionary containing the transformed data, as well as any other data present in the dictionary rrðNúdata['úB'] has pending operations, transform may return incorrect results.rÄ)rž©rTréF)Úrecompute_scale_factorÚinputÚ scale_factorrƒr…)Úroi_sizerÍ©ržr r­©rƒr„)%rŸr!r0r rìr/r rÅrÍrÎÚ set_devicer Úpending_operationsÚwarningsÚwarnr3ržrÈrôÚ deform_gridr#ÚnnÚ functionalÚ interpolateÚ unsqueezer2r-r.ÚBICUBICÚvaluerrr+r rƒr„rµ) rr›r¢r!r$r r&rr£rƒr„rrr‘r¥üs:      û zRand2DElasticd.__call__)NN)r©rªr«r¬rr­r,r®r-rrŒrr¥rürrrír‘r@—sò*Ycs„eZdZdZejZddddddejej ddf dddddd d d d d d d d d dœdd„Z dddddœ‡fdd„ Z dddœdd„Z ‡Z S)rAzQ Dictionary-based wrapper of :py:class:`monai.transforms.Rand3DElastic`. NräFr r,z!tuple[int, int, int] | int | Nonerærr rr€r)r‚Ú sigma_ranger.ržrçrrrrrƒr„r rˆrŠc Cs^t ||| ¡t ||¡t||d|||| || d |_t| t|jƒƒ|_t| t|jƒƒ|_ dS)a“ Args: keys: keys of the corresponding items to be transformed. sigma_range: a Gaussian kernel with standard deviation sampled from ``uniform[sigma_range[0], sigma_range[1])`` will be used to smooth the random offset grid. magnitude_range: the random offsets on the grid will be generated from ``uniform[magnitude[0], magnitude[1])``. spatial_size: specifying output image spatial size [h, w, d]. if `spatial_size` and `self.spatial_size` are not defined, or smaller than 1, the transform will use the spatial size of `img`. if some components of the `spatial_size` are non-positive values, the transform will use the corresponding components of img size. For example, `spatial_size=(32, 32, -1)` will be adapted to `(32, 32, 64)` if the third spatial dimension size of img is `64`. prob: probability of returning a randomized affine grid. defaults to 0.1, with 10% chance returns a randomized grid, otherwise returns a ``spatial_size`` centered area extracted from the input image. rotate_range: angle range in radians. If element `i` is a pair of (min, max) values, then `uniform[-rotate_range[i][0], rotate_range[i][1])` will be used to generate the rotation parameter for the `i`th spatial dimension. If not, `uniform[-rotate_range[i], rotate_range[i])` will be used. This can be altered on a per-dimension basis. E.g., `((0,3), 1, ...)`: for dim0, rotation will be in range `[0, 3]`, and for dim1 `[-1, 1]` will be used. Setting a single value will use `[-x, x]` for dim0 and nothing for the remaining dimensions. shear_range: shear range with format matching `rotate_range`, it defines the range to randomly select shearing factors(a tuple of 6 floats for 3D) for affine matrix, take a 3D affine as example:: [ [1.0, params[0], params[1], 0.0], [params[2], 1.0, params[3], 0.0], [params[4], params[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] translate_range: translate range with format matching `rotate_range`, it defines the range to randomly select voxel to translate for every spatial dims. scale_range: scaling range with format matching `rotate_range`. it defines the range to randomly select the scale factor to translate for every spatial dims. A value of 1.0 is added to the result. This allows 0 to correspond to no change (i.e., a scaling of 1.0). mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"reflection"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. device: device on which the tensor will be allocated. allow_missing_keys: don't raise exception if key is missing. See also: - :py:class:`RandAffineGrid` for the random affine parameters configurations. - :py:class:`Affine` for the affine transformation parameters configurations. r) rFr.rçrrrrržr N) r)rŒr*rÚrand_3d_elasticr2rŽr‚rƒr„)rr‚rFr.ržrçrrrrrƒr„r rˆrrr‘rŒ3sK ÷ zRand3DElasticd.__init__rrrcs |j ||¡tƒ ||¡|Sr”)rGrrërrírr‘rŽszRand3DElasticd.set_random_stater—r™r¦c Csvt|ƒ}| |¡}|dkr,t|tƒd}|S| d¡t||tƒr`||jr`t  d|›d¡t |j j ||j dd…ƒ}|j  |¡|j j}|dkr¾t||tjƒr¾||j}|j  |¡t||dd}|jr6td |j jd d  |¡}tj|j j|d  d ¡} |dd …|| ƒd |j j7<|j j|d}| ||j|j¡D](\} } } |j j|| || | d|| <qH|S)r0rrðNr1r2rÄrÍr9råg@)Ú spatial_dimsÚsigmaÚ truncated)r rr3r:) rŸr!r0r rìrÅr r<r=r>r3rGržrÈr rÍrÎr;r+rôrrIÚtoÚ as_tensorÚ rand_offsetrCÚ magnituder#r rƒr„rµ) rr›r¢r!r$r&r rÚgaussianÚoffsetr£rƒr„rrr‘r¥“s.      $ zRand3DElasticd.__call__)NN)r©rªr«r¬rr­r,r®r-rrŒrr¥rürrrír‘rA,sò*[c@sheZdZdZejZdddddddœd d „Zejj dd œd d „ƒZdddddœdd„Z dddœdd„Z dS)rBa‡ Dictionary-based wrapper of :py:class:`monai.transforms.Flip`. See `numpy.flip` for additional details. https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: Keys to pick data for transformation. spatial_axis: Spatial axes along which to flip over. Default is None. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False NFr rr€r)r‚Ú spatial_axisrˆr‰rŠcCs,t |||¡tj||dt|d|_dS)Nr‹)rQ)r)rŒr(rÚflipper)rr‚rQrˆr‰rrr‘rŒÐszFlipd.__init__©r“cCs||j_||_dSr”©rRr‰r•r–rrr‘r‰Ûsz Flipd.lazyr—r˜r™ršcCsDt|ƒ}|dkr|jn|}| |¡D]}|j|||d||<q$|SrÛ)rŸr‰r rRrÜrrr‘r¥às zFlipd.__call__r¦cCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”)rŸr rRr§r¨rrr‘r§ósz Flipd.inverse)NFF)N) r©rªr«r¬rr­rŒr(r‰r²r¥r§rrrr‘rB¼sû cs†eZdZdZejZddddddd d œd d „Zejj dd œdd„ƒZdddddœ‡fdd„ Z d ddddœdd„Z dddœdd„Z ‡Z S)!rCa¯ Dictionary-based version :py:class:`monai.transforms.RandFlip`. See `numpy.flip` for additional details. https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: Keys to pick data for transformation. prob: Probability of flipping. spatial_axis: Spatial axes along which to flip over. Default is None. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False räNFr rærr€r)r‚rçrQrˆr‰rŠcCs:t |||¡t ||¡tj||dt||d|_dS)Nr‹)rQr‰)r)rŒr*r(rrR)rr‚rçrQrˆr‰rrr‘rŒs zRandFlipd.__init__rScCs||j_||_dSr”rTr–rrr‘r‰szRandFlipd.lazyrrrcstƒ ||¡|Sr”©rërrrírr‘r!szRandFlipd.set_random_stater—r˜r™ršcCs€t|ƒ}| d¡|dkr |jn|}| |¡D]L}|jrP|j|||d||<nt||tƒd||<|j||d|dq.|Srï) rŸrìr‰r rôrRr0r rõrÜrrr‘r¥%s  zRandFlipd.__call__r¦c Cs`t|ƒ}| |¡D]H}| ||¡}|tjs0q|j d¡| ||¡||<W5QRXq|S)NF)rŸr rör4r÷rRÚtrace_transformrúrrr‘r§>s zRandFlipd.inverse)räNFF)NN)N)r©rªr«r¬rr­rŒr(r‰r²rr¥r§rürrrír‘rCúsú cs„eZdZdZejZdddddddœd d „Zejj dd œd d „ƒZdddddœ‡fdd„ Z dddddœdd„Z dddœdd„Z ‡Z S) rFae Dictionary-based version :py:class:`monai.transforms.RandAxisFlip`. See `numpy.flip` for additional details. https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: Keys to pick data for transformation. prob: Probability of flipping. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False räFr rær€r)r‚rçrˆr‰rŠcCs:t |||¡t ||¡tj||dtd|d|_dS)Nr‹r)rçr‰)r)rŒr*r(rrR)rr‚rçrˆr‰rrr‘rŒ]s zRandAxisFlipd.__init__rScCs||j_||_dSr”rTr–rrr‘r‰eszRandAxisFlipd.lazyNrrrcs tƒ ||¡|j ||¡|Sr”)rërrRrrírr‘rjszRandAxisFlipd.set_random_stater—r˜r™ršcCs¨t|ƒ}| |¡}|dkr|S| d¡|j ||¡|dkrF|jn|}| |¡D]N}|jrx|j||d|d||<nt||tƒd||<|j ||d|dqT|S)rœrNF)rìr‰rðTrò) rŸr!rìrRr‰r rôr0r rõ)rr›r‰r¢r!r¡r£rrr‘r¥os   zRandAxisFlipd.__call__r¦cCs^t|ƒ}| |¡D]F}| ||¡}|tjr||j |tj¡|j  ||¡||<q|Sr”) rŸr rör4r÷r(r)rùrRr§rúrrr‘r§s zRandAxisFlipd.inverse)räFF)NN)N)r©rªr«r¬rr­rŒr(r‰r²rr¥r§rürrrír‘rFIsÿ c @s†eZdZdZejZdejej de j ddfddddddd ddd d œ d d „Z e jjddœdd„ƒZdddddœdd„Zdddœdd„ZdS)rGa¦ Dictionary-based wrapper of :py:class:`monai.transforms.Rotate`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: Keys to pick data for transformation. angle: Rotation angle(s) in radians. keep_size: If it is False, the output shape is adapted so that the input array is contained completely in the output. If it is True, the output shape is the same as the input. Default is True. 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 It also can be a sequence of string, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html It also can be a sequence of string, each element corresponds to a key in ``keys``. align_corners: Defaults to False. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html It also can be a sequence of bool, each element corresponds to a key in ``keys``. dtype: data type for resampling computation. Defaults to ``float32``. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. It also can be a sequence of dtype or None, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False TFr r·r€r r~rÿr) r‚ÚangleÚ keep_sizerƒr„r…r†rˆr‰rŠc Csxt |||¡tj|| dt||| d|_t|t|jƒƒ|_t|t|jƒƒ|_ t|t|jƒƒ|_ t|t|jƒƒ|_ dS)Nr‹)rWrXr‰) r)rŒr(r"râr2rŽr‚rƒr„r…r†) rr‚rWrXrƒr„r…r†rˆr‰rrr‘rŒ¼s zRotated.__init__rScCs||j_||_dSr”)râr‰r•r–rrr‘r‰Ñsz Rotated.lazyNr—r˜r™ršc Csft|ƒ}|dkr|jn|}| ||j|j|j|j¡D],\}}}}} |j|||||| |d||<q4|S©rœN)rƒr„r…r†r‰)rŸr‰r rƒr„r…r†râ© rr›r‰r¢r¡r£rƒr„r…r†rrr‘r¥Ös$ ÿÿ zRotated.__call__r¦cCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”rãr¨rrr‘r§íszRotated.inverse)N)r©rªr«r¬r"r­r,r®r-r¯r°rrŒr(r‰r²r¥r§rrrr‘rG™s ö"cs°eZdZdZejZdddddejej de j ddf dddddd d d d d d d d dœ dd„Z e jjd dœdd„ƒZd#ddddœ‡fdd„ Zd$ddddœdd„Zddd œd!d"„Z‡ZS)%rHa5 Dictionary-based version :py:class:`monai.transforms.RandRotate` Randomly rotates the input arrays. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: Keys to pick data for transformation. range_x: Range of rotation angle in radians in the plane defined by the first and second axes. If single number, angle is uniformly sampled from (-range_x, range_x). range_y: Range of rotation angle in radians in the plane defined by the first and third axes. If single number, angle is uniformly sampled from (-range_y, range_y). only work for 3D data. range_z: Range of rotation angle in radians in the plane defined by the second and third axes. If single number, angle is uniformly sampled from (-range_z, range_z). only work for 3D data. prob: Probability of rotation. keep_size: If it is False, the output shape is adapted so that the input array is contained completely in the output. If it is True, the output shape is the same as the input. Default is True. 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 It also can be a sequence of string, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html It also can be a sequence of string, each element corresponds to a key in ``keys``. align_corners: Defaults to False. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html It also can be a sequence of bool, each element corresponds to a key in ``keys``. dtype: data type for resampling computation. Defaults to ``float64`` for best precision. If None, use the data type of input data. To be compatible with other modules, the output data type is always ``float32``. It also can be a sequence of dtype or None, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False çräTFr r+rær€r r~rÿr) r‚Úrange_xÚrange_yÚrange_zrçrXrƒr„r…r†rˆr‰rŠc CsŠt ||| ¡t ||¡tj|| dt|||d|| d|_t|t|jƒƒ|_ t|t|jƒƒ|_ t| t|jƒƒ|_ t| t|jƒƒ|_ dS)Nr‹r)r\r]r^rçrXr‰) r)rŒr*r(rÚ rand_rotater2rŽr‚rƒr„r…r†) rr‚r\r]r^rçrXrƒr„r…r†rˆr‰rrr‘rŒs ÿzRandRotated.__init__rScCs||j_||_dSr”)r_r‰r•r–rrr‘r‰8szRandRotated.lazyNrrrcs tƒ ||¡|j ||¡|Sr”)rërr_rrírr‘r=szRandRotated.set_random_stater—r˜r™ršc Cs²t|ƒ}| d¡|j ¡|dkr*|jn|}| ||j|j|j|j¡D]d\}}}}} |j r~|j|||||| d|d||<nt ||t ƒt j d||<|j||d|dqH|S)rœNF©rƒr„r…r†rìr‰r Trò)rŸrìr_r‰r rƒr„r…r†rôr0r rÍrrõrZrrr‘r¥Bs0   ÿù zRandRotated.__call__r¦cCs^t|ƒ}| |¡D]F}| ||¡}|tjr||j |tj¡|j  ||¡||<q|Sr”) rŸr rör4r÷r(r)rùr_r§rúrrr‘r§hs zRandRotated.inverse)NN)N)r©rªr«r¬rr­r,r®r-r¯r°rrŒr(r‰r²rr¥r§rürrrír‘rHôs&'ó(&c @s†eZdZdZejZejej de j dddfdddddd d d d d d œ d d„Z e jjd dœdd„ƒZdddddœdd„Zdddœdd„ZdS)rIaS Dictionary-based wrapper of :py:class:`monai.transforms.Zoom`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: Keys to pick data for transformation. zoom: The zoom factor along the spatial axes. If a float, zoom is the same for each spatial axis. If a sequence, zoom should contain one value for each spatial axis. mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. Defaults to ``"area"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html It also can be a sequence of string, each element corresponds to a key in ``keys``. padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"edge"``. The mode to pad data after zooming. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html align_corners: This only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html It also can be a sequence of bool or None, each element corresponds to a key in ``keys``. dtype: data type for resampling computation. Defaults to ``float32``. If None, use the data type of input data. keep_size: Should keep original size (pad if needed), default is True. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. NTFr r·r rþrÿr€r) r‚Úzoomrƒr„r…r†rXrˆr‰rŠc Ks€t |||¡tj|| dt|t|jƒƒ|_t|t|jƒƒ|_t|t|jƒƒ|_t|t|jƒƒ|_ t f||| dœ| —Ž|_ dS)Nr‹)rarXr‰) r)rŒr(r2rŽr‚rƒr„r…r†r&Úzoomer) rr‚rarƒr„r…r†rXrˆr‰Úkwargsrrr‘rŒšs zZoomd.__init__rScCs||j_||_dSr”)rbr‰r•r–rrr‘r‰°sz Zoomd.lazyr—r˜r™ršc Csft|ƒ}|dkr|jn|}| ||j|j|j|j¡D],\}}}}} |j|||||| |d||<q4|SrY)rŸr‰r rƒr„r…r†rbrZrrr‘r¥µs$ ÿÿ zZoomd.__call__r¦cCs0t|ƒ}| |¡D]}|j ||¡||<q|Sr”)rŸr rbr§r¨rrr‘r§Ìsz Zoomd.inverse)N)r©rªr«r¬r&r­r.rr/ÚEDGEr°rrŒr(r‰r²r¥r§rrrr‘rIrs%ö"cs¬eZdZdZejZdddejej de j dddf dd d d d d d d dddddœ dd„Z e jjddœdd„ƒZd$ddddœ‡fdd„ Zd%ddddœdd „Zddd!œd"d#„Z‡ZS)&rJaJ Dict-based version :py:class:`monai.transforms.RandZoom`. This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic` for more information. Args: keys: Keys to pick data for transformation. prob: Probability of zooming. min_zoom: Min zoom factor. Can be float or sequence same size as image. If a float, select a random factor from `[min_zoom, max_zoom]` then apply to all spatial dims to keep the original spatial shape ratio. If a sequence, min_zoom should contain one value for each spatial axis. If 2 values provided for 3D data, use the first value for both H & W dims to keep the same zoom ratio. max_zoom: Max zoom factor. Can be float or sequence same size as image. If a float, select a random factor from `[min_zoom, max_zoom]` then apply to all spatial dims to keep the original spatial shape ratio. If a sequence, max_zoom should contain one value for each spatial axis. If 2 values provided for 3D data, use the first value for both H & W dims to keep the same zoom ratio. mode: {``"nearest"``, ``"nearest-exact"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``, ``"area"``} The interpolation mode. Defaults to ``"area"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html It also can be a sequence of string, each element corresponds to a key in ``keys``. padding_mode: available modes for numpy array:{``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} available modes for PyTorch Tensor: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to ``"edge"``. The mode to pad data after zooming. See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html align_corners: This only has an effect when mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: None. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html It also can be a sequence of bool or None, each element corresponds to a key in ``keys``. dtype: data type for resampling computation. Defaults to ``float32``. If None, use the data type of input data. keep_size: Should keep original size (pad if needed), default is True. allow_missing_keys: don't raise exception if key is missing. lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False kwargs: other args for `np.pad` API, note that `np.pad` treats channel dimension as the first dimension. more details: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html rägÍÌÌÌÌÌì?gš™™™™™ñ?NTFr rær·r rþrÿr€r) r‚rçÚmin_zoomÚmax_zoomrƒr„r…r†rXrˆr‰rŠc Kst ||| ¡t ||¡tj|| dtfd||| | dœ| —Ž|_t|t|jƒƒ|_ t|t|jƒƒ|_ t|t|jƒƒ|_ t|t|jƒƒ|_ dS)Nr‹r)rçrerfrXr‰) r)rŒr*r(rÚ rand_zoomr2rŽr‚rƒr„r…r†) rr‚rçrerfrƒr„r…r†rXrˆr‰rcrrr‘rŒs  ÿÿzRandZoomd.__init__rScCs||j_||_dSr”)rgr‰r•r–rrr‘r‰szRandZoomd.lazyrrrcs tƒ ||¡|j ||¡|Sr”)rërrgrrírr‘r!szRandZoomd.set_random_stater—r˜r™ršc CsÜt|ƒ}| |¡}|dkr,t|tƒd}|S| d¡|j ||¡|dkrT|jn|}| ||j|j |j |j ¡D]d\}}} } } |j r¨|j|||| | | d|d||<nt||tƒt jd||<|j||d|dqr|S) rœrrðNFr`r Trò)rŸr!r0r rìrgr‰r rƒr„r…r†rôrÍrrõ) rr›r‰r¢r!r$r¡r£rƒr„r…r†rrr‘r¥&s8   ÿù zRandZoomd.__call__r¦cCs^t|ƒ}| |¡D]F}| ||¡}|tjr||j |tj¡|j  ||¡||<q|Sr”) rŸr rör4r÷r(r)rùrgr§rúrrr‘r§Qs zRandZoomd.inverse)NN)N)r©rªr«r¬rr­r.rr/rdr°rrŒr(r‰r²rr¥r§rürrrír‘rJÓs$,ô&+c sXeZdZdZejZejej ddfddddddd d d œ‡fd d „ Z dddœdd„Z ‡Z S)rDzR Dictionary-based wrapper of :py:class:`monai.transforms.GridDistortion`. NFr útuple[int] | intz list[tuple]r³rr€r)r‚Ú num_cellsÚ distort_stepsrƒr„r rˆrŠcsFtƒ ||¡t|||d|_t|t|jƒƒ|_t|t|jƒƒ|_dS)a¬ Args: keys: keys of the corresponding items to be transformed. num_cells: number of grid cells on each dimension. distort_steps: This argument is a list of tuples, where each tuple contains the distort steps of the corresponding dimensions (in the order of H, W[, D]). The length of each tuple equals to `num_cells + 1`. Each value in the tuple represents the distort step of the related cell. mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. device: device on which the tensor will be allocated. allow_missing_keys: don't raise exception if key is missing. )rirjr N) rërŒrÚgrid_distortionr2rŽr‚rƒr„)rr‚rirjrƒr„r rˆrírr‘rŒbs"zGridDistortiond.__init__r—r™r¦cCsBt|ƒ}| ||j|j¡D]"\}}}|j||||d||<q|S)r0r:)rŸr rƒr„rk)rr›r¢r£rƒr„rrr‘r¥‰s zGridDistortiond.__call__) r©rªr«r¬rr­r,r®r-r¯rŒr¥rürrrír‘rD[sø"'c steZdZdZejZdddejej ddfddd d d d d d ddœ dd„Z dddddœ‡fdd„ Z dddœdd„Z ‡Z S)rEzV Dictionary-based wrapper of :py:class:`monai.transforms.RandGridDistortion`. érä)g¸…ëQ¸ž¿g¸…ëQ¸ž?NFr rhrær+r³rr€r) r‚rirçÚ distort_limitrƒr„r rˆrŠc CsTt |||¡t ||¡t|d||d|_t|t|jƒƒ|_t|t|jƒƒ|_ dS)aŽ Args: keys: keys of the corresponding items to be transformed. num_cells: number of grid cells on each dimension. prob: probability of returning a randomized grid distortion transform. Defaults to 0.1. distort_limit: range to randomly distort. If single number, distort_limit is picked from (-distort_limit, distort_limit). Defaults to (-0.03, 0.03). mode: {``"bilinear"``, ``"nearest"``} or spline interpolation order 0-5 (integers). Interpolation mode to calculate output values. Defaults to ``"bilinear"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When it's an integer, the numpy (cpu tensor)/cupy (cuda tensor) backends will be used and the value represents the order of the spline interpolation. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. padding_mode: {``"zeros"``, ``"border"``, ``"reflection"``} Padding mode for outside grid values. Defaults to ``"border"``. See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.grid_sample.html When `mode` is an integer, using numpy/cupy backends, this argument accepts {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', 'mirror', 'grid-wrap', 'wrap'}. See also: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html It also can be a sequence, each element corresponds to a key in ``keys``. device: device on which the tensor will be allocated. allow_missing_keys: don't raise exception if key is missing. r)rirçrmr N) r)rŒr*rÚrand_grid_distortionr2rŽr‚rƒr„) rr‚rirçrmrƒr„r rˆrrr‘rŒ s% ÿzRandGridDistortiond.__init__rrrcs tƒ ||¡|j ||¡|Sr”)rërrnrrírr‘rÍsz$RandGridDistortiond.set_random_stater—r™r¦cCsÎt|ƒ}| d¡|js*t|tƒd}|S| |¡}|dkrNt|tƒd}|St||tƒrx||jrxt   d|›d¡|j  ||j dd…¡|  ||j|j¡D]$\}}}|j ||||dd||<q¤|S) r0Nrðrr1r2rÄF)rƒr„rì)rŸrìrôr0r r!rÅr r<r=r>rnrÈr rƒr„)rr›r¢r$r!r£rƒr„rrr‘r¥Ôs   zRandGridDistortiond.__call__)NN)r©rªr«r¬rr­r,r®r-r¯rŒrr¥rürrrír‘rE™s÷ .ÿcsDeZdZdZejZdddddd œ‡fd d „ Zd d dœdd„Z‡ZS)rqaí Split the image into patches based on the provided grid in 2D. Args: keys: keys of the corresponding items to be transformed. grid: a tuple define the shape of the grid upon which the image is split. Defaults to (2, 2) size: a tuple or an integer that defines the output patch sizes, or a dictionary that define it separately for each key, like {"image": 3, "mask", (2, 2)}. If it's an integer, the value will be repeated for each dimension. The default is None, where the patch size will be inferred from the grid shape. allow_missing_keys: don't raise exception if key is missing. Note: This transform currently support only image with two spatial dimensions. ©r4r4NFr rßzKint | tuple[int, int] | dict[Hashable, int | tuple[int, int] | None] | Noner€)r‚rÚsizerˆcsHtƒ ||¡||_tˆtƒr"ˆn‡fdd„|jDƒ|_t|d|_dS)Ncsi|] }|ˆ“qSrr)Ú.0r£©rprr‘Ú sz'GridSplitd.__init__..r3) rërŒrrÅrŸr‚rprÚsplitter)rr‚rrprˆrírrr‘rŒ s$zGridSplitd.__init__rËz%list[dict[Hashable, NdarrayOrTensor]]r¦csrt|ƒ‰t |j¡}‡fdd„t|ƒDƒ}| ˆ¡D]8}| ˆ||j|¡}t|ƒD]}|||||<qVq4|S)r0csg|] }tˆƒ‘qSr)rŸ)rqr©r¢rr‘Ú  sz'GridSplitd.__call__..)rŸr°ÚprodrÚranger rtrp)rr›Ú n_outputsÚoutputr£ÚresultÚirrur‘r¥ s   zGridSplitd.__call__)roNF) r©rªr«r¬rr­rŒr¥rürrrír‘rqñsû c sNeZdZdZejZdddddd d d d d d œ ‡fdd„ Zdddœdd„Z‡ZS)rta Extract all the patches sweeping the entire image in a row-major sliding-window manner with possible overlaps. It can sort the patches and return all or a subset of them. Args: keys: keys of the corresponding items to be transformed. patch_size: size of patches to generate slices for, 0 or None selects whole dimension offset: starting position in the array, default is 0 for each dimension. np.random.randint(0, patch_size, 2) creates random start between 0 and `patch_size` for a 2D image. num_patches: number of patches (or maximum number of patches) to return. If the requested number of patches is greater than the number of available patches, padding will be applied to provide exactly `num_patches` patches unless `threshold` is set. When `threshold` is set, this value is treated as the maximum number of patches. Defaults to None, which does not limit number of the patches. overlap: amount of overlap between patches in each dimension. Default to 0.0. sort_fn: when `num_patches` is provided, it determines if keep patches with highest values (`"max"`), lowest values (`"min"`), or in their default order (`None`). Default to None. threshold: a value to keep only the patches whose sum of intensities are less than the threshold. Defaults to no filtering. pad_mode: the mode for padding the input image by `patch_size` to include patches that cross boundaries. Available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to `None`, which means no padding will be applied. See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html requires pytorch >= 1.10 for best compatibility. allow_missing_keys: don't raise exception if key is missing. pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Returns: dictionary, contains the all the original key/value with the values for `keys` replaced by the patches, a MetaTensor with following metadata: - `PatchKeys.LOCATION`: the starting location of the patch in the image, - `PatchKeys.COUNT`: total number of patches in the image, - "spatial_shape": spatial size of the extracted patch, and - "offset": the amount of offset for the patches in the image (starting position of the first patch) Nr[Fr ú Sequence[int]zSequence[int] | NonerrærÖú float | Noner€) r‚Ú patch_sizerPÚ num_patchesÚoverlapÚsort_fnÚ thresholdÚpad_moderˆc s2tƒ || ¡tf|||||||dœ| —Ž|_dS)N)rrPr€rr‚rƒr„)rërŒrÚpatcher) rr‚rrPr€rr‚rƒr„rˆÚ pad_kwargsrírr‘rŒP s ùøzGridPatchd.__init__rËrÌr¦cCs.t|ƒ}| |¡D]}| ||¡||<q|S)r0)rŸr r…r¨rrr‘r¥i s zGridPatchd.__call__)NNr[NNNF) r©rªr«r¬rr­rŒr¥rürrrír‘rt# s*ö$c sdeZdZdZejZddddddd d d d d d œ dd„Zdddddœ‡fdd„ Zdddœdd„Z‡Z S)rwa° Extract all the patches sweeping the entire image in a row-major sliding-window manner with possible overlaps, and with random offset for the minimal corner of the image, (0,0) for 2D and (0,0,0) for 3D. It can sort the patches and return all or a subset of them. Args: keys: keys of the corresponding items to be transformed. patch_size: size of patches to generate slices for, 0 or None selects whole dimension min_offset: the minimum range of starting position to be selected randomly. Defaults to 0. max_offset: the maximum range of starting position to be selected randomly. Defaults to image size modulo patch size. num_patches: number of patches (or maximum number of patches) to return. If the requested number of patches is greater than the number of available patches, padding will be applied to provide exactly `num_patches` patches unless `threshold` is set. When `threshold` is set, this value is treated as the maximum number of patches. Defaults to None, which does not limit number of the patches. overlap: the amount of overlap of neighboring patches in each dimension (a value between 0.0 and 1.0). If only one float number is given, it will be applied to all dimensions. Defaults to 0.0. sort_fn: when `num_patches` is provided, it determines if keep patches with highest values (`"max"`), lowest values (`"min"`), in random ("random"), or in their default order (`None`). Default to None. threshold: a value to keep only the patches whose sum of intensities are less than the threshold. Defaults to no filtering. pad_mode: the mode for padding the input image by `patch_size` to include patches that cross boundaries. Available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. Defaults to `None`, which means no padding will be applied. See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html requires pytorch >= 1.10 for best compatibility. allow_missing_keys: don't raise exception if key is missing. pad_kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Returns: dictionary, contains the all the original key/value with the values for `keys` replaced by the patches, a MetaTensor with following metadata: - `PatchKeys.LOCATION`: the starting location of the patch in the image, - `PatchKeys.COUNT`: total number of patches in the image, - "spatial_shape": spatial size of the extracted patch, and - "offset": the amount of offset for the patches in the image (starting position of the first patch) Nr[Fr r}rrrærÖr~r€) r‚rÚ min_offsetÚ max_offsetr€rr‚rƒr„rˆc Ks4t ||| ¡tf|||||||| dœ| —Ž|_dS)N)rr‡rˆr€rr‚rƒr„)r)rŒrr…) rr‚rr‡rˆr€rr‚rƒr„rˆr†rrr‘rŒª sø ÷zRandGridPatchd.__init__rrcs tƒ ||¡|j ||¡|Sr”)rërr…rrírr‘rÅ szRandGridPatchd.set_random_staterËrÌr¦cCsVt|ƒ}| |¡D]}|j ||¡q,q| |¡D]}|j||dd||<q6|S)r0F)rì)rŸr r…rìr¨rrr‘r¥Ê s zRandGridPatchd.__call__)NNNr[NNNF)NN) r©rªr«r¬rr­rŒrr¥rürrrír‘rwy s.õ"c speZdZdZejZdejejddddfddddd d d d œd d„Z dddddœ‡fdd„ Z dddœdd„Z ‡Z S)rza) Dictionary-based wrapper of :py:class:`monai.transforms.RandSimulateLowResolution`. Random simulation of low resolution corresponding to nnU-Net's SimulateLowResolutionTransform (https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/resample_transforms.py#L23) First, the array/tensor is resampled at lower resolution as determined by the zoom_factor which is uniformly sampled from the `zoom_range`. Then, the array/tensor is resampled at the original resolution. rä)gà?rFNr ræzInterpolateMode | strr€rr)r‚rçÚdownsample_modeÚ upsample_moderˆr rŠc Cs\t |||¡t ||¡||_||_||_||_||_td|j|j|j|j|jd|_ dS)aÙ Args: keys: keys of the corresponding items to be transformed. prob: probability of performing this augmentation downsample_mode: interpolation mode for downsampling operation upsample_mode: interpolation mode for upsampling operation zoom_range: range from which the random zoom factor for the downsampling and upsampling operation is sampled. It determines the shape of the downsampled tensor. align_corners: This only has an effect when downsample_mode or upsample_mode is 'linear', 'bilinear', 'bicubic' or 'trilinear'. Default: False See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.interpolate.html allow_missing_keys: don't raise exception if key is missing. device: device on which the tensor will be allocated. See also: - :py:class:`monai.transforms.compose.MapTransform` r)rçr‰rŠÚ zoom_ranger…r N) r)rŒr*r‰rŠr‹r…r rÚsim_lowres_tfm) rr‚rçr‰rŠr‹r…rˆr rrr‘rŒé s úz#RandSimulateLowResolutiond.__init__rrrcstƒ ||¡|Sr”rUrrírr‘r sz+RandSimulateLowResolutiond.set_random_staterËrÌr¦cCs~t|ƒ}| |¡}|dkr,t|tƒd}|S| d¡| |¡D]8}|jr^| ||¡||<q@t||tƒtj d||<q@|S)a Args: data: a dictionary containing the tensor-like data to be transformed. The ``keys`` specified in this dictionary must be tensor like arrays that are channel first and have at most three spatial dimensions rrðNr ) rŸr!r0r rìr rôrŒrÍr)rr›r¢r!r$r£rrr‘r¥ s  z#RandSimulateLowResolutiond.__call__)NN) r©rªr«r¬rr­r.ÚNEARESTÚ TRILINEARrŒrr¥rürrrír‘rzÞ s÷0ÿ)•r¬Ú __future__rr=Úcollections.abcrrrÚtypingrrÚnumpyr°rÍÚ monai.configrr r Úmonai.config.type_definitionsr Úmonai.data.meta_objr Úmonai.data.meta_tensorr Z"monai.networks.layers.simplelayersrZmonai.transforms.croppad.arrayrÚmonai.transforms.inverserÚmonai.transforms.spatial.arrayrrrrrrrrrrrrrrrr r!r"r#r$r%r&Úmonai.transforms.traitsr'Úmonai.transforms.transformr(r)r*Úmonai.transforms.utilsr+Ú monai.utilsr,r-r.r/r0r1r2r3Úmonai.utils.enumsr4Úmonai.utils.moduler5ÚnibrÚ__all__r7r8r9r:r;r<r=r>r?r@rArBrCrFrGrHrIrJrDrErqrtrwrzrKrLÚResampleToMatchDÚResampleToMatchDictrMrNrOrPrQrRrSrTrUrVrWrXrYrZr[r\r]r^r_r`rarbrcrdrerfrgrhrirjrkrlrmrnrorprrrsrurvrxryr{r|rrrr‘Ú s$       `  (   ºJoe*O>Vl2>OP[~a >X2VeX