o
    Ñôj@!  ã                   @   s²   d dl mZ d dlmZ d dlmZmZmZ d dlZd dlm	Z	m
Z
 d dlm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mZ esOdgZG dd„ deƒZdS )é    )ÚSequence)Úpartial)ÚAnyÚOptionalÚUnionN)ÚTensorÚtensor)ÚLiteral)Ú_psnr_computeÚ_psnr_update)ÚMetric)Úrank_zero_warn)Ú_MATPLOTLIB_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEúPeakSignalNoiseRatio.plotc                       sö   e Zd ZU dZdZeed< dZeed< dZeed< dZ	e
ed< eed	< 	
		d d	ee
ee
e
f f de
ded deeeeedf f  deddf‡ fdd„Zdededdfdd„Zdefdd„Z	d!deeeee f  dee defdd„Z‡  ZS )"ÚPeakSignalNoiseRatioa4  `Compute Peak Signal-to-Noise Ratio`_ (PSNR).

    .. math:: \text{PSNR}(I, J) = 10 * \log_{10} \left(\frac{\max(I)^2}{\text{MSE}(I, J)}\right)

    Where :math:`\text{MSE}` denotes the `mean-squared-error`_ function.

    As input to ``forward`` and ``update`` the metric accepts the following input

    - ``preds`` (:class:`~torch.Tensor`): Predictions from model of shape ``(N,C,H,W)``
    - ``target`` (:class:`~torch.Tensor`): Ground truth values of shape ``(N,C,H,W)``

    As output of `forward` and `compute` the metric returns the following output

    - ``psnr`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average PSNR value
      over sample else returns tensor of shape ``(N,)`` with PSNR values per sample

    Args:
        data_range:
            the range of the data. If a tuple is provided, then the range is calculated as the difference and
            input is clamped between the values.
        base: a base of a logarithm to use.
        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

        dim:
            Dimensions to reduce PSNR scores over, provided as either an integer or a list of integers. Default is
            None meaning scores will be reduced across all dimensions and all batches.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torchmetrics.image import PeakSignalNoiseRatio
        >>> psnr = PeakSignalNoiseRatio(data_range=3.0)
        >>> preds = torch.tensor([[0.0, 1.0], [2.0, 3.0]])
        >>> target = torch.tensor([[3.0, 2.0], [1.0, 0.0]])
        >>> psnr(preds, target)
        tensor(2.5527)

    TÚis_differentiableÚhigher_is_betterFÚfull_state_updateç        Úplot_lower_boundÚ
data_rangeç      $@Úelementwise_meanNÚbaseÚ	reduction)r   ÚsumÚnoneNÚdim.ÚkwargsÚreturnc                    s  t ƒ jdi |¤Ž |d u r|dkrtd|› d�ƒ |d u r2| jdtdƒdd� | jdtd	ƒdd� n| jdg d
d� | jdg d
d� d | _t|tƒrh| jdt|d |d	  ƒdd� tt	j
|d	 |d d�| _n| jdtt|ƒƒdd� || _|| _t|tƒr†t|ƒ| _d S || _d S )Nr   zThe `reduction=z.` will not have any effect when `dim` is None.Úsum_squared_errorr   r   )ÚdefaultÚdist_reduce_fxÚtotalr   Úcatr   é   Úmean)ÚminÚmax© )ÚsuperÚ__init__r   Ú	add_stater   Úclamping_fnÚ
isinstanceÚtupler   ÚtorchÚclampÚfloatr   r   r   r   )Úselfr   r   r   r   r    ©Ú	__class__r+   új/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/image/psnr.pyr-   Q   s    
 "zPeakSignalNoiseRatio.__init__ÚpredsÚtargetc                 C   sø   | j dur|   |¡}|   |¡}t||| jd�\}}| jdu rNt| jtƒs.tdt| jƒ› �ƒ‚t| jtƒs>tdt| jƒ› �ƒ‚|  j|7  _|  j|7  _dS t| jt	ƒs^tdt| jƒ› �ƒ‚t| jt	ƒsntdt| jƒ› �ƒ‚| j 
|¡ | j 
|¡ dS )z*Update state with predictions and targets.N)r   z:Expected `self.sum_squared_error` to be a Tensor, but got z.Expected `self.total` to be a Tensor, but got z8Expected `self.sum_squared_error` to be a list, but got z,Expected `self.total` to be a list, but got )r/   r   r   r0   r"   r   Ú	TypeErrorÚtyper%   ÚlistÚappend)r5   r9   r:   r"   Únum_obsr+   r+   r8   Úupdatep   s*   



ÿÿzPeakSignalNoiseRatio.updatec                 C   sœ   t | jtjƒr| j}nt | jtƒrt dd„ | jD ƒ¡}ntdƒ‚t | jtjƒr,| j}nt | jtƒr>t dd„ | jD ƒ¡}ntdƒ‚t||| j	| j
| jd�S )z.Compute peak signal-to-noise ratio over state.c                 S   ó   g | ]}|  ¡ ‘qS r+   ©Úflatten©Ú.0Úvaluer+   r+   r8   Ú
<listcomp>�   ó    z0PeakSignalNoiseRatio.compute.<locals>.<listcomp>z>Expected sum_squared_error to be a Tensor or a list of Tensorsc                 S   rA   r+   rB   rD   r+   r+   r8   rG   —   rH   z2Expected total to be a Tensor or a list of Tensors)r   r   )r0   r"   r2   r   r=   r&   r;   r%   r
   r   r   r   )r5   r"   r%   r+   r+   r8   Úcompute‹   s   zPeakSignalNoiseRatio.computeÚvalÚaxc                 C   s   |   ||¡S )a
  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> import torch
            >>> from torchmetrics.image import PeakSignalNoiseRatio
            >>> metric = PeakSignalNoiseRatio(data_range=1.0)
            >>> preds = torch.tensor([[0.0, 1.0], [2.0, 3.0]])
            >>> target = torch.tensor([[3.0, 2.0], [1.0, 0.0]])
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.image import PeakSignalNoiseRatio
            >>> metric = PeakSignalNoiseRatio(data_range=1.0)
            >>> preds = torch.tensor([[0.0, 1.0], [2.0, 3.0]])
            >>> target = torch.tensor([[3.0, 2.0], [1.0, 0.0]])
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(values)

        )Ú_plot)r5   rJ   rK   r+   r+   r8   Úplot�   s   ,r   )r   r   N)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   r4   r   r   r1   r	   r   Úintr   r-   r@   rI   r   r   r   rM   Ú__classcell__r+   r+   r6   r8   r       sB   
 *ûþýüûúùÿÿÿþr   )Úcollections.abcr   Ú	functoolsr   Útypingr   r   r   r2   r   r   Útyping_extensionsr	   Ú"torchmetrics.functional.image.psnrr
   r   Útorchmetrics.metricr   Útorchmetrics.utilitiesr   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   r+   r+   r+   r8   Ú<module>   s   