o
    Ðôj%  ã                   @   sŽ   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
mZ d dlmZ d dlmZ d dlmZmZ es=d	gZG d
d„ deƒZdS )é    )ÚSequence)ÚAnyÚOptionalÚUnionN)ÚTensorÚtensor)Ú_psnrb_computeÚ_psnrb_update)ÚMetric)Ú_MATPLOTLIB_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEú*PeakSignalNoiseRatioWithBlockedEffect.plotc                	       sÞ   e Zd ZU dZdZeed< dZeed< dZeed< e	ed< e	ed< e	ed	< e	ed
< 	dd
e
eeeef f de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 )Ú%PeakSignalNoiseRatioWithBlockedEffecta  Computes `Peak Signal to Noise Ratio With Blocked Effect`_ (PSNRB).

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

    Where :math:`\text{MSE}` denotes the `mean-squared-error`_ function. This metric is a modified version of PSNR that
    better supports evaluation of images with blocked artifacts, that oftens occur in compressed images.

    .. attention::
        Metric only supports grayscale images. If you have RGB images, please convert them to grayscale first.

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

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

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

    - ``psnrb`` (:class:`~torch.Tensor`): float scalar tensor with aggregated PSNRB value

    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.
        block_size: integer indication the block size
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torch import rand
        >>> metric = PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0)
        >>> preds = rand(2, 1, 10, 10)
        >>> target = rand(2, 1, 10, 10)
        >>> metric(preds, target)
        tensor(7.2893)

    TÚis_differentiableÚhigher_is_betterFÚfull_state_updateÚsum_squared_errorÚtotalÚbefÚ
data_rangeé   Ú
block_sizeÚkwargsÚreturnNc                    sÌ   t ƒ jdi |¤Ž t|tƒs|dk rtdƒ‚|| _| jdtdƒdd� | jdtdƒdd� | jd	tdƒdd� tˆ tƒrU| jd
tˆ d ˆ d  ƒdd� ‡ fdd„| _	d S | jd
tt
ˆ ƒƒdd� d | _	d S )Né   z4Argument ``block_size`` should be a positive integerr   g        Úsum)ÚdefaultÚdist_reduce_fxr   r   r   r   Úmeanc                    s   t j| ˆ d ˆ d d�S )Nr   r   )ÚminÚmax)ÚtorchÚclamp)Úx©r   © úk/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/image/psnrb.pyÚ<lambda>\   s    z@PeakSignalNoiseRatioWithBlockedEffect.__init__.<locals>.<lambda>r&   )ÚsuperÚ__init__Ú
isinstanceÚintÚ
ValueErrorr   Ú	add_stater   ÚtupleÚclamping_fnÚfloat)Úselfr   r   r   ©Ú	__class__r%   r'   r*   K   s   
 
z.PeakSignalNoiseRatioWithBlockedEffect.__init__ÚpredsÚtargetc                 C   sb   | j dur|   |¡}|   |¡}t||| jd�\}}}|  j|7  _|  j|7  _|  j|7  _dS )z*Update state with predictions and targets.N)r   )r0   r	   r   r   r   r   )r2   r5   r6   r   r   Únum_obsr&   r&   r'   Úupdatea   s   


z,PeakSignalNoiseRatioWithBlockedEffect.updatec                 C   s   t | j| j| j| jƒS )z.Compute peak signal-to-noise ratio over state.)r   r   r   r   r   )r2   r&   r&   r'   Úcomputel   s   z-PeakSignalNoiseRatioWithBlockedEffect.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 PeakSignalNoiseRatioWithBlockedEffect
            >>> metric = PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0)
            >>> metric.update(torch.rand(2, 1, 10, 10), torch.rand(2, 1, 10, 10))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.image import PeakSignalNoiseRatioWithBlockedEffect
            >>> metric = PeakSignalNoiseRatioWithBlockedEffect(data_range=1.0)
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(torch.rand(2, 1, 10, 10), torch.rand(2, 1, 10, 10)))
            >>> fig_, ax_ = metric.plot(values)

        )Ú_plot)r2   r:   r;   r&   r&   r'   Úplotp   s   (r   )r   )NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   r   r1   r/   r,   r   r*   r8   r9   r   r   r   r   r=   Ú__classcell__r&   r&   r3   r'   r      s:   
 $ýþýüûÿÿÿþr   )Úcollections.abcr   Útypingr   r   r   r"   r   r   Ú#torchmetrics.functional.image.psnrbr   r	   Útorchmetrics.metricr
   Útorchmetrics.utilities.importsr   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   r&   r&   r&   r'   Ú<module>   s   