U
    PhS                     @  s*  d dl mZ d dlmZ d dlmZ d dlZd dlmZ d dl	m  m
Z d dlmZ d dlmZ d dlmZmZ d dlmZ d	d
ddgZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZG dd dejZ e  Z! Z"Z#dS )    )annotations)Sequence)OptionalN)Convolution)UpSample)ConvPool)ensure_tuple_repBasicUnetPlusPlusBasicunetPlusPlusbasicunetplusplusBasicUNetPlusPlusKernelModifiedc                      s(   e Zd ZdZ fddZdd Z  ZS )Attention_blockz
    Attention Block
    c              
     s   t t|   ttj||dddddt|| _ttj||dddddt|| _ttj|ddddddtdt	 | _
tjdd| _d S )N   r   T)kernel_sizestridepaddingbias)inplace)superr   __init__nn
SequentialConv3dBatchNorm3dW_gW_xSigmoidpsiReLUrelu)selfF_gF_lF_int	__class__ i/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/networks/nets/basic_unetplusplus_modified_aspp.pyr   (   s    zAttention_block.__init__c                 C  s4   |  |}| |}| || }| |}|| S )N)r   r   r    r   )r!   gxg1x1r   r'   r'   r(   forward<   s
    


zAttention_block.forward__name__
__module____qualname____doc__r   r-   __classcell__r'   r'   r%   r(   r   #   s   r   c                   @  s    e Zd ZdZdddddZdS )MCDropout3du>   MC Dropout：无论 model.train()/eval() 都启用随机失活torch.Tensor)inputreturnc                 C  s   t j|| jd| jdS )NT)ptrainingr   )F	dropout3dr8   r   )r!   r6   r'   r'   r(   r-   G   s    zMCDropout3d.forwardN)r/   r0   r1   r2   r-   r'   r'   r'   r(   r4   D   s   r4   c                      s:   e Zd ZdZdddddddd	d
ddd
 fddZ  ZS )TwoConvztwo convolutions.           r?   r?   r   r   r?   r   intstr | tupleboolfloat | tupleSequence[int]Optional[tuple]zSequence[int] | int)
spatial_dimsin_chnsout_chnsactnormr   dropoutr   r   r   c                   s\   t    t|||||||||	|
d
}t|||||||||	d	}| d| | d| dS )a  
        Args:
            spatial_dims: number of spatial dimensions.
            in_chns: number of input channels.
            out_chns: number of output channels.
            act: activation type and arguments.
            norm: feature normalization type and arguments.
            bias: whether to have a bias term in convolution blocks.
            dropout: dropout ratio. Defaults to no dropout.

        )rJ   rK   rL   r   r   r   strides)rJ   rK   rL   r   r   r   conv_0conv_1N)r   r   r   
add_module)r!   rG   rH   rI   rJ   rK   r   rL   r   r   r   rN   rO   r%   r'   r(   r   N   s4    
zTwoConv.__init__)r=   r>   r@   r   r/   r0   r1   r2   r   r3   r'   r'   r%   r(   r<   K   s   
    r<   c                      s:   e Zd ZdZdddddddd	d
ddd
 fddZ  ZS )Downz-maxpooling downsampling and two convolutions.r=   r>   r@   maxpoolrA   rB   rC   rD   rE   rF   str)
rG   rH   rI   rJ   rK   r   rL   r   r   downsample_modec                   s~   t    |
dkr6td|f dd}| d| d}n|
dkrDd}ntd|
 t|||||||||	|d	
}| d
| dS )a  
        Args:
            spatial_dims: number of spatial dimensions.
            in_chns: number of input channels.
            out_chns: number of output channels.
            act: activation type and arguments.
            norm: feature normalization type and arguments.
            bias: whether to have a bias term in convolution blocks.
            dropout: dropout ratio. Defaults to no dropout.
            downsample_mode: 'maxpool' or 'strideconv'. Defaults to 'maxpool'.

        rS   MAX   rX   r   r   max_poolingr   
strideconvzUnsupported downsample mode: )r   r   r   convsN)r   r   r   rP   
ValueErrorr<   )r!   rG   rH   rI   rJ   rK   r   rL   r   r   rU   rZ   conv_strider\   r%   r'   r(   r      s*    
zDown.__init__)r=   r>   r@   rS   rQ   r'   r'   r%   r(   rR      s   
    rR   c                      s   e Zd Z fddZ  ZS )	_ASPPConvc              
     s0   t  tj||d||ddt|t  d S )Nr?   F)r   r   dilationr   )r   r   r   r   r   r   )r!   in_channelsout_channelsr`   r%   r'   r(   r      s    z_ASPPConv.__init__)r/   r0   r1   r   r3   r'   r'   r%   r(   r_      s   r_   c                      s$   e Zd Z fddZdd Z  ZS )ASPPc                   s   t    g }|ttj||dddt|t  t|}|D ]}|t	||| qF|tt
dtj||dddt|t  t|| _ttjt| j| |dddt|t td| _d S )Nr   F)r   g      ?)r   r   appendr   r   r   r   r   tupler_   AdaptiveAvgPool3d
ModuleListr\   lenDropoutproject)r!   ra   rb   atrous_ratesmodulesratesrater%   r'   r(   r      s6    
	zASPP.__init__c              	   C  sN   g }| j D ]*}|tj|||jdd  ddd q
tj|dd}| |S )NrX   	trilinearF)sizemodealign_cornersr   dim)r\   rd   r:   interpolateshapetorchcatrj   )r!   r*   resconvr'   r'   r(   r-      s    
   zASPP.forwardr/   r0   r1   r   r-   r3   r'   r'   r%   r(   rc      s   !rc   c                      sX   e Zd ZdZdd
d
d
d
dddddddddddddd fddZdddddZ  ZS )UpCatzHupsampling, concatenation with the encoder feature map, two convolutionsr=   deconvdefaultlinearTr>   r@   FrA   rB   rC   rD   rT   znn.Module | str | Nonezbool | NonerE   rF   )rG   rH   cat_chnsrI   rJ   rK   r   rL   upsamplepre_convinterp_moderr   halvesis_padr   r   	attentionc                   s   t    |	dkr |
dkr |}n|r,|d n|}t|||d|	|
|||d	| _t||| |||||||d	| _|| _|| _| jrt|||d d| _	dS )a  
        Args:
            spatial_dims: number of spatial dimensions.
            in_chns: number of input channels to be upsampled.
            cat_chns: number of channels from the encoder.
            out_chns: number of output channels.
            act: activation type and arguments.
            norm: feature normalization type and arguments.
            bias: whether to have a bias term in convolution blocks.
            dropout: dropout ratio. Defaults to no dropout.
            upsample: upsampling mode, available options are
                ``"deconv"``, ``"pixelshuffle"``, ``"nontrainable"``.
            pre_conv: a conv block applied before upsampling.
                Only used in the "nontrainable" or "pixelshuffle" mode.
            interp_mode: {``"nearest"``, ``"linear"``, ``"bilinear"``, ``"bicubic"``, ``"trilinear"``}
                Only used in the "nontrainable" mode.
            align_corners: set the align_corners parameter for upsample. Defaults to True.
                Only used in the "nontrainable" mode.
            halves: whether to halve the number of channels during upsampling.
                This parameter does not work on ``nontrainable`` mode if ``pre_conv`` is `None`.
            is_pad: whether to pad upsampling features to fit features from encoder. Defaults to True.
            attention: whether to use attention gate. Defaults to False.

        nontrainableNrX   rW   )rq   r   r   rr   r   )r   r   )r"   r#   r$   )
r   r   r   r   r<   r\   r   use_attentionr   attention_gate)r!   rG   rH   r   rI   rJ   rK   r   rL   r   r   r   rr   r   r   r   r   r   up_chnsr%   r'   r(   r      sD    ,
  zUpCat.__init__r5   zOptional[torch.Tensor])r*   x_ec                 C  s   |  |}|dk	r|}| jr*| j||d}| jrt|jd }dg|d  }t|D ]4}|j| d  |j| d  krTd||d d < qTtjj	
||d}| tj||gdd}n
| |}|S )z

        Args:
            x: features to be upsampled.
            x_e: optional features from the encoder, if None, this branch is not in use.
        N)r)   r*   rX   r   r   	replicaters   )r   r   r   r   rh   rv   rangerw   r   
functionalpadr\   rx   )r!   r*   r   x_0x_e_non_none
dimensionsspir'   r'   r(   r-   H  s"    
 
zUpCat.forward)
r=   r}   r~   r   TTTr>   r@   Fr.   r'   r'   r%   r(   r|      s             4Nr|   c                      sn   e Zd Zddddddddd	fd
ddifddddfdddddddddddd fddZddddZ  ZS )r   r?   r   rX   )    r   @         r   F	LeakyReLUg?T)negative_sloper   instanceaffiner=   r}   rA   rE   rC   rB   rD   rT   float)rG   ra   rb   featuresdeep_supervisionrJ   rK   r   rL   r   	dropout_pc                   sT  t    || _|| _t|d}td| d t|||d ||||	dd| _t||d |d ||||	dd| _	t||d |d ||||	dd| _
t||d |d	 ||||	dd
d	| _t|d	 |d dddgd| _t||d |d |d ||||	|
dddd| _t||d |d |d ||||	|
dddd| _t||d	 |d |d ||||	|
dddd| _t||d |d	 |d	 ||||	|
dddd| _t||d |d d |d ||||	|
dddd| _t||d |d d |d ||||	|
dddd| _t||d	 |d d |d ||||	|
dddd| _t||d |d d	 |d ||||	|
dddd| _t||d |d d	 |d ||||	|
dddd| _t||d |d d |d ||||	|
dddd| _| jr| jdkrt| jnt | _td|f |d |dd| _td|f |d |dd| _td|f |d |dd| _ td|f |d |dd| _!dS )a	  
        A UNet++ implementation with 1D/2D/3D supports.

        Based on:

            Zhou et al. "UNet++: A Nested U-Net Architecture for Medical Image
            Segmentation". 4th Deep Learning in Medical Image Analysis (DLMIA)
            Workshop, DOI: https://doi.org/10.48550/arXiv.1807.10165


        Args:
            spatial_dims: number of spatial dimensions. Defaults to 3 for spatial 3D inputs.
            in_channels: number of input channels. Defaults to 1.
            out_channels: number of output channels. Defaults to 2.
            features: six integers as numbers of features.
                Defaults to ``(32, 32, 64, 128, 256, 32)``,

                - the first five values correspond to the five-level encoder feature sizes.
                - the last value corresponds to the feature size after the last upsampling.

            deep_supervision: whether to prune the network at inference time. Defaults to False. If true, returns a list,
                whose elements correspond to outputs at different nodes.
            act: activation type and arguments. Defaults to LeakyReLU.
            norm: feature normalization type and arguments. Defaults to instance norm.
            bias: whether to have a bias term in convolution blocks. Defaults to True.
                According to `Performance Tuning Guide <https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html>`_,
                if a conv layer is directly followed by a batch norm layer, bias should be False.
            dropout: dropout ratio. Defaults to no dropout.
            upsample: upsampling mode, available options are
                ``"deconv"``, ``"pixelshuffle"``, ``"nontrainable"``.

        Examples::

            # for spatial 2D
            >>> net = BasicUNetPlusPlus(spatial_dims=2, features=(64, 128, 256, 512, 1024, 128))

            # for spatial 2D, with deep supervision enabled
            >>> net = BasicUNetPlusPlus(spatial_dims=2, features=(64, 128, 256, 512, 1024, 128), deep_supervision=True)

            # for spatial 2D, with group norm
            >>> net = BasicUNetPlusPlus(spatial_dims=2, features=(64, 128, 256, 512, 1024, 128), norm=("group", {"num_groups": 4}))

            # for spatial 3D
            >>> net = BasicUNetPlusPlus(spatial_dims=3, features=(32, 32, 64, 128, 256, 32))

        See Also
            - :py:class:`monai.networks.nets.BasicUNet`
            - :py:class:`monai.networks.nets.DynUNet`
            - :py:class:`monai.networks.nets.UNet`

           zBasicUNetPlusPlus features: .r   )r?   r?      rY   r   rX   r?   r[   )r   rU            )ra   rb   rk   FT)r   r   r      rz   N)"r   r   r   r   r	   printr<   conv_0_0rR   conv_1_0conv_2_0conv_3_0rc   asppr|   	upcat_0_1	upcat_1_1	upcat_2_1	upcat_3_1	upcat_0_2	upcat_1_2	upcat_2_2	upcat_0_3	upcat_1_3	upcat_0_4r4   r   Identitymc_dropout_outr   final_conv_0_1final_conv_0_2final_conv_0_3final_conv_0_4)r!   rG   ra   rb   r   r   rJ   rK   r   rL   r   r   fear%   r'   r(   r   g  s   A




  






  
  
  
  z(BasicUNetPlusPlusKernelModified.__init__r5   )r*   c                 C  s$  |  |}| |}| ||}| |}| ||}| |tj||gdd}| |}| 	||}	| 
|	tj||gdd}
| |
tj|||gdd}| |}| ||}| |tj||	gdd}| |tj|||
gdd}| |tj||||gdd}| |}| |}|g}|S )a  
        Args:
            x: input should have spatially N dimensions
                ``(Batch, in_channels, dim_0[, dim_1, ..., dim_N-1])``, N is defined by `dimensions`.
                It is recommended to have ``dim_n % 16 == 0`` to ensure all maxpooling inputs have
                even edge lengths.

        Returns:
            A torch Tensor of "raw" predictions in shape
            ``(Batch, out_channels, dim_0[, dim_1, ..., dim_N-1])``.
        r   rs   )r   r   r   r   r   r   rw   rx   r   r   r   r   r   r   r   r   r   r   r   )r!   r*   x_0_0x_1_0x_0_1x_2_0x_1_1x_0_2x_3_0x_2_1x_1_2x_0_3x_4_0x_3_1x_2_2x_1_3x_0_4
output_0_4outputr'   r'   r(   r-   }  s&    






z'BasicUNetPlusPlusKernelModified.forwardr{   r'   r'   r%   r(   r   f  s   
(  )$
__future__r   collections.abcr   typingr   rw   torch.nnr   torch.nn.functionalr   r:   "monai.networks.blocks.convolutionsr   monai.networks.blocks.upsampler   monai.networks.layers.factoriesr   r   monai.utils.miscr	   __all__Moduler   	Dropout3dr4   r   r<   rR   r_   rc   r|   r   r
   r   r   r'   r'   r'   r(   <module>   s4   !86.o  G