o
    )i4                     @  s   d dl mZ d dlZd dlmZ d dlZd dlmZ d dlm	Z	m
Z
 d dlmZmZ d dlmZ ddgZG d	d dejZeZdS )
    )annotationsN)Sequence)ConvolutionResidualUnit)ActNorm)SkipConnectionUNetUnetc                      sj   e Zd ZdZdddejejdddfd0 fddZd1d#d$Z	d2d&d'Z
d3d(d)Zd2d*d+Zd4d.d/Z  ZS )5r	   a]  
    Enhanced version of UNet which has residual units implemented with the ResidualUnit class.
    The residual part uses a convolution to change the input dimensions to match the output dimensions
    if this is necessary but will use nn.Identity if not.
    Refer to: https://link.springer.com/chapter/10.1007/978-3-030-12029-0_40.

    Each layer of the network has a encode and decode path with a skip connection between them. Data in the encode path
    is downsampled using strided convolutions (if `strides` is given values greater than 1) and in the decode path
    upsampled using strided transpose convolutions. These down or up sampling operations occur at the beginning of each
    block rather than afterwards as is typical in UNet implementations.

    To further explain this consider the first example network given below. This network has 3 layers with strides
    of 2 for each of the middle layers (the last layer is the bottom connection which does not down/up sample). Input
    data to this network is immediately reduced in the spatial dimensions by a factor of 2 by the first convolution of
    the residual unit defining the first layer of the encode part. The last layer of the decode part will upsample its
    input (data from the previous layer concatenated with data from the skip connection) in the first convolution. this
    ensures the final output of the network has the same shape as the input.

    Padding values for the convolutions are chosen to ensure output sizes are even divisors/multiples of the input
    sizes if the `strides` value for a layer is a factor of the input sizes. A typical case is to use `strides` values
    of 2 and inputs that are multiples of powers of 2. An input can thus be downsampled evenly however many times its
    dimensions can be divided by 2, so for the example network inputs would have to have dimensions that are multiples
    of 4. In the second example network given below the input to the bottom layer will have shape (1, 64, 15, 15) for
    an input of shape (1, 1, 240, 240) demonstrating the input being reduced in size spatially by 2**4.

    Args:
        spatial_dims: number of spatial dimensions.
        in_channels: number of input channels.
        out_channels: number of output channels.
        channels: sequence of channels. Top block first. The length of `channels` should be no less than 2.
        strides: sequence of convolution strides. The length of `stride` should equal to `len(channels) - 1`.
        kernel_size: convolution kernel size, the value(s) should be odd. If sequence,
            its length should equal to dimensions. Defaults to 3.
        up_kernel_size: upsampling convolution kernel size, the value(s) should be odd. If sequence,
            its length should equal to dimensions. Defaults to 3.
        num_res_units: number of residual units. Defaults to 0.
        act: activation type and arguments. Defaults to PReLU.
        norm: feature normalization type and arguments. Defaults to instance norm.
        dropout: dropout ratio. Defaults to no dropout.
        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.
        adn_ordering: a string representing the ordering of activation (A), normalization (N), and dropout (D).
            Defaults to "NDA". See also: :py:class:`monai.networks.blocks.ADN`.

    Examples::

        from monai.networks.nets import UNet

        # 3 layer network with down/upsampling by a factor of 2 at each layer with 2-convolution residual units
        net = UNet(
            spatial_dims=2,
            in_channels=1,
            out_channels=1,
            channels=(4, 8, 16),
            strides=(2, 2),
            num_res_units=2
        )

        # 5 layer network with simple convolution/normalization/dropout/activation blocks defining the layers
        net=UNet(
            spatial_dims=2,
            in_channels=1,
            out_channels=1,
            channels=(4, 8, 16, 32, 64),
            strides=(2, 2, 2, 2),
        )

    Note: The acceptable spatial size of input data depends on the parameters of the network,
        to set appropriate spatial size, please check the tutorial for more details:
        https://github.com/Project-MONAI/tutorials/blob/master/modules/UNet_input_size_constrains.ipynb.
        Typically, when using a stride of 2 in down / up sampling, the output dimensions are either half of the
        input when downsampling, or twice when upsampling. In this case with N numbers of layers in the network,
        the inputs must have spatial dimensions that are all multiples of 2^N.
        Usually, applying `resize`, `pad` or `crop` transforms can help adjust the spatial size of input data.

       r   g        TNDAspatial_dimsintin_channelsout_channelschannelsSequence[int]strideskernel_sizeSequence[int] | intup_kernel_sizenum_res_unitsacttuple | strnormdropoutfloatbiasbooladn_orderingstrreturnNonec                   s  t    t|dk rtdt|t|d  }|dk r!td|dkr.td| d t|tr=t||kr=tdt|trLt||krLtd	|_|_	|_
|_|_|_|_|_|	_|
_|_|_|_d fdd  ||jjd_d S )N   z2the length of `channels` should be no less than 2.   r   z<the length of `strides` should equal to `len(channels) - 1`.z-`len(strides) > len(channels) - 1`, the last z$ values of strides will not be used.z9the length of `kernel_size` should equal to `dimensions`.z<the length of `up_kernel_size` should equal to `dimensions`.incr   outcr   r   r   is_topr   r!   	nn.Modulec                   s   |d }|d }t |dkr# |||dd |dd d}|d }n||d }||d  }| |||}	||||}
|	|
|S )a  
            Builds the UNet structure from the bottom up by recursing down to the bottom block, then creating sequential
            blocks containing the downsample path, a skip connection around the previous block, and the upsample path.

            Args:
                inc: number of input channels.
                outc: number of output channels.
                channels: sequence of channels. Top block first.
                strides: convolution stride.
                is_top: True if this is the top block.
            r   r#   r$   NF)len_get_bottom_layer_get_down_layer_get_up_layer_get_connection_block)r%   r&   r   r   r'   cssubblockZupcdownup_create_blockself Z/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/networks/nets/unet.pyr4      s    
z$UNet.__init__.<locals>._create_blockT)r%   r   r&   r   r   r   r   r   r'   r   r!   r(   )super__init__r)   
ValueErrorwarningswarn
isinstancer   
dimensionsr   r   r   r   r   r   r   r   r   r   r   r   model)r5   r   r   r   r   r   r   r   r   r   r   r   r   r   delta	__class__r3   r7   r9   j   s6   
 zUNet.__init__	down_pathr(   up_pathr0   c                 C  s   t |t||S )a  
        Returns the block object defining a layer of the UNet structure including the implementation of the skip
        between encoding (down) and decoding (up) sides of the network.

        Args:
            down_path: encoding half of the layer
            up_path: decoding half of the layer
            subblock: block defining the next layer in the network.
        Returns: block for this layer: `nn.Sequential(down_path, SkipConnection(subblock), up_path)`
        )nn
Sequentialr   )r5   rC   rD   r0   r6   r6   r7   r-      s   zUNet._get_connection_blockr'   c                 C  sj   | j dkrt| j|||| j| j | j| j| j| j| jd}|S t	| j|||| j| j| j| j| j| jd
}|S )a  
        Returns the encoding (down) part of a layer of the network. This typically will downsample data at some point
        in its structure. Its output is used as input to the next layer down and is concatenated with output from the
        next layer to form the input for the decode (up) part of the layer.

        Args:
            in_channels: number of input channels.
            out_channels: number of output channels.
            strides: convolution stride.
            is_top: True if this is the top block.
        r   )r   r   subunitsr   r   r   r   r   )r   r   r   r   r   r   r   )
r   r   r>   r   r   r   r   r   r   r   )r5   r   r   r   r'   modr6   r6   r7   r+      s8   
zUNet._get_down_layerc                 C  s   |  ||ddS )z
        Returns the bottom or bottleneck layer at the bottom of the network linking encode to decode halves.

        Args:
            in_channels: number of input channels.
            out_channels: number of output channels.
        r$   F)r+   )r5   r   r   r6   r6   r7   r*      s   zUNet._get_bottom_layerc                 C  s   t | j|||| j| j| j| j| j|o| jdkd| jd}| jdkr>t	| j||d| j
d| j| j| j| j|| jd}t||}|S )a  
        Returns the decoding (up) part of a layer of the network. This typically will upsample data at some point
        in its structure. Its output is used as input to the next layer up.

        Args:
            in_channels: number of input channels.
            out_channels: number of output channels.
            strides: convolution stride.
            is_top: True if this is the top block.
        r   T)	r   r   r   r   r   r   	conv_onlyis_transposedr   r$   )	r   r   rG   r   r   r   r   last_conv_onlyr   )r   r>   r   r   r   r   r   r   r   r   r   rE   rF   )r5   r   r   r   r'   convrur6   r6   r7   r,      s>   
zUNet._get_up_layerxtorch.Tensorc                 C  s   |  |}|S )N)r?   )r5   rN   r6   r6   r7   forward(  s   
zUNet.forward)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   )rC   r(   rD   r(   r0   r(   r!   r(   )
r   r   r   r   r   r   r'   r   r!   r(   )r   r   r   r   r!   r(   )rN   rO   r!   rO   )__name__
__module____qualname____doc__r   PRELUr   INSTANCEr9   r-   r+   r*   r,   rP   __classcell__r6   r6   rA   r7   r	      s     U
N

*

/)
__future__r   r;   collections.abcr   torchtorch.nnrE   "monai.networks.blocks.convolutionsr   r   monai.networks.layers.factoriesr   r   "monai.networks.layers.simplelayersr   __all__Moduler	   r
   r6   r6   r6   r7   <module>   s     