
    i                        d dl mZ d dlmZ d dlZd dlmZmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d	ed
edeeef   fdZ	 	 	 dd	ed
edee   dee   deed      defdZ	 	 	 dd	ed
edee   dee   deed      defdZy)    )Sequence)OptionalN)Tensornn)Literal)_gaussian_kernel_2d)_check_same_shape)reducepredstargetreturnc                    | j                   |j                   k7  r&t        d| j                    d|j                    d      t        | |       t        | j                        dk7  r&t        d| j                   d|j                   d      | |fS )zUpdate and returns variables required to compute Universal Image Quality Index.

    Args:
        preds: Predicted tensor
        target: Ground truth tensor

    zEExpected `preds` and `target` to have the same data type. Got preds: z and target: .   z@Expected `preds` and `target` to have BxCxHxW shape. Got preds: )dtype	TypeErrorr	   lenshape
ValueError)r   r   s     v/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/functional/image/uqi.py_uqi_updater      s     {{fll" ;;-}V\\N!E
 	
 eV$
5;;1Nu{{m[hioiuiuhvvwx
 	
 &=    kernel_sizesigma	reduction)elementwise_meansumnonec                    t        |      dk7  st        |      dk7  r$t        dt        |       dt        |       d      t        d |D              rt        d| d      t        d |D              rt        d| d      | j                  }| j	                  d	      }| j
                  }t        |||||      }|d
   d	z
  dz  }	|d	   d	z
  dz  }
t        j                  j                  | |	|	|
|
fd      } t        j                  j                  ||	|	|
|
fd      }t        j                  | || | z  ||z  | |z  f      }t        j                  j                  |||      }|j                  | j                  d
         }|d
   j                  d      }|d	   j                  d      }|d
   |d	   z  }t        j                   |d   |z
  d      }t        j                   |d   |z
  d      }|d   |z
  }d|z  }||z   }t        j"                  |j
                        j$                  }d|z  |z  ||z   |z  |z   z  }|d|	|	 |
|
 f   }t'        ||      S )a  Compute Universal Image Quality Index.

    Args:
        preds: estimated image
        target: ground truth image
        kernel_size: size of the gaussian kernel
        sigma: Standard deviation of the gaussian kernel
        reduction: a method to reduce metric score over labels.

            - ``'elementwise_mean'``: takes the mean (default)
            - ``'sum'``: takes the sum
            - ``'none'`` or ``None``: no reduction will be applied

    Example:
        >>> preds = torch.rand([16, 1, 16, 16])
        >>> target = preds * 0.75
        >>> preds, target = _uqi_update(preds, target)
        >>> _uqi_compute(preds, target)
        tensor(0.9216)

       zOExpected `kernel_size` and `sigma` to have the length of two. Got kernel_size: z and sigma: r   c              3   :   K   | ]  }|d z  dk(  xs |dk    yw)r    r   N ).0xs     r   	<genexpr>z_uqi_compute.<locals>.<genexpr>Q   s%     
5A1q5A:as   z8Expected `kernel_size` to have odd positive number. Got c              3   &   K   | ]	  }|d k    yw)r   Nr"   )r#   ys     r   r%   z_uqi_compute.<locals>.<genexpr>T   s     
!5a165s   z.Expected `sigma` to have positive number. Got    r   reflect)mode)groupsg        )min   r   .)r   r   anydevicesizer   r   r   
functionalpadtorchcatconv2dsplitr   powclampfinfoepsr
   )r   r   r   r   r   r/   channelr   kernelpad_hpad_w
input_listoutputsoutput_list
mu_pred_sqmu_target_sqmu_pred_targetsigma_pred_sqsigma_target_sqsigma_pred_targetupperlowerr:   uqi_idxs                           r   _uqi_computerK   /   s   8 ;1E
a!!$[!1 2,s5zl!M
 	

 
5
55ST_S``abcc

!5
!!I%PQRSS\\FjjmGKKE +ueVLF^aA%E^aA%EMMeeUE5%A	RE]]vueU'C)TFE655=&6/5SY>Z[Jmm"":vg"FG--A/KQ##A&Jq>%%a(L ^k!n4N KKA ;EMkk+a.<"?SIO#A7!!EO+E
++m))
*
.
.CN"e+l1Je0SVY0YZGc5%<v56G'9%%r   c                 >    t        | |      \  } }t        | ||||      S )a  Universal Image Quality Index.

    Args:
        preds: estimated image
        target: ground truth image
        kernel_size: size of the gaussian kernel
        sigma: Standard deviation of the gaussian kernel
        reduction: a method to reduce metric score over labels.

            - ``'elementwise_mean'``: takes the mean (default)
            - ``'sum'``: takes the sum
            - ``'none'`` or ``None``: no reduction will be applied

    Return:
        Tensor with UniversalImageQualityIndex score

    Raises:
        TypeError:
            If ``preds`` and ``target`` don't have the same data type.
        ValueError:
            If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
        ValueError:
            If the length of ``kernel_size`` or ``sigma`` is not ``2``.
        ValueError:
            If one of the elements of ``kernel_size`` is not an ``odd positive number``.
        ValueError:
            If one of the elements of ``sigma`` is not a ``positive number``.

    Example:
        >>> from torchmetrics.functional.image import universal_image_quality_index
        >>> preds = torch.rand([16, 1, 16, 16])
        >>> target = preds * 0.75
        >>> universal_image_quality_index(preds, target)
        tensor(0.9216)

    References:
        [1] Zhou Wang and A. C. Bovik, "A universal image quality index," in IEEE Signal Processing Letters, vol. 9,
        no. 3, pp. 81-84, March 2002, doi: 10.1109/97.995823.

        [2] Zhou Wang, A. C. Bovik, H. R. Sheikh and E. P. Simoncelli, "Image quality assessment: from error visibility
        to structural similarity," in IEEE Transactions on Image Processing, vol. 13, no. 4, pp. 600-612, April 2004,
        doi: 10.1109/TIP.2003.819861.

    )r   rK   )r   r   r   r   r   s        r   universal_image_quality_indexrM   w   s(    f  v.ME6v{E9EEr   ))   rN   )      ?rO   r   )collections.abcr   typingr   r3   r   r   typing_extensionsr   #torchmetrics.functional.image.utilsr   torchmetrics.utilities.checksr	   "torchmetrics.utilities.distributedr
   tupler   intfloatrK   rM   r"   r   r   <module>rY      s   %    % C ; 5v v %2G 0 "*'FXE&E&E& #E& E?	E&
  ABCE& E&V "*'FX4F4F4F #4F E?	4F
  ABC4F 4Fr   