o
    yiL%                     @   s  d dl Z d dlZd dlmZmZ d dlZd dlmZ d dlmZ d dl	m
Z
 d dlmZ ejjZer9d dlmZ ndZded	efd
dZdededed	eeef fddZ				ddededee dededee d	efddZddededed	efddZdS )    N)OptionalTuple)Tensor)norm)_check_same_shape)_FAST_BSS_EVAL_AVAILABLE)toeplitz_conjugate_gradientvectorreturnc                 C   sl   t jt j| dd| dddf gdd}| jd }t j||jdd ||f | dd d d	jddS )
a  Construct a symmetric Toeplitz matrix using one vector.

    Args:
        vector: shape [..., L]

    Example:
        >>> from torchmetrics.functional.audio.sdr import _symmetric_toeplitz
        >>> import torch
        >>> v = torch.tensor([0, 1, 2, 3, 4])
        >>> _symmetric_toeplitz(v)
        tensor([[0, 1, 2, 3, 4],
                [1, 0, 1, 2, 3],
                [2, 1, 0, 1, 2],
                [3, 2, 1, 0, 1],
                [4, 3, 2, 1, 0]])

    Returns:
        a symmetric Toeplitz matrix of shape [..., L, L]
    ))dims.   Nr   dim)r   r   )sizestride)torchcatflipshape
as_stridedr   )r	   vec_expv_len r   U/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/functional/audio/sdr.py_symmetric_toeplitz$   s   (
(r   targetpredscorr_lenc                 C   s   dt t |jd | jd  d  }tjj| |dd}tjj|jd |j	d  |ddd|f }tjj||dd}tjj|
 | |dddd|f }||fS )a	  Compute the auto correlation of `target` and the cross correlation of `target` and `preds` using the fast
    Fourier transform (FFT). Let's denotes the symmetric Toeplitz matric of the auto correlation of `target` as
    `R`, the cross correlation as 'b', then solving the equation `Rh=b` could have `h` as the coordinate of `preds`
    in the column space of the `corr_len` shifts of `target`.

    Args:
        target: the target (reference) signal of shape [..., time]
        preds: the preds (estimated) signal of shape [..., time]
        corr_len: the length of the auto correlation and cross correlation

    Returns:
        the auto correlation of `target` of shape [..., corr_len]
        the cross correlation of `target` and `preds` of shape [..., corr_len]
       r   r   )nr   )r    .N)mathceillog2r   r   fftrfftirfftrealimagconj)r   r   r   n_fftt_fftr_0p_fftbr   r   r   _compute_autocorr_crosscorr?   s   (,&r/      Fuse_cg_iterfilter_length	zero_mean	load_diagc                 C   s.  t | | | j}|  } | }|r$| | jddd } ||jddd }|tjt|ddddd }| tjt| ddddd } t|| |d\}}|durU|d  |7  < |durctrct	|||d	}	n|durotsot
d
t t|}
t|
|}	td||	}|d|  }dt| }|tjkr|S | S )ay	  Calculates Signal to Distortion Ratio (SDR) metric. See `SDR ref1`_ and `SDR ref2`_ for details on the
    metric.

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

    Args:
        preds: float tensor with shape ``(...,time)``
        target: float tensor with shape ``(...,time)``
        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

    Returns:
        Float tensor with shape ``(...,)`` of SDR values per sample

    Raises:
        RuntimeError:
            If ``preds`` and ``target`` does not have the same shape

    Example:
        >>> from torchmetrics.functional.audio import signal_distortion_ratio
        >>> import torch
        >>> g = torch.manual_seed(1)
        >>> preds = torch.randn(8000)
        >>> target = torch.randn(8000)
        >>> signal_distortion_ratio(preds, target)
        tensor(-12.0589)
        >>> # use with permutation_invariant_training
        >>> from torchmetrics.functional.audio import permutation_invariant_training
        >>> preds = torch.randn(4, 2, 8000)  # [batch, spk, time]
        >>> target = torch.randn(4, 2, 8000)
        >>> best_metric, best_perm = permutation_invariant_training(preds, target, signal_distortion_ratio, 'max')
        >>> best_metric
        tensor([-11.6375, -11.4358, -11.7148, -11.6325])
        >>> best_perm
        tensor([[1, 0],
                [0, 1],
                [1, 0],
                [0, 1]])
    r   Tr   keepdimgư>)min)r   N).r   )n_itera  The `use_cg_iter` parameter of `SDR` requires that `fast-bss-eval` is installed. To make this this warning disappear, you could install `fast-bss-eval` using `pip install fast-bss-eval` or set `use_cg_iter=None`. For this time, the solver provided by Pytorch is used.z...l,...l->...r   g      $@)r   dtypedoublemeanr   clampr   r/   r   r   warningswarnUserWarningr   solveeinsumlog10float64float)r   r   r1   r2   r3   r4   preds_dtyper,   r.   solrcohratiovalr   r   r   signal_distortion_ratio]   s8   
<

rK   c                 C   s   t | | t| jj}|r"|tj|ddd }| tj| ddd } tj| | ddd| tj|d ddd|  }|| }||  }tj|d dd| tj|d dd|  }dt| }|S )a=  `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.

    Args:
        preds: float tensor with shape ``(...,time)``
        target: float tensor with shape ``(...,time)``
        zero_mean: If to zero mean target and preds or not

    Returns:
        Float tensor with shape ``(...,)`` of SDR values per sample

    Raises:
        RuntimeError:
            If ``preds`` and ``target`` does not have the same shape

    Example:
        >>> from torchmetrics.functional.audio import scale_invariant_signal_distortion_ratio
        >>> target = torch.tensor([3.0, -0.5, 2.0, 7.0])
        >>> preds = torch.tensor([2.5, 0.0, 2.0, 8.0])
        >>> scale_invariant_signal_distortion_ratio(preds, target)
        tensor(18.4030)
    r   Tr5   r   r   
   )r   r   finfor9   epsr;   sumrB   )r   r   r3   rN   alphatarget_scalednoiserJ   r   r   r   'scale_invariant_signal_distortion_ratio   s   
,rS   )Nr0   FN)F)r!   r=   typingr   r   r   r   torch.linalgr   torchmetrics.utilities.checksr   torchmetrics.utilities.importsr   linalgr@   fast_bss_eval.torch.cgdr   r   intr/   boolrD   rK   rS   r   r   r   r   <module>   sD   "!
 q