o
    i                     @  s  d Z ddlmZ ddlmZmZmZmZ ddlm	Z	 ddl
mZ ddlZddlZddlmZmZmZ ddlmZ dd	lmZ dd
l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&m'Z'm(Z( ddl)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8 g dZ9G dd de0e*e/Z:G dd de:Z;G dd de:Z<G dd de:Z=G dd de0e*e/Z>G dd de>e1Z?G dd de>Z@G dd  d e>ZAG d!d" d"e>ZBG d#d$ d$e?ZCG d%d& d&e?ZDG d'd( d(e1e0e/e-ZEG d)d* d*e>ZFG d+d, d,e1e0e/e-ZGG d-d. d.e1e0e/e-ZHG d/d0 d0e1e0e/e-ZIG d1d2 d2e:ZJG d3d4 d4e0ZKe: ZLZMe; ZNZOe< ZPZQe= ZRZSe> ZTZUe? ZVZWe@ ZXZYeA ZZZ[eB Z\Z]eC Z^Z_eD Z`ZaeE ZbZceF ZdZeeG ZfZgeH ZhZieI ZjZkeJ ZlZmeK ZnZodS )5z
A collection of dictionary-based wrappers around the "vanilla" transforms for crop and pad operations
defined in :py:class:`monai.transforms.croppad.array`.

Class names are ended with 'd' to denote dictionary-based transforms.
    )annotations)CallableHashableMappingSequence)deepcopy)AnyN)IndexSelectionKeysCollectionSequenceStr)NdarrayOrTensor)
MetaTensor)	BorderPadBoundingRectCenterScaleCropCenterSpatialCropCropCropForegroundDivisiblePadPadRandCropByLabelClassesRandCropByPosNegLabelRandScaleCropRandSpatialCropRandSpatialCropSamplesRandWeightedCropResizeWithPadOrCropSpatialCrop
SpatialPad)InvertibleTransform)	LazyTraitMultiSampleTrait)LazyTransformMapTransformRandomizable)is_positive)MAX_SEEDMethodPytorchPadModeensure_tuple_rep)6PaddSpatialPadd
BorderPaddDivisiblePaddCropd	RandCropdSpatialCropdCenterSpatialCropdCenterScaleCropdRandScaleCropdRandSpatialCropdRandSpatialCropSamplesdCropForegrounddRandWeightedCropdRandCropByPosNegLabeldResizeWithPadOrCropdBoundingRectdRandCropByLabelClassesdPadDPadDictSpatialPadDSpatialPadDict
BorderPadDBorderPadDictDivisiblePadDDivisiblePadDictCropDCropDict	RandCropDRandCropDictSpatialCropDSpatialCropDictCenterSpatialCropDCenterSpatialCropDictCenterScaleCropDCenterScaleCropDictRandScaleCropDRandScaleCropDictRandSpatialCropDRandSpatialCropDictRandSpatialCropSamplesDRandSpatialCropSamplesDictCropForegroundDCropForegroundDictRandWeightedCropDRandWeightedCropDictRandCropByPosNegLabelDRandCropByPosNegLabelDictResizeWithPadOrCropDResizeWithPadOrCropDictBoundingRectDBoundingRectDictRandCropByLabelClassesDRandCropByLabelClassesDictc                   @  sR   e Zd ZdZejZejddfdddZe	j
jdddZ
d d!ddZd"ddZdS )#r*   z
    Dictionary-based wrapper of :py:class:`monai.transforms.Pad`.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.
    Fkeysr
   padderr   moder   allow_missing_keysboollazyreturnNonec                 C  s\   t | || t| | |du r t|ts tdt| d|| _t|t	| j
| _dS )aj  
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            padder: pad transform for the input image.
            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 ``"constant"``.
                See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
                https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
                It also can be a sequence of string, 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.
        TzD'padder' must inherit LazyTrait if lazy is True 'padder' is of type()N)r#   __init__r"   
isinstancer    
ValueErrortypera   r)   lenr`   rb   )selfr`   ra   rb   rc   re    ro   e/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/croppad/dictionary.pyri   {   s   zPadd.__init__valuec                 C  "   || _ t| jtr|| j_d S d S N)_lazyrj   ra   r"   re   rn   rq   ro   ro   rp   re         z	Padd.lazyNdataMapping[Hashable, torch.Tensor]bool | Nonedict[Hashable, torch.Tensor]c                 C  s   t |}|d u r| jn|}|du r!t| jts!tdt| j | || jD ]"\}}t| jtr?| j|| ||d||< q(| j|| |d||< q(|S )NTzN'self.padder' must inherit LazyTrait if lazy is True 'self.padder' is of type()rb   re   )rb   )	dictre   rj   ra   r    rk   rl   key_iteratorrb   )rn   rw   re   dlazy_keymro   ro   rp   __call__   s   zPadd.__call__Mapping[Hashable, MetaTensor]dict[Hashable, MetaTensor]c                 C  0   t |}| |D ]}| j|| ||< q	|S rs   )r{   r|   ra   inversern   rw   r}   r   ro   ro   rp   r         zPadd.inverse)r`   r
   ra   r   rb   r   rc   rd   re   rd   rf   rg   rq   rd   rf   rg   rs   rw   rx   re   ry   rf   rz   rw   r   rf   r   )__name__
__module____qualname____doc__r   backendr(   CONSTANTri   r"   re   setterr   r   ro   ro   ro   rp   r*   q   s    r*   c                   @  s(   e Zd ZdZejejddfdddZdS )r+   a1  
    Dictionary-based wrapper of :py:class:`monai.transforms.SpatialPad`.
    Performs padding to the data, symmetric for all sides or all on one side for each dimension.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.
    Fr`   r
   spatial_sizeSequence[int] | intmethodstrrb   r   rc   rd   re   rf   rg   c           	      K  s0   t ||fd|i|}tj| |||||d dS )aW  
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            spatial_size: the spatial size of output data after padding, if a dimension of the input
                data size is larger than the pad size, will not pad that dimension.
                If its components have non-positive values, the corresponding size of input image will be used.
                for example: if the spatial size of input data is [30, 30, 30] and `spatial_size=[32, 25, -1]`,
                the spatial size of output data will be [32, 30, 30].
            method: {``"symmetric"``, ``"end"``}
                Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``.
            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 ``"constant"``.
                See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
                https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
                It also can be a sequence of string, 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.
            kwargs: other arguments for the `np.pad` or `torch.pad` function.
                note that `np.pad` treats channel dimension as the first dimension.

        re   ra   rb   rc   re   N)r   r*   ri   )	rn   r`   r   r   rb   rc   re   kwargsra   ro   ro   rp   ri         "zSpatialPadd.__init__N)r`   r
   r   r   r   r   rb   r   rc   rd   re   rd   rf   rg   )	r   r   r   r   r'   	SYMMETRICr(   r   ri   ro   ro   ro   rp   r+      s    r+   c                   @  s*   e Zd ZdZejZejddfdddZdS )r,   a  
    Pad the input data by adding specified borders to every dimension.
    Dictionary-based wrapper of :py:class:`monai.transforms.BorderPad`.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.
    Fr`   r
   spatial_borderr   rb   r   rc   rd   re   rf   rg   c                 K  s.   t d||d|}tj| |||||d dS )a#  
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            spatial_border: specified size for every spatial border. it can be 3 shapes:

                - single int number, pad all the borders with the same size.
                - length equals the length of image shape, pad every spatial dimension separately.
                  for example, image shape(CHW) is [1, 4, 4], spatial_border is [2, 1],
                  pad every border of H dim with 2, pad every border of W dim with 1, result shape is [1, 8, 6].
                - length equals 2 x (length of image shape), pad every border of every dimension separately.
                  for example, image shape(CHW) is [1, 4, 4], spatial_border is [1, 2, 3, 4], pad top of H dim with 1,
                  pad bottom of H dim with 2, pad left of W dim with 3, pad right of W dim with 4.
                  the result shape is [1, 7, 11].

            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 ``"constant"``.
                See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
                https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
                It also can be a sequence of string, 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.
            kwargs: other arguments for the `np.pad` or `torch.pad` function.
                note that `np.pad` treats channel dimension as the first dimension.

        )r   re   r   Nro   )r   r*   ri   )rn   r`   r   rb   rc   re   r   ra   ro   ro   rp   ri      s   %zBorderPadd.__init__N)r`   r
   r   r   rb   r   rc   rd   re   rd   rf   rg   )	r   r   r   r   r   r   r(   r   ri   ro   ro   ro   rp   r,      s    r,   c                   @  s.   e Zd ZdZejZejej	ddfdddZ
dS )r-   a  
    Pad the input data, so that the spatial sizes are divisible by `k`.
    Dictionary-based wrapper of :py:class:`monai.transforms.DivisiblePad`.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.
    Fr`   r
   kr   rb   r   r   r   rc   rd   re   rf   rg   c           	      K  s0   t d|||d|}tj| |||||d dS )a  
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            k: the target k for each spatial dimension.
                if `k` is negative or 0, the original size is preserved.
                if `k` is an int, the same `k` be applied to all the input spatial dimensions.
            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 ``"constant"``.
                See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
                https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
                It also can be a sequence of string, each element corresponds to a key in ``keys``.
            method: {``"symmetric"``, ``"end"``}
                Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``.
            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.

        See also :py:class:`monai.transforms.SpatialPad`

        )r   r   re   r   Nro   )r   r*   ri   )	rn   r`   r   rb   r   rc   re   r   ra   ro   ro   rp   ri   #  r   zDivisiblePadd.__init__N)r`   r
   r   r   rb   r   r   r   rc   rd   re   rd   rf   rg   )r   r   r   r   r   r   r(   r   r'   r   ri   ro   ro   ro   rp   r-     s    r-   c                   @  sJ   e Zd ZdZejZddd
dZejj	dddZdd ddZ
d!ddZdS )"r.   aP  
    Dictionary-based wrapper of abstract class :py:class:`monai.transforms.Crop`.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: :py:class:`monai.transforms.compose.MapTransform`
        cropper: crop transform for the input image.
        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.
    Fr`   r
   cropperr   rc   rd   re   c                 C  s$   t | || t| | || _d S rs   )r#   ri   r"   r   rn   r`   r   rc   re   ro   ro   rp   ri   Z  s   
zCropd.__init__rq   rf   rg   c                 C  rr   rs   )rt   rj   r   r"   re   ru   ro   ro   rp   re   _  rv   z
Cropd.lazyNrw   rx   ry   rz   c                 C  sD   t |}|d u r| jn|}| |D ]}| j|| |d||< q|S Nre   )r{   re   r|   r   )rn   rw   re   r}   r~   r   ro   ro   rp   r   e  s
   zCropd.__call__r   r   c                 C  r   rs   )r{   r|   r   r   r   ro   ro   rp   r   l  r   zCropd.inverseFFr`   r
   r   r   rc   rd   re   rd   r   rs   r   r   )r   r   r   r   r   r   ri   r"   re   r   r   r   ro   ro   ro   rp   r.   I  s    r.   c                      sP   e Zd ZdZejZdd  fd
dZd!d" fddZd#ddZd$d%ddZ	  Z
S )&r/   a/  
    Base class for random crop transform.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: :py:class:`monai.transforms.compose.MapTransform`
        cropper: random crop transform for the input image.
        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.
    Fr`   r
   r   r   rc   rd   re   c                   s   t  j||||d d S )Nr   rc   re   )superri   r   	__class__ro   rp   ri     s   zRandCropd.__init__Nseed
int | Nonestatenp.random.RandomState | Nonerf   c                   s,   t  || t| jtr| j|| | S rs   )r   set_random_staterj   r   r$   rn   r   r   r   ro   rp   r     s   zRandCropd.set_random_stateimg_sizeSequence[int]rg   c                 C  s    t | jtr| j| d S d S rs   )rj   r   r$   	randomize)rn   r   ro   ro   rp   r     s   zRandCropd.randomizerw   rx   ry   rz   c                 C  s   t |}|| | }| t|tr| n|jdd   |d u r%| jn|}|du r;t| jt	s;t
dt| j | |D ]%}t| jtrLddini }t| jt	rX||d< | j|| fi |||< q@|S )N   TzP'self.cropper' must inherit LazyTrait if lazy is True 'self.cropper' is of type(r   Fre   )r{   	first_keyr   rj   r   peek_pending_shapeshapere   r   r    rk   rl   r|   r$   )rn   rw   re   r}   Z
first_itemr~   r   r   ro   ro   rp   r     s    &zRandCropd.__call__r   r   NN)r   r   r   r   rf   r/   )r   r   rf   rg   rs   r   )r   r   r   r   r   r   ri   r   r   r   __classcell__ro   ro   r   rp   r/   s  s    
r/   c                      s2   e Zd ZdZ							dd fddZ  ZS )r0   aR  
    Dictionary-based wrapper of :py:class:`monai.transforms.SpatialCrop`.
    General purpose cropper to produce sub-volume region of interest (ROI).
    If a dimension of the expected ROI size is larger than the input image size, will not crop that dimension.
    So the cropped result may be smaller than the expected ROI, and the cropped results of several images may
    not have exactly the same shape.
    It can support to crop ND spatial (channel-first) data.

    The cropped region can be parameterised in various ways:
        - a list of slices for each spatial dimension (allows for use of -ve indexing and `None`)
        - a spatial center and size
        - the start and end coordinates of the ROI

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.
    NFr`   r
   
roi_centerSequence[int] | int | Noneroi_size	roi_startroi_end
roi_slicesSequence[slice] | Nonerc   rd   re   rf   rg   c	           
        s,   t ||||||d}	t j||	||d dS )ab  
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            roi_center: voxel coordinates for center of the crop ROI.
            roi_size: size of the crop ROI, if a dimension of ROI size is larger than image size,
                will not crop that dimension of the image.
            roi_start: voxel coordinates for start of the crop ROI.
            roi_end: voxel coordinates for end of the crop ROI, if a coordinate is out of image,
                use the end coordinate of image.
            roi_slices: list of slices for each of the 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   r   N)r   r   ri   )
rn   r`   r   r   r   r   r   rc   re   r   r   ro   rp   ri     s   zSpatialCropd.__init__)NNNNNFF)r`   r
   r   r   r   r   r   r   r   r   r   r   rc   rd   re   rd   rf   rg   r   r   r   r   ri   r   ro   ro   r   rp   r0     s    r0   c                      s&   e Zd ZdZ	dd fddZ  ZS )r1   a  
    Dictionary-based wrapper of :py:class:`monai.transforms.CenterSpatialCrop`.
    If a dimension of the expected ROI size is larger than the input image size, will not crop that dimension.
    So the cropped result may be smaller than the expected ROI, and the cropped results of several images may
    not have exactly the same shape.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: monai.transforms.MapTransform
        roi_size: the size of the crop region e.g. [224,224,128]
            if a dimension of ROI size is larger than image size, will not crop that dimension of the image.
            If its components have non-positive values, the corresponding size of input image will be used.
            for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`,
            the spatial size of output data will be [32, 40, 40].
        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.
    Fr`   r
   r   r   rc   rd   re   rf   rg   c                   $   t ||d}t j||||d d S Nr   r   )r   r   ri   )rn   r`   r   rc   re   r   r   ro   rp   ri     s   zCenterSpatialCropd.__init__r   )
r`   r
   r   r   rc   rd   re   rd   rf   rg   r   ro   ro   r   rp   r1     s    r1   c                      s(   e Zd ZdZ		dd fddZ  ZS )r2   aj  
    Dictionary-based wrapper of :py:class:`monai.transforms.CenterScaleCrop`.
    Note: as using the same scaled ROI to crop, all the input data specified by `keys` should have
    the same spatial shape.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: monai.transforms.MapTransform
        roi_scale: specifies the expected scale of image size to crop. e.g. [0.3, 0.4, 0.5] or a number for all dims.
            If its components have non-positive values, will use `1.0` instead, which means the input image size.
        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.
    Fr`   r
   	roi_scaleSequence[float] | floatrc   rd   re   rf   rg   c                   r   r   )r   r   ri   )rn   r`   r   rc   re   r   r   ro   rp   ri     s   zCenterScaleCropd.__init__r   )
r`   r
   r   r   rc   rd   re   rd   rf   rg   r   ro   ro   r   rp   r2     s
    r2   c                      .   e Zd ZdZ					dd fddZ  ZS )r4   a  
    Dictionary-based version :py:class:`monai.transforms.RandSpatialCrop`.
    Crop image with random size or specific size ROI. It can crop at a random position as
    center or at the image center. And allows to set the minimum and maximum size to limit the randomly
    generated ROI. Suppose all the expected fields specified by `keys` have same shape.

    Note: even `random_size=False`, if a dimension of the expected ROI size is larger than the input image size,
    will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped
    results of several images may not have exactly the same shape.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: monai.transforms.MapTransform
        roi_size: if `random_size` is True, it specifies the minimum crop region.
            if `random_size` is False, it specifies the expected ROI size to crop. e.g. [224, 224, 128]
            if a dimension of ROI size is larger than image size, will not crop that dimension of the image.
            If its components have non-positive values, the corresponding size of input image will be used.
            for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`,
            the spatial size of output data will be [32, 40, 40].
        max_roi_size: if `random_size` is True and `roi_size` specifies the min crop region size, `max_roi_size`
            can specify the max crop region size. if None, defaults to the input image size.
            if its components have non-positive values, the corresponding size of input image will be used.
        random_center: crop at random position as center or the image center.
        random_size: crop with random size or specific size ROI.
            if True, the actual size is sampled from:
            `randint(roi_scale * image spatial size, max_roi_scale * image spatial size + 1)`.
        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.
    NTFr`   r
   r   r   max_roi_sizer   random_centerrd   random_sizerc   re   rf   rg   c           	        *   t |||||d}t j||||d d S r   )r   r   ri   )	rn   r`   r   r   r   r   rc   re   r   r   ro   rp   ri   /     
zRandSpatialCropd.__init__NTFFF)r`   r
   r   r   r   r   r   rd   r   rd   rc   rd   re   rd   rf   rg   r   ro   ro   r   rp   r4     s    %r4   c                      r   )r3   aB  
    Dictionary-based version :py:class:`monai.transforms.RandScaleCrop`.
    Crop image with random size or specific size ROI.
    It can crop at a random position as center or at the image center.
    And allows to set the minimum and maximum scale of image size to limit the randomly generated ROI.
    Suppose all the expected fields specified by `keys` have same shape.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: monai.transforms.MapTransform
        roi_scale: if `random_size` is True, it specifies the minimum crop size: `roi_scale * image spatial size`.
            if `random_size` is False, it specifies the expected scale of image size to crop. e.g. [0.3, 0.4, 0.5].
            If its components have non-positive values, will use `1.0` instead, which means the input image size.
        max_roi_scale: if `random_size` is True and `roi_scale` specifies the min crop region size, `max_roi_scale`
            can specify the max crop region size: `max_roi_scale * image spatial size`.
            if None, defaults to the input image size. if its components have non-positive values,
            will use `1.0` instead, which means the input image size.
        random_center: crop at random position as center or the image center.
        random_size: crop with random size or specified size ROI by `roi_scale * image spatial size`.
            if True, the actual size is sampled from:
            `randint(roi_scale * image spatial size, max_roi_scale * image spatial size + 1)`.
        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.
    NTFr`   r
   r   r   max_roi_scaleSequence[float] | float | Noner   rd   r   rc   re   rf   rg   c           	        r   r   )r   r   ri   )	rn   r`   r   r   r   r   rc   re   r   r   ro   rp   ri   Z  r   zRandScaleCropd.__init__r   )r`   r
   r   r   r   r   r   rd   r   rd   rc   rd   re   rd   rf   rg   r   ro   ro   r   rp   r3   =  s     r3   c                   @  sX   e Zd ZdZejZ					d"d#ddZejj	d$ddZd%d&ddZ
	d%d'd d!ZdS )(r5   a	  
    Dictionary-based version :py:class:`monai.transforms.RandSpatialCropSamples`.
    Crop image with random size or specific size ROI to generate a list of N samples.
    It can crop at a random position as center or at the image center. And allows to set
    the minimum size to limit the randomly generated ROI. Suppose all the expected fields
    specified by `keys` have same shape, and add `patch_index` to the corresponding metadata.
    It will return a list of dictionaries for all the cropped images.

    Note: even `random_size=False`, if a dimension of the expected ROI size is larger than the input image size,
    will not crop that dimension. So the cropped result may be smaller than the expected ROI, and the cropped
    results of several images may not have exactly the same shape.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: monai.transforms.MapTransform
        roi_size: if `random_size` is True, it specifies the minimum crop region.
            if `random_size` is False, it specifies the expected ROI size to crop. e.g. [224, 224, 128]
            if a dimension of ROI size is larger than image size, will not crop that dimension of the image.
            If its components have non-positive values, the corresponding size of input image will be used.
            for example: if the spatial size of input data is [40, 40, 40] and `roi_size=[32, 64, -1]`,
            the spatial size of output data will be [32, 40, 40].
        num_samples: number of samples (crop regions) to take in the returned list.
        max_roi_size: if `random_size` is True and `roi_size` specifies the min crop region size, `max_roi_size`
            can specify the max crop region size. if None, defaults to the input image size.
            if its components have non-positive values, the corresponding size of input image will be used.
        random_center: crop at random position as center or the image center.
        random_size: crop with random size or specific size ROI.
            The actual size is sampled from `randint(roi_size, img_size)`.
        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.

    Raises:
        ValueError: When ``num_samples`` is nonpositive.

    NTFr`   r
   r   r   num_samplesintr   r   r   rd   r   rc   re   rf   rg   c	           	      C  s4   t | || t| | t||||||d| _d S r   )r#   ri   r"   r   r   )	rn   r`   r   r   r   r   r   rc   re   ro   ro   rp   ri     s
   z RandSpatialCropSamplesd.__init__rq   c                 C     || _ || j_d S rs   rt   r   re   ru   ro   ro   rp   re        zRandSpatialCropSamplesd.lazyrw   
Any | Nonec                 C  s   | j jtdd| _d S )Nuint32)dtype)Rrandintr&   sub_seed)rn   rw   ro   ro   rp   r     s   z!RandSpatialCropSamplesd.randomizerx   ry   "list[dict[Hashable, torch.Tensor]]c                   s    fddt | jjD }t | jjD ]}t  t| jD ]}t | || |< q!q|   |d u r:| jn|}| 	t
 D ]"}| jjt| jd t| j | |dD ]
\}}||| |< qZqC|S )Nc                      g | ]}t  qS ro   r{   .0_rw   ro   rp   
<listcomp>      z4RandSpatialCropSamplesd.__call__.<locals>.<listcomp>)r   r   )ranger   r   setr`   
differencer   r   re   r|   r{   r   r   r   	enumeratern   rw   re   retir   r~   imro   r   rp   r     s   z RandSpatialCropSamplesd.__call__r   )r`   r
   r   r   r   r   r   r   r   rd   r   rd   rc   rd   re   rd   rf   rg   r   rs   )rw   r   rf   rg   rw   rx   re   ry   rf   r   )r   r   r   r   r   r   ri   r"   re   r   r   r   ro   ro   ro   rp   r5   h  s    'r5   c                
      sd   e Zd ZdZeddddejddddf
d+ fddZej	j
d,d!d"Z	ed#d$ Zd-d.d)d*Z  ZS )/r6   a  
    Dictionary-based version :py:class:`monai.transforms.CropForeground`.
    Crop only the foreground object of the expected images.
    The typical usage is to help training and evaluation if the valid part is small in the whole medical image.
    The valid part can be determined by any field in the data with `source_key`, for example:
    - Select values > 0 in image field as the foreground and crop on all fields specified by `keys`.
    - Select label = 3 in label field as the foreground to crop on all fields specified by `keys`.
    - Select label > 0 in the third channel of a One-Hot label field as the foreground to crop all `keys` fields.
    Users can define arbitrary function to select expected foreground from the whole source image or specified
    channels. And it can also add margin to every dim of the bounding box of foreground object.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.
    Nr   Fr   Zforeground_start_coordZforeground_end_coordr`   r
   
source_keyr   	select_fnr   channel_indicesIndexSelection | Nonemarginr   allow_smallerrd   k_divisiblerb   r   start_coord_key
str | Noneend_coord_keyrc   re   rf   rg   c              	     sX   || _ |	| _|
| _td||||||d|}t j||||d t|t| j| _	dS )a	  
        Args:
            keys: keys of the corresponding items to be transformed.
                See also: :py:class:`monai.transforms.compose.MapTransform`
            source_key: data source to generate the bounding box of foreground, can be image or label, etc.
            select_fn: function to select expected foreground, default is to select values > 0.
            channel_indices: if defined, select foreground only on the specified channels
                of image. if None, select foreground on the whole image.
            margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims.
            allow_smaller: when computing box size with `margin`, whether to allow the image edges to be smaller than the
                final box edges. If `False`, part of a padded output box might be outside of the original image, if `True`,
                the image edges will be used as the box edges. Default to `False`.
                The default value is changed from `True` to `False` in v1.5.0.
            k_divisible: make each spatial dimension to be divisible by k, default to 1.
                if `k_divisible` is an int, the same `k` be applied to all the input spatial dimensions.
            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 ``"constant"``.
                See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
                https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
                it also can be a sequence of string, each element corresponds to a key in ``keys``.
            start_coord_key: key to record the start coordinate of spatial bounding box for foreground.
            end_coord_key: key to record the end coordinate of spatial bounding box for foreground.
            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.
            pad_kwargs: other arguments for the `np.pad` or `torch.pad` function.
                note that `np.pad` treats channel dimension as the first dimension.

        )r   r   r   r   r   re   r   Nro   )
r   r   r   r   r   ri   r)   rm   r`   rb   )rn   r`   r   r   r   r   r   r   rb   r   r   rc   re   
pad_kwargsr   r   ro   rp   ri     s   .	zCropForegroundd.__init__rq   c                 C  r   rs   r   ru   ro   ro   rp   re     r   zCropForegroundd.lazyc                 C     dS NTro   rn   ro   ro   rp   requires_current_data     z%CropForegroundd.requires_current_datarw   rx   ry   rz   c           	      C  s   t |}|  | jj|| j d\}}| jd ur||| j< | jd ur&||| j< |d u r-| jn|}| || jD ]\}}| jj	|| ||||d||< q6|S )N)img)r   	box_startbox_endrb   re   )
r{   r   compute_bounding_boxr   r   r   re   r|   rb   crop_pad)	rn   rw   re   r}   r   r   r~   r   r   ro   ro   rp   r     s   



 zCropForegroundd.__call__)r`   r
   r   r   r   r   r   r   r   r   r   rd   r   r   rb   r   r   r   r   r   rc   rd   re   rd   rf   rg   r   rs   r   )r   r   r   r   r%   r(   r   ri   r"   re   r   propertyr   r   r   ro   ro   r   rp   r6     s$    =
r6   c                      sh   e Zd ZdZejZ			d'd(ddZ	d)d* fddZd+ddZe	j
jd,dd Z
	d-d.d%d&Z  ZS )/r7   aG  
    Samples a list of `num_samples` image patches according to the provided `weight_map`.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: :py:class:`monai.transforms.compose.MapTransform`
        w_key: key for the weight map. The corresponding value will be used as the sampling weights,
            it should be a single-channel array in size, for example, `(1, spatial_dim_0, spatial_dim_1, ...)`
        spatial_size: the spatial size of the image patch e.g. [224, 224, 128].
            If its components have non-positive values, the corresponding size of `img` will be used.
        num_samples: number of samples (image patches) to take in the returned list.
        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.RandWeightedCrop`
    r   Fr`   r
   w_keyr   r   r   r   r   rc   rd   re   c                 C  s4   t | || t| | || _t|||d| _d S r   )r#   ri   r"   r   r   r   )rn   r`   r   r   r   rc   re   ro   ro   rp   ri   <  s   	zRandWeightedCropd.__init__Nr   r   r   r   rf   c                       t  || | j|| | S rs   r   r   r   r   r   ro   rp   r   J     z"RandWeightedCropd.set_random_state
weight_mapr   rg   c                 C  s   | j | d S rs   r   r   )rn   r  ro   ro   rp   r   Q  s   zRandWeightedCropd.randomizerq   c                 C  r   rs   r   ru   ro   ro   rp   re   T  r   zRandWeightedCropd.lazyrw   rx   ry   r   c                   s    fddt | jjD }t | jjD ]}t  t| jD ]}t | || |< q!q| j | j d |d u r?| j	n|}| 
 D ]}t| j | d|dD ]
\}}||| |< qTqF|S )Nc                   r   ro   r   r   r   ro   rp   r   ]  r   z.RandWeightedCropd.__call__.<locals>.<listcomp>)r  Fr   re   )r   r   r   r   r`   r   r   r   r   re   r|   r   r   ro   r   rp   r   Y  s    zRandWeightedCropd.__call__)r   FF)r`   r
   r   r   r   r   r   r   rc   rd   re   rd   r   )r   r   r   r   rf   r7   )r  r   rf   rg   r   rs   r   )r   r   r   r   r   r   ri   r   r   r"   re   r   r   r   ro   ro   r   rp   r7   $  s    
r7   c                      s   e Zd ZdZejZ										d8d9ddZ	d:d; fd#d$Z				d<d=d+d,Ze	j
jd>d.d/Z
ed0d1 Z	d?d@d6d7Z  ZS )Ar8   a(  
    Dictionary-based version :py:class:`monai.transforms.RandCropByPosNegLabel`.
    Crop random fixed sized regions with the center being a foreground or background voxel
    based on the Pos Neg Ratio.
    Suppose all the expected fields specified by `keys` have same shape,
    and add `patch_index` to the corresponding metadata.
    And will return a list of dictionaries for all the cropped images.

    If a dimension of the expected spatial size is larger than the input image size,
    will not crop that dimension. So the cropped result may be smaller than the expected size,
    and the cropped results of several images may not have exactly the same shape.
    And if the crop ROI is partly out of the image, will automatically adjust the crop center
    to ensure the valid crop ROI.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: :py:class:`monai.transforms.compose.MapTransform`
        label_key: name of key for label image, this will be used for finding foreground/background.
        spatial_size: the spatial size of the crop region e.g. [224, 224, 128].
            if a dimension of ROI size is larger than image size, will not crop that dimension of the image.
            if its components have non-positive values, the corresponding size of `data[label_key]` will be used.
            for example: if the spatial size of input data is [40, 40, 40] and `spatial_size=[32, 64, -1]`,
            the spatial size of output data will be [32, 40, 40].
        pos: used with `neg` together to calculate the ratio ``pos / (pos + neg)`` for the probability
            to pick a foreground voxel as a center rather than a background voxel.
        neg: used with `pos` together to calculate the ratio ``pos / (pos + neg)`` for the probability
            to pick a foreground voxel as a center rather than a background voxel.
        num_samples: number of samples (crop regions) to take in each list.
        image_key: if image_key is not None, use ``label == 0 & image > image_threshold`` to select
            the negative sample(background) center. so the crop center will only exist on valid image area.
        image_threshold: if enabled image_key, use ``image > image_threshold`` to determine
            the valid image content area.
        fg_indices_key: if provided pre-computed foreground indices of `label`, will ignore above `image_key` and
            `image_threshold`, and randomly select crop centers based on them, need to provide `fg_indices_key`
            and `bg_indices_key` together, expect to be 1 dim array of spatial indices after flattening.
            a typical usage is to call `FgBgToIndicesd` transform first and cache the results.
        bg_indices_key: if provided pre-computed background indices of `label`, will ignore above `image_key` and
            `image_threshold`, and randomly select crop centers based on them, need to provide `fg_indices_key`
            and `bg_indices_key` together, expect to be 1 dim array of spatial indices after flattening.
            a typical usage is to call `FgBgToIndicesd` transform first and cache the results.
        allow_smaller: if `False`, an exception will be raised if the image is smaller than
            the requested ROI in any dimension. If `True`, any smaller dimensions will be set to
            match the cropped size (i.e., no cropping in that dimension).
        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.

    Raises:
        ValueError: When ``pos`` or ``neg`` are negative.
        ValueError: When ``pos=0`` and ``neg=0``. Incompatible values.

          ?r   N        Fr`   r
   	label_keyr   r   r   posfloatnegr   r   	image_keyr   image_thresholdfg_indices_keybg_indices_keyr   rd   rc   re   rf   rg   c              	   C  sN   t | || t| | || _|| _|	| _|
| _t|||||||d| _d S )N)r   r  r	  r   r  r   re   )	r#   ri   r"   r  r
  r  r  r   r   )rn   r`   r  r   r  r	  r   r
  r  r  r  r   rc   re   ro   ro   rp   ri     s   zRandCropByPosNegLabeld.__init__r   r   r   r   c                   r   rs   r   r   r   ro   rp   r     r   z'RandCropByPosNegLabeld.set_random_statelabeltorch.Tensor | None
fg_indicesNdarrayOrTensor | None
bg_indicesimagec                 C  s   | j j||||d d S )N)r  r  r  r  r  )rn   r  r  r  r  ro   ro   rp   r     s   z RandCropByPosNegLabeld.randomizerq   c                 C  r   rs   r   ru   ro   ro   rp   re     r   zRandCropByPosNegLabeld.lazyc                 C  r   r   ro   r   ro   ro   rp   r     r   z,RandCropByPosNegLabeld.requires_current_datarw   rx   ry   r   c           
        s   t |  | jd } | jd }|  | j|| | j  fddt| j	j
D }t| j	j
D ]}t  t| jD ]}t | || |< qCq5|d u rX| jn|}|  D ]}t| j	 | d|dD ]
\}}	|	|| |< qmq_|S )Nc                   r   ro   r   r   r}   ro   rp   r     r   z3RandCropByPosNegLabeld.__call__.<locals>.<listcomp>Fr  )r{   popr  r  r   getr  r
  r   r   r   r   r`   r   r   re   r|   r   )
rn   rw   re   r  r  r   r   r   r~   r   ro   r  rp   r     s     zRandCropByPosNegLabeld.__call__)
r  r  r   Nr  NNFFF)r`   r
   r  r   r   r   r  r  r	  r  r   r   r
  r   r  r  r  r   r  r   r   rd   rc   rd   re   rd   rf   rg   r   )r   r   r   r   rf   r8   )NNNN)
r  r  r  r  r  r  r  r  rf   rg   r   rs   r   )r   r   r   r   r   r   ri   r   r   r"   re   r   r   r   r   r   ro   ro   r   rp   r8   k  s6    7!		
r8   c                      s   e Zd ZdZejZ											d:d;d d!Z	d<d= fd%d&Z	d<d>d-d.Ze	j
jd?d0d1Z
ed2d3 Zd@dAd8d9Z  ZS )Br;   a  
    Dictionary-based version :py:class:`monai.transforms.RandCropByLabelClasses`.
    Crop random fixed sized regions with the center being a class based on the specified ratios of every class.
    The label data can be One-Hot format array or Argmax data. And will return a list of arrays for all the
    cropped images. For example, crop two (3 x 3) arrays from (5 x 5) array with `ratios=[1, 2, 3, 1]`::

        cropper = RandCropByLabelClassesd(
            keys=["image", "label"],
            label_key="label",
            spatial_size=[3, 3],
            ratios=[1, 2, 3, 1],
            num_classes=4,
            num_samples=2,
        )
        data = {
            "image": np.array([
                [[0.0, 0.3, 0.4, 0.2, 0.0],
                [0.0, 0.1, 0.2, 0.1, 0.4],
                [0.0, 0.3, 0.5, 0.2, 0.0],
                [0.1, 0.2, 0.1, 0.1, 0.0],
                [0.0, 0.1, 0.2, 0.1, 0.0]]
            ]),
            "label": np.array([
                [[0, 0, 0, 0, 0],
                [0, 1, 2, 1, 0],
                [0, 1, 3, 0, 0],
                [0, 0, 0, 0, 0],
                [0, 0, 0, 0, 0]]
            ]),
        }
        result = cropper(data)

        The 2 randomly cropped samples of `label` can be:
        [[0, 1, 2],     [[0, 0, 0],
         [0, 1, 3],      [1, 2, 1],
         [0, 0, 0]]      [1, 3, 0]]

    If a dimension of the expected spatial size is larger than the input image size,
    will not crop that dimension. So the cropped result may be smaller than expected size, and the cropped
    results of several images may not have exactly same shape.
    And if the crop ROI is partly out of the image, will automatically adjust the crop center to ensure the
    valid crop ROI.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: :py:class:`monai.transforms.compose.MapTransform`
        label_key: name of key for label image, this will be used for finding indices of every class.
        spatial_size: the spatial size of the crop region e.g. [224, 224, 128].
            if a dimension of ROI size is larger than image size, will not crop that dimension of the image.
            if its components have non-positive values, the corresponding size of `label` will be used.
            for example: if the spatial size of input data is [40, 40, 40] and `spatial_size=[32, 64, -1]`,
            the spatial size of output data will be [32, 40, 40].
        ratios: specified ratios of every class in the label to generate crop centers, including background class.
            if None, every class will have the same ratio to generate crop centers.
        num_classes: number of classes for argmax label, not necessary for One-Hot label.
        num_samples: number of samples (crop regions) to take in each list.
        image_key: if image_key is not None, only return the indices of every class that are within the valid
            region of the image (``image > image_threshold``).
        image_threshold: if enabled `image_key`, use ``image > image_threshold`` to
            determine the valid image content area and select class indices only in this area.
        indices_key: if provided pre-computed indices of every class, will ignore above `image` and
            `image_threshold`, and randomly select crop centers based on them, expect to be 1 dim array
            of spatial indices after flattening. a typical usage is to call `ClassesToIndices` transform first
            and cache the results for better performance.
        allow_smaller: if `False`, an exception will be raised if the image is smaller than
            the requested ROI in any dimension. If `True`, any smaller dimensions will remain
            unchanged.
        allow_missing_keys: don't raise exception if key is missing.
        warn: if `True` prints a warning if a class is not present in the label.
        max_samples_per_class: maximum length of indices in each class to reduce memory consumption.
            Default is None, no subsampling.
        lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
    Nr   r  FTr`   r
   r  r   r   r   ratioslist[float | int] | Nonenum_classesr   r   r   r
  r   r  r  indices_keyr   rd   rc   warnmax_samples_per_classre   rf   rg   c                 C  sL   t | || t| | || _|| _|	| _t||||||
|||d	| _d S )N)	r   r  r  r   r  r   r  r  re   )r#   ri   r"   r  r
  r  r   r   )rn   r`   r  r   r  r  r   r
  r  r  r   rc   r  r  re   ro   ro   rp   ri   E  s    z RandCropByLabelClassesd.__init__r   r   r   c                   r   rs   r   r   r   ro   rp   r   g  r   z(RandCropByLabelClassesd.set_random_stater  torch.Tensorindiceslist[NdarrayOrTensor] | Noner  r  c                 C  s   | j j|||d d S )N)r  r  r  r  )rn   r  r  r  ro   ro   rp   r   n  s   z!RandCropByLabelClassesd.randomizerq   c                 C  r   rs   r   ru   ro   ro   rp   re   s  r   zRandCropByLabelClassesd.lazyc                 C  r   r   ro   r   ro   ro   rp   r   x  r   z-RandCropByLabelClassesd.requires_current_datarw   Mapping[Hashable, Any]ry   r   c                   s   t | |  | j | jd  | j  fddt| jj	D }t| jj	D ]}t
  t
| jD ]}t | || |< q9q+|d u rN| jn|}|  D ]}t| j | d|dD ]
\}}||| |< qcqU|S )Nc                   r   ro   r   r   r  ro   rp   r     r   z4RandCropByLabelClassesd.__call__.<locals>.<listcomp>Fr  )r{   r   r  r  r  r  r
  r   r   r   r   r`   r   r   re   r|   r   r   ro   r  rp   r   |  s   ( z RandCropByLabelClassesd.__call__)NNr   Nr  NFFTNF)r`   r
   r  r   r   r   r  r  r  r   r   r   r
  r   r  r  r  r   r   rd   rc   rd   r  rd   r  r   re   rd   rf   rg   r   )r   r   r   r   rf   r;   )r  r  r  r  r  r  rf   rg   r   rs   )rw   r   re   ry   rf   r   )r   r   r   r   r   r   ri   r   r   r"   re   r   r   r   r   r   ro   ro   r   rp   r;     s0    M#
r;   c                      s0   e Zd ZdZejdejdfd fddZ  Z	S )r9   a  
    Dictionary-based wrapper of :py:class:`monai.transforms.ResizeWithPadOrCrop`.

    This transform is capable of lazy execution. See the :ref:`Lazy Resampling topic<lazy_resampling>`
    for more information.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: monai.transforms.MapTransform
        spatial_size: the spatial size of output data after padding or crop.
            If has non-positive values, the corresponding size of input image will be used (no 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 ``"constant"``.
            See also: https://numpy.org/doc/1.18/reference/generated/numpy.pad.html
            https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
            It also can be a sequence of string, each element corresponds to a key in ``keys``.
        allow_missing_keys: don't raise exception if key is missing.
        method: {``"symmetric"``, ``"end"``}
            Pad image symmetrically on every side or only pad at the end sides. Defaults to ``"symmetric"``.
        lazy: a flag to indicate whether this transform should execute lazily or not. Defaults to False.
        pad_kwargs: other arguments for the `np.pad` or `torch.pad` function.
            note that `np.pad` treats channel dimension as the first dimension.

    Fr`   r
   r   r   rb   r   rc   rd   r   r   re   rf   rg   c           	        s6   t d||d|d|i}t j|||||d d S )N)r   r   re   r   ro   )r   r   ri   )	rn   r`   r   rb   rc   r   re   r   Z
padcropperr   ro   rp   ri     s   


zResizeWithPadOrCropd.__init__)r`   r
   r   r   rb   r   rc   rd   r   r   re   rd   rf   rg   )
r   r   r   r   r(   r   r'   r   ri   r   ro   ro   r   rp   r9     s    r9   c                      s:   e Zd ZdZejZdedfd fddZdddZ  Z	S )r:   a  
    Dictionary-based wrapper of :py:class:`monai.transforms.BoundingRect`.

    Args:
        keys: keys of the corresponding items to be transformed.
            See also: monai.transforms.MapTransform
        bbox_key_postfix: the output bounding box coordinates will be
            written to the value of `{key}_{bbox_key_postfix}`.
        select_fn: function to select expected foreground, default is to select values > 0.
        allow_missing_keys: don't raise exception if key is missing.
    bboxFr`   r
   bbox_key_postfixr   r   r   rc   rd   c                   s$   t  || t|d| _|| _d S )N)r   )r   ri   r   r!  r"  )rn   r`   r"  r   rc   r   ro   rp   ri     s   
zBoundingRectd.__init__rw   "Mapping[Hashable, NdarrayOrTensor]rf   dict[Hashable, NdarrayOrTensor]c                 C  sZ   t |}| |D ]!}| || }| d| j }||v r&td| d|||< q	|S )z]
        See also: :py:class:`monai.transforms.utils.generate_spatial_bounding_box`.
        r   zBounding box data with key z already exists.)r{   r|   r!  r"  KeyError)rn   rw   r}   r   r!  Z
key_to_addro   ro   rp   r     s   
zBoundingRectd.__call__)r`   r
   r"  r   r   r   rc   rd   )rw   r#  rf   r$  )
r   r   r   r   r   r   r%   ri   r   r   ro   ro   r   rp   r:     s    r:   )pr   
__future__r   collections.abcr   r   r   r   copyr   typingr   numpynptorchmonai.configr	   r
   r   monai.config.type_definitionsr   monai.data.meta_tensorr   Zmonai.transforms.croppad.arrayr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   monai.transforms.inverser   monai.transforms.traitsr    r!   monai.transforms.transformr"   r#   r$   monai.transforms.utilsr%   monai.utilsr&   r'   r(   r)   __all__r*   r+   r,   r-   r.   r/   r0   r1   r2   r4   r3   r5   r6   r7   r8   r;   r9   r:   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rP   rQ   rN   rO   rR   rS   rT   rU   rV   rW   rX   rY   r^   r_   rZ   r[   r\   r]   ro   ro   ro   rp   <module>   sn   
L:D/41*1/0+WeG  ,(