o
    %ݫi;                     @   s   d 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
mZmZmZ ddlmZ eeZG dd dejjZG dd	 d	ejZdS )
zfLibrary implementing complex-valued convolutional neural networks.

Authors
 * Titouan Parcollet 2020
    N)get_padding_elem)affect_conv_initcomplex_conv_opcomplex_initunitary_init)
get_loggerc                       sR   e Zd ZdZ								d fdd		Zd
d Zdd Zdd Zdd Z  Z	S )CConv1da  This function implements complex-valued 1d convolution.

    Arguments
    ---------
    out_channels : int
        Number of output channels. Please note
        that these are complex-valued neurons. If 256
        channels are specified, the output dimension
        will be 512.
    kernel_size : int
        Kernel size of the convolutional filters.
    input_shape : tuple
        The expected shape of the input tensor.
    stride : int, optional
        Stride factor of the convolutional filters (default 1).
    dilation : int, optional
        Dilation factor of the convolutional filters (default 1).
    padding : str, optional
        (same, valid, causal). If "valid", no padding is performed.
        If "same" and stride is 1, output shape is same as input shape.
        "causal" results in causal (dilated) convolutions. (default "same")
    groups : int, optional
        This option specifies the convolutional groups. See torch.nn
        documentation for more information (default 1).
    bias : bool, optional
        If True, the additive bias b is adopted (default True).
    padding_mode : str, optional
        This flag specifies the type of padding. See torch.nn documentation
        for more information (default "reflect").
    init_criterion : str, optional
        (glorot, he).
        This parameter controls the initialization criterion of the weights.
        It is combined with weights_init to build the initialization method of
        the complex-valued weights. (default "glorot")
    weight_init : str, optional
        (complex, unitary).
        This parameter defines the initialization procedure of the
        complex-valued weights. "complex" will generate random complex-valued
        weights following the init_criterion and the complex polar form.
        "unitary" will normalize the weights to lie on the unit circle. (default "complex")
        More details in: "Deep Complex Networks", Trabelsi C. et al.

    Example
    -------
    >>> inp_tensor = torch.rand([10, 16, 30])
    >>> cnn_1d = CConv1d(
    ...     input_shape=inp_tensor.shape, out_channels=12, kernel_size=5
    ... )
    >>> out_tensor = cnn_1d(inp_tensor)
    >>> out_tensor.shape
    torch.Size([10, 16, 24])
       sameTreflectglorotcomplexc                    s   t    || _|| _|| _|| _|| _|| _|| _|	| _	d| _
|
| _|| _| |d | _|  \| _| _tjtj| j | _tjtj| j | _| jrdtjtd| j | _| jjd nd | _ttd| j | _t| j| j| j| j| j d S NF   r   )r   unitary)super__init__out_channelskernel_sizestridedilationpaddinggroupsbiaspadding_mode	unsqueezeinit_criterionweight_init_check_inputin_channels_get_kernel_and_weight_shapek_shapew_shapetorchnn	ParameterTensorreal_weightimag_weightbdatafill_r   r   winitr   selfr   r   input_shaper   r   r   r   r   r   r   r   	__class__ [/home/ubuntu/.local/lib/python3.10/site-packages/speechbrain/nnet/complex_networks/c_CNN.pyr   M   s<   
zCConv1d.__init__c              
   C   s   | dd}| jdkr| || j| j| j}n#| jdkr-| jd | j }t||df}n| jdkr3ntd| j t	|| j
| j| j| jd| jdd	}| dd}|S )
a-  Returns the output of the convolution.

        Arguments
        ---------
        x : torch.Tensor
            (batch, time, channel).
            Input to convolve. 3d or 4d tensors are expected.

        Returns
        -------
        wx : torch.Tensor
            The convolved outputs.
        r	   r
   causalr   valid4Padding must be 'same', 'valid' or 'causal'. Got %s.Tr   r   r   conv1d)	transposer   _manage_paddingr   r   r   Fpad
ValueErrorr   r'   r(   r)   )r.   xnum_padwxr2   r2   r3   forward   s6   


zCConv1d.forwardc                 C   s2   |j d }t||||}tj|t|| jd}|S )a  This function performs zero-padding on the time axis
        such that their lengths is unchanged after the convolution.

        Arguments
        ---------
        x : torch.Tensor
            Input tensor.
        kernel_size : int
            Kernel size.
        dilation : int
            Dilation.
        stride : int
            Stride.

        Returns
        -------
        x : torch.Tensor
            The padded outputs.
        r4   mode)shaper   r<   r=   tupler   )r.   r?   r   r   r   L_inr   r2   r2   r3   r;      s   
zCConv1d._manage_paddingc                 C   sn   t |dkr|d }ntd| | jd dkrtd| j |d dkr5tdt| j d t| j |S ):Checks the input and returns the number of input channels.   r   z%ComplexConv1d expects 3d inputs. Got r   4The field kernel size must be an odd number. Got %s.HComplex torch.Tensors must have dimensions divisible by 2. input.size()[] = )lenr>   r   strchannels_axisnb_channelsr.   r/   r   r2   r2   r3   r      s,   
zCConv1d._check_inputc                 C   s$   | j }| j| jft|f }||fS )BReturns the kernel size and weight shape for convolutional layers.)r   r   r   rF   r.   ksr"   r2   r2   r3   r       s   z$CConv1d._get_kernel_and_weight_shaper	   r	   r
   r	   Tr   r   r   )
__name__
__module____qualname____doc__r   rB   r;   r   r    __classcell__r2   r2   r0   r3   r      s    :70 r   c                       sT   e Zd ZdZ								d fdd		ZdddZdd Zdd Zdd Z  Z	S )CConv2da  This function implements complex-valued 1d convolution.

    Arguments
    ---------
    out_channels : int
        Number of output channels. Please note
        that these are complex-valued neurons. If 256
        channels are specified, the output dimension
        will be 512.
    kernel_size : int
        Kernel size of the convolutional filters.
    input_shape : tuple
        The expected shape of the input.
    stride : int, optional
        Stride factor of the convolutional filters (default 1).
    dilation : int, optional
        Dilation factor of the convolutional filters (default 1).
    padding : str, optional
        (same, valid, causal). If "valid", no padding is performed.
        If "same" and stride is 1, output shape is same as input shape.
        "causal" results in causal (dilated) convolutions. (default "same")
    groups : int, optional
        This option specifies the convolutional groups (default 1). See torch.nn
        documentation for more information.
    bias : bool, optional
        If True, the additive bias b is adopted (default True).
    padding_mode : str, optional
        This flag specifies the type of padding (default "reflect").
        See torch.nn documentation for more information.
    init_criterion : str , optional
        (glorot, he).
        This parameter controls the initialization criterion of the weights (default "glorot").
        It is combined with weights_init to build the initialization method of
        the complex-valued weights.
    weight_init : str, optional
        (complex, unitary).
        This parameter defines the initialization procedure of the
        complex-valued weights (default complex). "complex" will generate random complex-valued
        weights following the init_criterion and the complex polar form.
        "unitary" will normalize the weights to lie on the unit circle.
        More details in: "Deep Complex Networks", Trabelsi C. et al.

    Example
    -------
    >>> inp_tensor = torch.rand([10, 16, 30, 30])
    >>> cnn_2d = CConv2d(
    ...     input_shape=inp_tensor.shape, out_channels=12, kernel_size=5
    ... )
    >>> out_tensor = cnn_2d(inp_tensor)
    >>> out_tensor.shape
    torch.Size([10, 16, 30, 24])
    r	   r
   Tr   r   r   c                    sL  t    || _|| _|| _|| _|| _|| _|| _|	| _	d| _
|
| _|| _t| jtr3| j| jg| _t| jtr@| j| jg| _t| jtrM| j| jg| _| |d | _|  \| _| _tjtj| j | _tjtj| j | _| jrtjtd| j | _| jjd nd | _ttd| j | _t | j| j| j| j| j d S r   )!r   r   r   r   r   r   r   r   r   r   r   r   r   
isinstanceintr   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r   r   r,   r   r-   r0   r2   r3   r   /  sH   
zCConv2d.__init__Fc              
   C   s   |r|  | |dd}| jdkr| || j| j| j}n#| jdkr4| jd | j }t||df}n| jdkr:nt	d| j t
|| j| j| j| jd| jdd	}|dd}|S )
a  Returns the output of the convolution.

        Arguments
        ---------
        x : torch.Tensor
            (batch, time, feature, channels).
            Input to convolve. 3d or 4d tensors are expected.
        init_params : bool
            Whether to initialize the parameters in this pass.

        Returns
        -------
        x : torch.Tensor
            The output of the convolution.
        r	   r4   r
   r5   r   r6   r7   Fr8   )init_paramsr:   r   r;   r   r   r   r<   r=   r>   r   r'   r(   r)   )r.   r?   r^   r@   rA   r2   r2   r3   rB   p  s:   



zCConv2d.forwardc                 C   s2   | j d | j d f}| j| jfg |R  }||fS )rR   r   r	   )r   r   r   rS   r2   r2   r3   r      s   z$CConv2d._get_kernel_and_weight_shapec           	      C   sb   |j d }t||d |d |d }t||d |d |d }|| }tjj|t|| jd}|S )a  This function performs zero-padding on the time and frequency axes
        such that their lengths is unchanged after the convolution.

        Arguments
        ---------
        x : torch.Tensor
            Input tensor.
        kernel_size : int
            Kernel size.
        dilation : int
            Dilation.
        stride: int
            Stride.

        Returns
        -------
        x : torch.Tensor
            The padded tensor.
        r4   rC   )rE   r   r$   
functionalr=   rF   r   )	r.   r?   r   r   r   rG   padding_timepadding_freqr   r2   r2   r3   r;     s   
zCConv2d._manage_paddingc                 C   s   t |dkrd| _d}nt |dkr|d }ntd| | jd d dks/| jd d dkr6td| j |d dkrLtd	t| j d
 t| j |S )rH   rI   Tr	      zExpected 3d or 4d inputs. Got r   r   rJ   rK   rL   )rM   r   r>   r   rN   rO   rP   rQ   r2   r2   r3   r     s.   
$zCConv2d._check_inputrU   )F)
rV   rW   rX   rY   r   rB   r    r;   r   rZ   r2   r2   r0   r3   r[      s    :
A8&r[   )rY   r#   torch.nnr$   torch.nn.functionalr`   r<   speechbrain.nnet.CNNr   'speechbrain.nnet.complex_networks.c_opsr   r   r   r   speechbrain.utils.loggerr   rV   loggerModuler   r[   r2   r2   r2   r3   <module>   s     c