a
    þdˆ  ã                   @   sP   d dl mZmZmZ d dlZd dlmZ d dlm  mZ	 G dd„ dej
ƒZdS )é    )ÚListÚOptionalÚTupleNc                	       s´   e Zd ZdZg d¢dddddfee eeeef eeedd	œ‡ fd
d„Zde	ee
ej e
ej ejdœdd„Zde	ee
ej e
ej ejdœdd„Zejejejdœdd„Z‡  ZS )ÚMS_SSIMLossa€  Creates a criterion that computes MSSIM + L1 loss.

    According to [1], we compute the MS_SSIM + L1 loss as follows:

    .. math::
        \text{loss}(x, y) = \alpha \cdot \mathcal{L_{MSSIM}}(x,y)+(1 - \alpha) \cdot G_\alpha \cdot \mathcal{L_1}(x,y)

    Where:
        - :math:`\alpha` is the weight parameter.
        - :math:`x` and :math:`y` are the reconstructed and true reference images.
        - :math:`\mathcal{L_{MSSIM}}` is the MS-SSIM loss.
        - :math:`G_\alpha` is the sigma values for computing multi-scale SSIM.
        - :math:`\mathcal{L_1}` is the L1 loss.

    Reference:
        [1]: https://research.nvidia.com/sites/default/files/pubs/2017-03_Loss-Functions-for/NN_ImgProc.pdf#page11

    Args:
        sigmas: gaussian sigma values.
        data_range: the range of the images.
        K: k values.
        alpha : specifies the alpha value
        compensation: specifies the scaling coefficient.
        reduction : Specifies the reduction to apply to the
         output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
         ``'mean'``: the sum of the output will be divided by the number of elements
         in the output, ``'sum'``: the output will be summed.

    Returns:
        The computed loss.

    Shape:
        - Input1: :math:`(N, C, H, W)`.
        - Input2: :math:`(N, C, H, W)`.
        - Output: :math:`(N, H, W)` or scalar if reduction is set to ``'mean'`` or ``'sum'``.

    Examples:
        >>> input1 = torch.rand(1, 3, 5, 5)
        >>> input2 = torch.rand(1, 3, 5, 5)
        >>> criterion = kornia.losses.MS_SSIMLoss()
        >>> loss = criterion(input1, input2)
    )g      à?ç      ð?g       @g      @g       @r   )g{®Gáz„?g¸…ëQ¸ž?gš™™™™™™?g      i@ÚmeanN)ÚsigmasÚ
data_rangeÚKÚalphaÚcompensationÚ	reductionÚreturnc                    s   t ƒ  ¡  || _|d | d | _|d | d | _td|d  ƒ| _|| _|| _|| _	td|d  d ƒ}t
 dt|ƒ d||f¡}t|ƒD ]€\}	}
|  ||
¡|d|	 d dd d …d d …f< |  ||
¡|d|	 d dd d …d d …f< |  ||
¡|d|	 d dd d …d d …f< qŽ|  d|¡ d S )Nr   é   é   éÿÿÿÿé   é   Ú_g_masks)ÚsuperÚ__init__ÚDRÚC1ÚC2ÚintÚpadr   r   r   ÚtorchÚzerosÚlenÚ	enumerateÚ_fspecial_gauss_2dZregister_buffer)Úselfr   r	   r
   r   r   r   Zfilter_sizeÚg_masksÚidxÚsigma©Ú	__class__© ú^/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/kornia/losses/ms_ssim.pyr   7   s    	
((*zMS_SSIMLoss.__init__)Úsizer$   ÚdeviceÚdtyper   c                 C   sN   t j|||d}||d 8 }t  |d  d|d   ¡}|| ¡  }| d¡S )z½Create 1-D gauss kernel.

        Args:
            size: the size of gauss kernel.
            sigma: sigma of normal distribution.

        Returns:
            1D kernel (size).
        )r*   r+   r   r   )r   ZarangeÚexpÚsumZreshape)r!   r)   r$   r*   r+   ZcoordsÚgr'   r'   r(   Ú_fspecial_gauss_1dU   s
    zMS_SSIMLoss._fspecial_gauss_1dc                 C   s   |   ||||¡}t ||¡S )zÄCreate 2-D gauss kernel.

        Args:
            size: the size of gauss kernel.
            sigma: sigma of normal distribution.

        Returns:
            2D kernel (size x size).
        )r/   r   Úouter)r!   r)   r$   r*   r+   Zgaussian_vecr'   r'   r(   r    g   s    zMS_SSIMLoss._fspecial_gauss_2d)Úimg1Úimg2r   c                 C   sp  t |tjƒstdt|ƒ› ƒ‚t |tjƒs<tdt|ƒ› ƒ‚t|jƒt|jƒksntdt|ƒ› dt|ƒ› dƒ‚tj 	tj| j
¡}|jd }tj|||| jd}tj|||| jd}|| }|| }|| }	tj|| ||| jd| }
tj|| ||| jd| }tj|| ||| jd|	 }d|	 | j || | j  }d| | j |
| | j  }|d	d	…d
d	d	…d	d	…f |d	d	…dd	d	…d	d	…f  |d	d	…dd	d	…d	d	…f  }|jdd}d||  }tj||dd}tj||| d	… || jd d¡}| j| d| j | | j  }| j| }| jdkr6t |¡}n6| jdkrNt |¡}n| jdkr\ntd| j› ƒ‚|S )zöCompute MS_SSIM loss.

        Args:
            img1: the predicted image with shape :math:`(B, C, H, W)`.
            img2: the target image with a shape of :math:`(B, C, H, W)`.

        Returns:
            Estimated MS-SSIM_L1 loss.
        z&Input type is not a torch.Tensor. Got z'Output type is not a torch.Tensor. Got z!Input shapes should be same. Got z and Ú.éýÿÿÿ)ÚgroupsÚpaddingr   Nr   éþÿÿÿr   )ZdimÚnone)r   r   r-   zInvalid reduction mode: )Ú
isinstancer   ÚTensorÚ	TypeErrorÚtyper   ÚshapeÚ
ValueErrorZjitZannotater   ÚFZconv2dr   r   r   ÚprodZl1_lossr   r   r   r   r   r-   ÚNotImplementedError)r!   r1   r2   r"   ZCHZmuxZmuyZmux2Zmuy2ZmuxyZsigmax2Zsigmay2ZsigmaxyÚlcÚcsZlMZPIcsZloss_ms_ssimZloss_l1Zgaussian_l1Zlossr'   r'   r(   Úforwardv   sB    

T$
zMS_SSIMLoss.forward)NN)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Úfloatr   Ústrr   r   r   r   r*   r+   r:   r/   r    rD   Ú__classcell__r'   r'   r%   r(   r      s6   -ù
ø ÿþ ÿþr   )Útypingr   r   r   r   Ztorch.nnÚnnZtorch.nn.functionalZ
functionalr?   ÚModuler   r'   r'   r'   r(   Ú<module>   s   