a
    d1                     @   s   d dl mZmZmZmZ d dlmZmZ d dlm	Z	m
Z
mZ d dlmZ d dlmZ d dlmZmZ espg dZG dd	 d	eZG d
d deZG dd deZdS )    )AnyOptionalSequenceUnion)Tensortensor)*complex_scale_invariant_signal_noise_ratio"scale_invariant_signal_noise_ratiosignal_noise_ratio)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPE)SignalNoiseRatio.plot#ScaleInvariantSignalNoiseRatio.plot*ComplexScaleInvariantSignalNoiseRatio.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< d	Z
ee ed
< d	Zee ed< deed	d fddZe	e	d	dddZe	dddZdeee	ee	 f  ee edddZ  ZS )SignalNoiseRatioa3  Calculate `Signal-to-noise ratio`_ (SNR_) meric for evaluating quality of audio.

    .. math::
        \text{SNR} = \frac{P_{signal}}{P_{noise}}

    where  :math:`P` denotes the power of each signal. The SNR metric compares the level of the desired signal to
    the level of background noise. Therefore, a high value of SNR means that the audio is clear.

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

    - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``
    - ``target`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``

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

    - ``snr`` (:class:`~torch.Tensor`): float scalar tensor with average SNR value over samples

    Args:
        zero_mean: if to zero mean target and preds or not
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        TypeError:
            if target and preds have a different shape

    Example:
        >>> from torch import tensor
        >>> from torchmetrics.audio import SignalNoiseRatio
        >>> target = tensor([3.0, -0.5, 2.0, 7.0])
        >>> preds = tensor([2.5, 0.0, 2.0, 8.0])
        >>> snr = SignalNoiseRatio()
        >>> snr(preds, target)
        tensor(16.1805)

    Ffull_state_updateTis_differentiablehigher_is_bettersum_snrtotalNplot_lower_boundplot_upper_bound	zero_meankwargsreturnc                    sD   t  jf i | || _| jdtddd | jdtddd d S )Nr           sumdefaultZdist_reduce_fxr   r   )super__init__r   	add_stater   selfr   r   	__class__ _/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/audio/snr.pyr#   O   s    zSignalNoiseRatio.__init__predstargetr   c                 C   s8   t ||| jd}|  j| 7  _|  j| 7  _dS *Update state with predictions and targets.)r,   r-   r   N)r
   r   r   r   r   numel)r&   r,   r-   Z	snr_batchr)   r)   r*   updateZ   s    zSignalNoiseRatio.updater   c                 C   s   | j | j S zCompute metric.)r   r   r&   r)   r)   r*   computea   s    zSignalNoiseRatio.computevalaxr   c                 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.audio import SignalNoiseRatio
            >>> metric = SignalNoiseRatio()
            >>> metric.update(torch.rand(4), torch.rand(4))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.audio import SignalNoiseRatio
            >>> metric = SignalNoiseRatio()
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(torch.rand(4), torch.rand(4)))
            >>> fig_, ax_ = metric.plot(values)

        Z_plotr&   r7   r8   r)   r)   r*   plote   s    (r   )F)NN)__name__
__module____qualname____doc__r   bool__annotations__r   r   r   r   r   floatr   r   r#   r1   r5   r   r   r   r   r;   __classcell__r)   r)   r'   r*   r   #   s*   
#  r   c                       s   e Zd ZU dZdZeed< eed< dZdZe	e
 ed< dZe	e
 ed< edd fd	d
ZeeddddZedddZdeeee df e	e edddZ  ZS )ScaleInvariantSignalNoiseRatioa7  Calculate `Scale-invariant signal-to-noise ratio`_ (SI-SNR) metric for evaluating quality of audio.

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

    - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``
    - ``target`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``

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

    - ``si_snr`` (:class:`~torch.Tensor`): float scalar tensor with average SI-SNR value over samples

    Args:
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        TypeError:
            if target and preds have a different shape

    Example:
        >>> import torch
        >>> from torch import tensor
        >>> from torchmetrics.audio import ScaleInvariantSignalNoiseRatio
        >>> target = tensor([3.0, -0.5, 2.0, 7.0])
        >>> preds = tensor([2.5, 0.0, 2.0, 8.0])
        >>> si_snr = ScaleInvariantSignalNoiseRatio()
        >>> si_snr(preds, target)
        tensor(15.0918)

    T
sum_si_snrr   Nr   r   )r   r   c                    s>   t  jf i | | jdtddd | jdtddd d S )NrE   r   r   r    r   r   )r"   r#   r$   r   )r&   r   r'   r)   r*   r#      s    z'ScaleInvariantSignalNoiseRatio.__init__r+   c                 C   s4   t ||d}|  j| 7  _|  j| 7  _dS )r/   )r,   r-   N)r	   rE   r   r   r0   )r&   r,   r-   Zsi_snr_batchr)   r)   r*   r1      s    z%ScaleInvariantSignalNoiseRatio.updater2   c                 C   s   | j | j S r3   )rE   r   r4   r)   r)   r*   r5      s    z&ScaleInvariantSignalNoiseRatio.computer6   c                 C   s   |  ||S )a6  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.audio import ScaleInvariantSignalNoiseRatio
            >>> metric = ScaleInvariantSignalNoiseRatio()
            >>> metric.update(torch.rand(4), torch.rand(4))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.audio import ScaleInvariantSignalNoiseRatio
            >>> metric = ScaleInvariantSignalNoiseRatio()
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(torch.rand(4), torch.rand(4)))
            >>> fig_, ax_ = metric.plot(values)

        r9   r:   r)   r)   r*   r;      s    &r   )NN)r<   r=   r>   r?   r   r   rA   r   r   r   rB   r   r   r#   r1   r5   r   r   r   r   r;   rC   r)   r)   r'   r*   rD      s   
	rD   c                       s   e Zd ZU dZdZeed< eed< dZdZe	e
 ed< dZe	e
 ed< deedd	 fd
dZeeddddZedddZdeeee df e	e edddZ  ZS )%ComplexScaleInvariantSignalNoiseRatioa!  Calculate `Complex scale-invariant signal-to-noise ratio`_ (C-SI-SNR) metric for evaluating quality of audio.

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

    - ``preds`` (:class:`~torch.Tensor`): real float tensor with shape ``(...,frequency,time,2)`` or complex float
      tensor with shape ``(..., frequency,time)``

    - ``target`` (:class:`~torch.Tensor`): real float tensor with shape ``(...,frequency,time,2)`` or complex float
      tensor with shape ``(..., frequency,time)``

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

    - ``c_si_snr`` (:class:`~torch.Tensor`): float scalar tensor with average C-SI-SNR value over samples

    Args:
        zero_mean: if to zero mean target and preds or not
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``zero_mean`` is not an bool
        TypeError:
            If ``preds`` is not the shape (..., frequency, time, 2) (after being converted to real if it is complex).
            If ``preds`` and ``target`` does not have the same shape.

    Example:
        >>> import torch
        >>> from torch import tensor
        >>> from torchmetrics.audio import ComplexScaleInvariantSignalNoiseRatio
        >>> g = torch.manual_seed(1)
        >>> preds = torch.randn((1,257,100,2))
        >>> target = torch.randn((1,257,100,2))
        >>> c_si_snr = ComplexScaleInvariantSignalNoiseRatio()
        >>> c_si_snr(preds, target)
        tensor(-63.4849)

    T
ci_snr_sumnumNr   r   Fr   c                    s\   t  jf i | t|ts*td| || _| jdtddd | jdtddd d S )Nz5Expected argument `zero_mean` to be an bool, but got rG   r   r   r    rH   r   )r"   r#   
isinstancer@   
ValueErrorr   r$   r   r%   r'   r)   r*   r#   !  s    
z.ComplexScaleInvariantSignalNoiseRatio.__init__r+   c                 C   s8   t ||| jd}|  j| 7  _|  j| 7  _dS r.   )r   r   rG   r   rH   r0   )r&   r,   r-   vr)   r)   r*   r1   .  s    z,ComplexScaleInvariantSignalNoiseRatio.updater2   c                 C   s   | j | j S r3   )rG   rH   r4   r)   r)   r*   r5   5  s    z-ComplexScaleInvariantSignalNoiseRatio.computer6   c                 C   s   |  ||S )az  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.audio import ComplexScaleInvariantSignalNoiseRatio
            >>> metric = ComplexScaleInvariantSignalNoiseRatio()
            >>> metric.update(torch.rand(1,257,100,2), torch.rand(1,257,100,2))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.audio import ComplexScaleInvariantSignalNoiseRatio
            >>> metric = ComplexScaleInvariantSignalNoiseRatio()
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(torch.rand(1,257,100,2), torch.rand(1,257,100,2)))
            >>> fig_, ax_ = metric.plot(values)

        r9   r:   r)   r)   r*   r;   9  s    &r   )F)NN)r<   r=   r>   r?   r   r   rA   r   r   r   rB   r   r@   r   r#   r1   r5   r   r   r   r   r;   rC   r)   r)   r'   r*   rF      s    
& rF   N)typingr   r   r   r   Ztorchr   r   Z!torchmetrics.functional.audio.snrr   r	   r
   Ztorchmetrics.metricr   Ztorchmetrics.utilities.importsr   Ztorchmetrics.utilities.plotr   r   Z__doctest_skip__r   rD   rF   r)   r)   r)   r*   <module>   s   mc