U
    Ph 4                     @  s   d dl mZ d dlmZ d dlZd dlmZ d dlmZm	Z	m
Z
 d dlmZmZ d dlmZmZmZmZ ddd	d
dgZG dd dejZG dd	 d	ejZeZe ZZdS )    )annotations)SequenceN)ConvPadPool)	icnr_initpixelshuffle)InterpolateModeUpsampleModeensure_tuple_replook_up_optionUpsampleUpSampleSubpixelUpsampleSubpixelupsampleSubpixelUpSamplec                      sZ   e Zd ZdZdddddejdejdddfddddd	d
dddddddd fddZ  Z	S )r   a  
    Upsamples data by `scale_factor`.
    Supported modes are:

        - "deconv": uses a transposed convolution.
        - "deconvgroup": uses a transposed group convolution.
        - "nontrainable": uses :py:class:`torch.nn.Upsample`.
        - "pixelshuffle": uses :py:class:`monai.networks.blocks.SubpixelUpsample`.

    This operation will cause non-deterministic when ``mode`` is ``UpsampleMode.NONTRAINABLE``.
    Please check the link below for more details:
    https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html#torch.use_deterministic_algorithms
    This module can optionally take a pre-convolution
    (often used to map the number of features from `in_channels` to `out_channels`).
    N   defaultTint
int | NonezSequence[float] | floatzSequence[float] | float | Noneztuple[int] | int | NonezUpsampleMode | strnn.Module | str | Nonestrzbool | NoneboolNone)spatial_dimsin_channelsout_channelsscale_factorkernel_sizesizemodepre_convinterp_modealign_cornersbiasapply_pad_poolreturnc                   sX  t    t||}t|t}|s0|}d }}n4t||}tdd |D }tdd t||D }|tjkr|std| d| 	dt
t
j|f ||p||||||d n|tjkr |std| d|d	kr|}|| dkr|nd
}| 	dt
t
j|f ||||||||d n4|tjkr|dkr||kr|sVtd| d| 	dt
t
j|f ||pr|d
|d n>|d	k	r|dkr| 	d| n|d	kr||krtdt|	}	tjtjtjg}|	|kr||d
  }	| 	dtj||rd	n||	j|
d n@|tjkrD| 	dt||||d |||d ntd| dd	S )a  
        Args:
            spatial_dims: number of spatial dimensions of the input image.
            in_channels: number of channels of the input image.
            out_channels: number of channels of the output image. Defaults to `in_channels`.
            scale_factor: multiplier for spatial size. Has to match input size if it is a tuple. Defaults to 2.
            kernel_size: kernel size used during transposed convolutions. Defaults to `scale_factor`.
            size: spatial size of the output image.
                Only used when ``mode`` is ``UpsampleMode.NONTRAINABLE``.
                In torch.nn.functional.interpolate, only one of `size` or `scale_factor` should be defined,
                thus if size is defined, `scale_factor` will not be used.
                Defaults to None.
            mode: {``"deconv"``, ``"deconvgroup"``, ``"nontrainable"``, ``"pixelshuffle"``}. Defaults to ``"deconv"``.
            pre_conv: a conv block applied before upsampling. Defaults to "default".
                When ``conv_block`` is ``"default"``, one reserved conv layer will be utilized when
                Only used in the "nontrainable" or "pixelshuffle" mode.
            interp_mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``}
                Only used in the "nontrainable" mode.
                If ends with ``"linear"`` will use ``spatial dims`` to determine the correct interpolation.
                This corresponds to linear, bilinear, trilinear for 1D, 2D, and 3D respectively.
                The interpolation mode. Defaults to ``"linear"``.
                See also: https://pytorch.org/docs/stable/generated/torch.nn.Upsample.html
            align_corners: set the align_corners parameter of `torch.nn.Upsample`. Defaults to True.
                Only used in the "nontrainable" mode.
            bias: whether to have a bias term in the default preconv and deconv layers. Defaults to True.
            apply_pad_pool: if True the upsampled tensor is padded then average pooling is applied with a kernel the
                size of `scale_factor` with a stride of 1. See also: :py:class:`monai.networks.blocks.SubpixelUpsample`.
                Only used in the "pixelshuffle" mode.

        r   c                 s  s   | ]}|d  d V  qdS    r   N ).0kr)   r)   S/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/networks/blocks/upsample.py	<genexpr>a   s     z$UpSample.__init__.<locals>.<genexpr>c                 s  s&   | ]\}}|d  |d  d  V  qdS r'   r)   )r*   r+   sr)   r)   r,   r-   b   s     z*in_channels needs to be specified in the 'z' mode.deconv)r   r   r   stridepaddingoutput_paddingr$   Nr(   deconvgroup)r   r   r   r0   r1   r2   groupsr$   r   Zpreconv)r   r   r   r$   z\in the nontrainable mode, if not setting pre_conv, out_channels should equal to in_channels.Zupsample_non_trainable)r   r   r    r#   r   )r   r   r   r   
conv_blockr%   r$   zUnsupported upsampling mode .)super__init__r   r   r
   tuplezipDECONV
ValueError
add_moduler   	CONVTRANSDECONVGROUPNONTRAINABLECONVr	   LINEARBILINEAR	TRILINEARnnr   valuePIXELSHUFFLEr   NotImplementedError)selfr   r   r   r   r   r   r    r!   r"   r#   r$   r%   Zscale_factor_Zup_modekernel_size_r2   r1   r4   Zlinear_mode	__class__r)   r,   r8   +   s    -





   
	zUpSample.__init__)
__name__
__module____qualname____doc__r
   r;   r	   rB   r8   __classcell__r)   r)   rK   r,   r      s   c                
      sF   e Zd ZdZddddddd	d	d
d fddZdddddZ  ZS )r   a  
    Upsample via using a subpixel CNN. This module supports 1D, 2D and 3D input images.
    The module is consisted with two parts. First of all, a convolutional layer is employed
    to increase the number of channels into: ``in_channels * (scale_factor ** dimensions)``.
    Secondly, a pixel shuffle manipulation is utilized to aggregates the feature maps from
    low resolution space and build the super resolution space.
    The first part of the module is not fixed, a sequential layers can be used to replace the
    default single layer.

    See: Shi et al., 2016, "Real-Time Single Image and Video Super-Resolution
    Using a nEfficient Sub-Pixel Convolutional Neural Network."

    See: Aitken et al., 2017, "Checkerboard artifact free sub-pixel convolution".

    The idea comes from:
    https://arxiv.org/abs/1609.05158

    The pixel shuffle mechanism refers to:
    https://pytorch.org/docs/stable/generated/torch.nn.PixelShuffle.html#torch.nn.PixelShuffle.
    and:
    https://github.com/pytorch/pytorch/pull/6340.

    Nr   r   Tr   r   r   r   r   )r   r   r   r   r5   r%   r$   r&   c                   s  t    |dkr"td| d|| _|| _|dkr|p<|}|sJtd||| j  }ttj| jf ||ddd|d| _t| j| j n|d	krt	
 | _n|| _t	
 | _|rttj| jf }	ttj| jf }
t	|
| jd df| j d
d|	| jdd| _d	S )a4  
        Args:
            spatial_dims: number of spatial dimensions of the input image.
            in_channels: number of channels of the input image.
            out_channels: optional number of channels of the output image.
            scale_factor: multiplier for spatial size. Defaults to 2.
            conv_block: a conv block to extract feature maps before upsampling. Defaults to None.

                - When ``conv_block`` is ``"default"``, one reserved conv layer will be utilized.
                - When ``conv_block`` is an ``nn.module``,
                  please ensure the output number of channels is divisible ``(scale_factor ** dimensions)``.

            apply_pad_pool: if True the upsampled tensor is padded then average pooling is applied with a kernel the
                size of `scale_factor` with a stride of 1. This implements the nearest neighbour resize convolution
                component of subpixel convolutions described in Aitken et al.
            bias: whether to have a bias term in the default conv_block. Defaults to True.

        r   zEThe `scale_factor` multiplier must be an integer greater than 0, got r6   r   z!in_channels need to be specified.   r(   )r   r   r   r0   r1   r$   Ng        )r1   rF   )r   r0   )r7   r8   r<   
dimensionsr   r   rA   r5   r   rE   Identitypad_poolr   AVGr   ZCONSTANTPAD
Sequential)rI   r   r   r   r   r5   r%   r$   conv_out_channels	pool_typeZpad_typerK   r)   r,   r8      s<    
     
zSubpixelUpsample.__init__ztorch.Tensor)xr&   c              
   C  sv   |  |}|jd | j| j  dkrXtd|jd  d| j d| j d| j| j  d	t|| j| j}| |}|S )zd
        Args:
            x: Tensor in shape (batch, channel, spatial_1[, spatial_2, ...).
        r(   r   z'Number of channels after `conv_block` (z:) must be evenly divisible by scale_factor ** dimensions (^=z).)r5   shaper   rS   r<   r   rU   )rI   rZ   r)   r)   r,   forward  s    
.
zSubpixelUpsample.forward)Nr   r   TT)rM   rN   rO   rP   r8   r^   rQ   r)   r)   rK   r,   r      s        ">)
__future__r   collections.abcr   torchtorch.nnrE   monai.networks.layers.factoriesr   r   r   monai.networks.utilsr   r   monai.utilsr	   r
   r   r   __all__rW   r   Moduler   r   r   r   r)   r)   r)   r,   <module>   s    h