U
    Ph                     @  s   d dl mZ d dlmZ d dlZd dlZd dlm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gZG d	d deZdS )
    )annotations)SequenceN)
functional)calculate_out_shapesame_padding)ActNorm)AutoEncoderVarAutoEncoderc                      s   e Zd ZdZddddddejejdddf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	d!ddddddZ
ddddddZddddd Z  ZS )"r
   a	  
    Variational Autoencoder based on the paper - https://arxiv.org/abs/1312.6114

    Args:
        spatial_dims: number of spatial dimensions.
        in_shape: shape of input data starting with channel dimension.
        out_channels: number of output channels.
        latent_size: size of the latent variable.
        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.
        inter_channels: sequence of channels defining the blocks in the intermediate layer between encode and decode.
        inter_dilations: defines the dilation value for each block of the intermediate layer. Defaults to 1.
        num_inter_units: number of residual units for each block of the intermediate layer. 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.
        use_sigmoid: whether to use the sigmoid function on final output. Defaults to True.

    Examples::

        from monai.networks.nets import VarAutoEncoder

        # 3 layer network accepting images with dimensions (1, 32, 32) and using a latent vector with 2 values
        model = VarAutoEncoder(
            spatial_dims=2,
            in_shape=(32, 32),  # image spatial shape
            out_channels=1,
            latent_size=2,
            channels=(16, 32, 64),
            strides=(1, 2, 2),
        )

    see also:
        - Variational autoencoder network with MedNIST Dataset
          https://github.com/Project-MONAI/tutorials/blob/master/modules/varautoencoder_mednist.ipynb
       r   N   TintzSequence[int]zSequence[int] | intzlist | Noneztuple | str | Noneztuple | strztuple | str | float | NoneboolNone)spatial_dimsin_shapeout_channelslatent_sizechannelsstrideskernel_sizeup_kernel_sizenum_res_unitsinter_channelsinter_dilationsnum_inter_unitsactnormdropoutbiasuse_sigmoidreturnc                   s   |^| _ | _|| _|| _tj| jtd| _t 	|| j ||||||	|
|||||| t
| j}|D ]}t| j| j||| _qbtt| j| j }t|| j| _t|| j| _t| j|| _d S )N)dtype)in_channelsr   r    r   npasarrayr   
final_sizesuper__init__r   r   r   prodencoded_channelsnnLinearmulogvardecodeL)selfr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    paddingsZlinear_size	__class__ W/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/networks/nets/varautoencoder.pyr(   J   s8    
zVarAutoEncoder.__init__ztorch.Tensorz!tuple[torch.Tensor, torch.Tensor])xr!   c                 C  sB   |  |}| |}||jd d}| |}| |}||fS Nr   )encodeintermediateviewshaper-   r.   )r0   r7   r-   r.   r5   r5   r6   encode_forward   s    



zVarAutoEncoder.encode_forward)zr    r!   c                 C  sL   t | |}|j|jd | jd f| j }| |}|rHt	|}|S r8   )
Frelur/   r<   r=   r   r&   decodetorchsigmoid)r0   r?   r    r7   r5   r5   r6   decode_forward   s     

zVarAutoEncoder.decode_forward)r-   r.   r!   c                 C  s.   t d| }| jr$t ||}||S )Ng      ?)rC   exptraining
randn_likemuladd_)r0   r-   r.   stdr5   r5   r6   reparameterize   s    zVarAutoEncoder.reparameterizez=tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]c                 C  s0   |  |\}}| ||}| || j|||fS )N)r>   rL   rE   r    )r0   r7   r-   r.   r?   r5   r5   r6   forward   s    zVarAutoEncoder.forward)T)__name__
__module____qualname____doc__r   PRELUr   INSTANCEr(   r>   rE   rL   rM   __classcell__r5   r5   r3   r6   r
      s"   566)
__future__r   collections.abcr   numpyr$   rC   torch.nnr+   r   r@   monai.networks.layers.convutilsr   r   monai.networks.layers.factoriesr   r   monai.networks.netsr	   __all__r
   r5   r5   r5   r6   <module>   s   