o
    yi0                     @   sj   d dl mZmZ d dlmZmZ d dlmZmZ d dl	m
Z
 ddgiZG dd de
ZG dd	 d	e
Zd
S )    )AnyOptional)Tensortensor)'scale_invariant_signal_distortion_ratiosignal_distortion_ratio)MetricSignalDistortionRatiofast_bss_evalc                       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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  ZS )r	   a	  Calculates 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 torchmetrics.audio import SignalDistortionRatio
        >>> import torch
        >>> g = torch.manual_seed(1)
        >>> preds = torch.randn(8000)
        >>> target = torch.randn(8000)
        >>> sdr = SignalDistortionRatio()
        >>> sdr(preds, target)
        tensor(-12.0589)
        >>> # use with pit
        >>> from torchmetrics.audio import PermutationInvariantTraining
        >>> from torchmetrics.functional.audio import signal_distortion_ratio
        >>> preds = torch.randn(4, 2, 8000)  # [batch, spk, time]
        >>> target = torch.randn(4, 2, 8000)
        >>> pit = PermutationInvariantTraining(signal_distortion_ratio, 'max')
        >>> pit(preds, target)
        tensor(-11.6051)
    sum_sdrtotalFfull_state_updateTis_differentiablehigher_is_betterN   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   J/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/audio/sdr.pyr   S   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$   r%   	sdr_batchr   r   r#   updatee   s
   zSignalDistortionRatio.updatec                 C      | j | j S zComputes metric.)r   r   r    r   r   r#   computen      zSignalDistortionRatio.compute)Nr   FN)__name__
__module____qualname____doc__r   __annotations__r   boolr   r   r   intfloatr   r   r)   r-   __classcell__r   r   r!   r#   r	      s4   
 4	c                       sp   e Zd ZU dZdZdZeed< 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  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:
        >>> import torch
        >>> from torchmetrics import ScaleInvariantSignalDistortionRatio
        >>> target = torch.tensor([3.0, -0.5, 2.0, 7.0])
        >>> preds = torch.tensor([2.5, 0.0, 2.0, 8.0])
        >>> si_sdr = ScaleInvariantSignalDistortionRatio()
        >>> si_sdr(preds, target)
        tensor(18.4030)
    T
sum_si_sdrr   Fr   r   r   Nc                    sD   t  jdi | || _| jdtddd | jdtddd d S )Nr9   r   r   r   r   r   r   )r   r   r   r   r   )r    r   r   r!   r   r#   r      s   z,ScaleInvariantSignalDistortionRatio.__init__r$   r%   c                 C   s8   t ||| jd}|  j| 7  _|  j| 7  _dS )r&   )r$   r%   r   N)r   r   r9   r   r   r'   )r    r$   r%   si_sdr_batchr   r   r#   r)      s   z*ScaleInvariantSignalDistortionRatio.updatec                 C   r*   r+   )r9   r   r,   r   r   r#   r-      r.   z+ScaleInvariantSignalDistortionRatio.compute)F)r/   r0   r1   r2   r   r   r   r3   r4   r   r   r)   r-   r7   r   r   r!   r#   r8   s   s    
 r8   N)typingr   r   torchr   r   !torchmetrics.functional.audio.sdrr   r   torchmetrics.metricr   __doctest_requires__r	   r8   r   r   r   r#   <module>   s   
[