o
    .wi;                     @   s   d dl mZ d dl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 dd	giZesAg d
ZG dd deZG dd deZG dd deZdS )    )Sequence)AnyOptionalUnion)Tensortensor)'scale_invariant_signal_distortion_ratiosignal_distortion_ratio)source_aggregated_signal_distortion_ratio)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPESignalDistortionRatiofast_bss_eval)SignalDistortionRatio.plot(ScaleInvariantSignalDistortionRatio.plot*SourceAggregatedSignalDistortionRatio.plotc                       s   e Zd ZU dZeed< eed< dZeed< dZeed< dZ	eed< d	Z
ee ed
< d	Zee ed< 						ddee dedede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 d	f dee defddZ  ZS )!r   a	  Calculate Signal to Distortion Ratio (SDR) metric.

    See `SDR ref1`_ and `SDR ref2`_ for details on the metric.

    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

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

    .. note:
        The metric currently does not seem to work with Pytorch v1.11 and specific GPU hardware.

    Args:
        use_cg_iter:
            If provided, conjugate gradient descent is used to solve for the distortion
            filter coefficients instead of direct Gaussian elimination, which requires that
            ``fast-bss-eval`` is installed and pytorch version >= 1.8.
            This can speed up the computation of the metrics in case the filters
            are long. Using a value of 10 here has been shown to provide
            good accuracy in most cases and is sufficient when using this
            loss to train neural separation networks.
        filter_length: The length of the distortion filter allowed
        zero_mean:
            When set to True, the mean of all signals is subtracted prior to computation of the metrics
        load_diag:
            If provided, this small value is added to the diagonal coefficients of the system metrics when solving
            for the filter coefficients. This can help stabilize the metric in the case where some reference
            signals may sometimes be zero
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torch import randn
        >>> from torchmetrics.audio import SignalDistortionRatio
        >>> preds = randn(8000)
        >>> target = randn(8000)
        >>> sdr = SignalDistortionRatio()
        >>> sdr(preds, target)
        tensor(-11.9930)
        >>> # use with pit
        >>> from torchmetrics.audio import PermutationInvariantTraining
        >>> from torchmetrics.functional.audio import signal_distortion_ratio
        >>> preds = randn(4, 2, 8000)  # [batch, spk, time]
        >>> target = randn(4, 2, 8000)
        >>> pit = PermutationInvariantTraining(signal_distortion_ratio,
        ...     mode="speaker-wise", eval_func="max")
        >>> pit(preds, target)
        tensor(-11.7277)

    sum_sdrtotalFfull_state_updateTis_differentiablehigher_is_betterNplot_lower_boundplot_upper_bound   use_cg_iterfilter_length	zero_mean	load_diagkwargsreturnc                    sV   t  jdi | || _|| _|| _|| _| jdtddd | jdtddd d S )Nr           sumdefaultdist_reduce_fxr   r    )super__init__r   r   r   r   	add_stater   )selfr   r   r   r   r    	__class__r'   S/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/audio/sdr.pyr)   e   s   zSignalDistortionRatio.__init__predstargetc                 C   sB   t ||| j| j| j| j}|  j| 7  _|  j| 7  _dS *Update state with predictions and targets.N)	r	   r   r   r   r   r   r#   r   numel)r+   r/   r0   	sdr_batchr'   r'   r.   updatew   s
   zSignalDistortionRatio.updatec                 C      | j | j S zCompute metric.)r   r   r+   r'   r'   r.   compute      zSignalDistortionRatio.computevalaxc                 C      |  ||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 SignalDistortionRatio
            >>> metric = SignalDistortionRatio()
            >>> metric.update(torch.rand(8000), torch.rand(8000))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

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

        _plotr+   r;   r<   r'   r'   r.   plot      &r   )Nr   FNNN)__name__
__module____qualname____doc__r   __annotations__r   boolr   r   r   r   floatr   intr   r)   r5   r9   r   r   r   r   rA   __classcell__r'   r'   r,   r.   r   &   s:   
 6	2c                       s   e Zd ZU dZdZdZeed< eed< dZe	e
 ed< dZe	e
 ed< 	d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 )#ScaleInvariantSignalDistortionRatioa  `Scale-invariant signal-to-distortion ratio`_ (SI-SDR).

    The SI-SDR value is in general considered an overall measure of how good a source sound.

    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_sdr`` (:class:`~torch.Tensor`): float scalar tensor with average SI-SDR 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 ScaleInvariantSignalDistortionRatio
        >>> target = tensor([3.0, -0.5, 2.0, 7.0])
        >>> preds = tensor([2.5, 0.0, 2.0, 8.0])
        >>> si_sdr = ScaleInvariantSignalDistortionRatio()
        >>> si_sdr(preds, target)
        tensor(18.4030)

    T
sum_si_sdrr   Nr   r   Fr   r    r!   c                    sD   t  jdi | || _| jdtddd | jdtddd d S )NrN   r"   r#   r$   r   r   r'   )r(   r)   r   r*   r   )r+   r   r    r,   r'   r.   r)      s   z,ScaleInvariantSignalDistortionRatio.__init__r/   r0   c                 C   s8   t ||| jd}|  j| 7  _|  j| 7  _dS )r2   )r/   r0   r   N)r   r   rN   r#   r   r3   )r+   r/   r0   si_sdr_batchr'   r'   r.   r5      s   z*ScaleInvariantSignalDistortionRatio.updatec                 C   r6   r7   )rN   r   r8   r'   r'   r.   r9      r:   z+ScaleInvariantSignalDistortionRatio.computer;   r<   c                 C   r=   )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 ScaleInvariantSignalDistortionRatio
            >>> target = torch.randn(5)
            >>> preds = torch.randn(5)
            >>> metric = ScaleInvariantSignalDistortionRatio()
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.audio import ScaleInvariantSignalDistortionRatio
            >>> target = torch.randn(5)
            >>> preds = torch.randn(5)
            >>> metric = ScaleInvariantSignalDistortionRatio()
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(values)

        r>   r@   r'   r'   r.   rA      s   ,r   )FrC   )rD   rE   rF   rG   r   r   r   rH   r   r   rJ   r   rI   r   r)   r5   r9   r   r   r   r   rA   rL   r'   r'   r,   r.   rM      s4   
  rM   c                	       s   e Zd ZU dZeed< eed< dZeed< dZeed< dZ	eed< d	Z
ee ed
< d	Zee ed< 		dde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 d	f dee defddZ  ZS )%SourceAggregatedSignalDistortionRatioaL  `Source-aggregated signal-to-distortion ratio`_ (SA-SDR).

    The SA-SDR is proposed to provide a stable gradient for meeting style source separation, where
    one-speaker and multiple-speaker scenes coexist.

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

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

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

    - ``sa_sdr`` (:class:`~torch.Tensor`): float scalar tensor with average SA-SDR value over samples

    Args:
        preds: float tensor with shape ``(..., spk, time)``
        target: float tensor with shape ``(..., spk, time)``
        scale_invariant: if True, scale the targets of different speakers with the same alpha
        zero_mean: If to zero mean target and preds or not
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torch import randn
        >>> from torchmetrics.audio import SourceAggregatedSignalDistortionRatio
        >>> preds = randn(2, 8000) # [..., spk, time]
        >>> target = randn(2, 8000)
        >>> sasdr = SourceAggregatedSignalDistortionRatio()
        >>> sasdr(preds, target)
        tensor(-50.8171)
        >>> # use with pit
        >>> from torchmetrics.audio import PermutationInvariantTraining
        >>> from torchmetrics.functional.audio import source_aggregated_signal_distortion_ratio
        >>> preds = randn(4, 2, 8000)  # [batch, spk, time]
        >>> target = randn(4, 2, 8000)
        >>> pit = PermutationInvariantTraining(source_aggregated_signal_distortion_ratio,
        ...     mode="permutation-wise", eval_func="max")
        >>> pit(preds, target)
        tensor(-43.9780)

    msummnumFr   Tr   r   Nr   r   scale_invariantr   r    r!   c                    sz   t  jd	i | t|tstd| || _t|ts$td| || _| jdtddd | jdtddd d S )
Nz9Expected argument `scale_invarint` to be a bool, but got z4Expected argument `zero_mean` to be a bool, but got rQ   r"   r#   r$   rR   r   r'   )	r(   r)   
isinstancerI   
ValueErrorrS   r   r*   r   )r+   rS   r   r    r,   r'   r.   r)   L  s   

z.SourceAggregatedSignalDistortionRatio.__init__r/   r0   c                 C   s:   t ||| j| j}|  j| 7  _|  j| 7  _dS r1   )r
   rS   r   rQ   r#   rR   r3   )r+   r/   r0   mbatchr'   r'   r.   r5   ^  s   z,SourceAggregatedSignalDistortionRatio.updatec                 C   r6   r7   )rQ   rR   r8   r'   r'   r.   r9   e  r:   z-SourceAggregatedSignalDistortionRatio.computer;   r<   c                 C   r=   )af  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 SourceAggregatedSignalDistortionRatio
            >>> metric = SourceAggregatedSignalDistortionRatio()
            >>> metric.update(torch.rand(2,8000), torch.rand(2,8000))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

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

        r>   r@   r'   r'   r.   rA   i  rB   r   )TFrC   )rD   rE   rF   rG   r   rH   r   rI   r   r   r   r   rJ   r   r   r)   r5   r9   r   r   r   r   rA   rL   r'   r'   r,   r.   rP     s.   
 )2rP   N)collections.abcr   typingr   r   r   torchr   r   !torchmetrics.functional.audio.sdrr   r	   r
   torchmetrics.metricr   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_requires____doctest_skip__r   rM   rP   r'   r'   r'   r.   <module>   s   
 m