o
    ³ôj   ã                   @   sv  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ededefd	d
„Z	dededefdd„Z
	d3dededeeed f defdd„Z	d4dedee dedededededefdd„Zdededeeef fdd„Zd5deded!ed"edef
d#d$„Zd6deded&edefd'd(„Zd6deded&edefd)d*„Zded+ededefd,d-„Zd.ed/eed0  defd1d2„ZdS )7é    )ÚOptionalÚUnionN)ÚTensor)ÚLiteral)Úrank_zero_warnÚxÚyÚreturnc                 C   s8   | j tjks|j tjkr|  ¡ |j ¡   ¡ S | |j S )zSafe calculation of matrix multiplication.

    If input is float16, will cast to float32 for computation and back again.

    )ÚdtypeÚtorchÚfloat16ÚfloatÚTÚhalf©r   r   © r   úq/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/utilities/compute.pyÚ_safe_matmul   s   
r   c                 C   s   | t  |¡ }d|| dk< |S )z¦Compute x * log(y). Returns 0 if x=0.

    Example:
        >>> import torch
        >>> x = torch.zeros(1)
        >>> _safe_xlogy(x, 1/x)
        tensor([0.])

    ç        r   )r   Úlog)r   r   Úresr   r   r   Ú_safe_xlogy"   s   
r   r   ÚnumÚdenomÚzero_division)ÚwarnÚnanc                 C   s¤   |   ¡ r| n|  ¡ } |  ¡ r|n| ¡ }t|ttfƒs|dkrL|dkr.t |dk¡r.tdƒ |dkr4dn|}tjd|| j| j	d�}t 
|dk| | |¡S t | |¡S )a  Safe division, by preventing division by zero.

    Function will cast to float if input is not already to secure backwards compatibility.

    Args:
        num: numerator tensor
        denom: denominator tensor, which may contain zeros
        zero_division: value to replace elements divided by zero

    Example:
        >>> import torch
        >>> num = torch.tensor([1.0, 2.0, 3.0])
        >>> denom = torch.tensor([0.0, 1.0, 2.0])
        >>> _safe_divide(num, denom)
        tensor([0.0000, 2.0000, 1.5000])

    r   r   z:Detected zero division in _safe_divide. Setting 0/0 to 0.0r   r   )r
   Údevice)Úis_floating_pointr   Ú
isinstanceÚintr   Úanyr   Úfullr
   r   ÚwhereÚtrue_divide)r   r   r   Zzero_division_tensorr   r   r   Ú_safe_divide1   s   r%   é   ÚscoreÚaverageÚ
multilabelÚtpÚfpÚfnÚtop_kc                 C   sz   |d u s|dkr
| S |dkr|| }nt  | ¡}|s.d||dkr(|| | dkn|| dk< t||  |jddd�ƒ d¡S )	NÚnoneÚweightedr   r&   r   éÿÿÿÿT)Úkeepdim)r   Ú	ones_liker%   Úsum)r'   r(   r)   r*   r+   r,   r-   Úweightsr   r   r   Ú_adjust_weights_safe_divideR   s   

(r5   c                 C   sŒ   | j dkr	|  ¡ n| } |j dkr| ¡ n|}| j dks |j dkr,td| j › d|j › �ƒ‚|  ¡ | ¡ krBtd|  ¡ › d| ¡ › �ƒ‚| |fS )z Check that auc input is correct.r&   zJExpected both `x` and `y` tensor to be 1d, but got tensors with dimension z and zHExpected the same number of elements in `x` and `y` tensor but received )ÚndimÚsqueezeÚ
ValueErrorÚnumelr   r   r   r   Ú_auc_format_inputs`   s   ÿÿr:   r0   Ú	directionÚaxisc                 C   sB   t  ¡ � t j|| |d�| }W d  ƒ |S 1 sw   Y  |S )zrCompute area under the curve using the trapezoidal rule.

    Assumes increasing or decreasing order of `x`.

    ©ÚdimN)r   Úno_gradÚtrapz)r   r   r;   r<   Z	auc_scorer   r   r   Ú_auc_compute_without_checkp   s   

ÿþrA   FÚreorderc                 C   s˜   t  ¡ �> |rt j| dd�\} }|| }| dd… | dd…  }|dk  ¡ r3|dk ¡ r/d}ntdƒ‚d	}t| ||ƒW  d  ƒ S 1 sEw   Y  dS )
zñCompute area under the curve using the trapezoidal rule.

    Example:
        >>> import torch
        >>> x = torch.tensor([1, 2, 3, 4])
        >>> y = torch.tensor([1, 2, 3, 4])
        >>> _auc_compute(x, y)
        tensor(7.5000)

    T)Ústabler&   Nr0   r   g      ð¿z_The `x` tensor is neither increasing or decreasing. Try setting the reorder argument to `True`.g      ð?)r   r?   Úsortr!   Úallr8   rA   )r   r   rB   Úx_idxÚdxr;   r   r   r   Ú_auc_compute{   s   
ÿ
$ñrH   c                 C   s   t | |ƒ\} }t| ||d�S )a8  Compute Area Under the Curve (AUC) using the trapezoidal rule.

    Args:
        x: x-coordinates, must be either increasing or decreasing
        y: y-coordinates
        reorder: if True, will reorder the arrays to make it either increasing or decreasing

    Return:
        Tensor containing AUC score

    )rB   )r:   rH   )r   r   rB   r   r   r   Úauc˜   s   rI   Úxpc              	   C   s¨   t |dd… |dd…  |dd… |dd…  ƒ}|dd… ||dd…   }t t | dd…df |ddd…f ¡d¡d }t |dt|ƒd ¡}|| |  ||  S )ai  One-dimensional linear interpolation for monotonically increasing sample points.

    Returns the one-dimensional piecewise linear interpolation to a function with
    given discrete data points :math:`(xp, fp)`, evaluated at :math:`x`.

    Adjusted version of this https://github.com/pytorch/pytorch/issues/50334#issuecomment-1000917964

    Args:
        x: the :math:`x`-coordinates at which to evaluate the interpolated values.
        xp: the :math:`x`-coordinates of the data points, must be increasing.
        fp: the :math:`y`-coordinates of the data points, same length as `xp`.

    Returns:
        the interpolated values, same size as `x`.

    Example:
        >>> x = torch.tensor([0.5, 1.5, 2.5])
        >>> xp = torch.tensor([1, 2, 3])
        >>> fp = torch.tensor([1, 2, 3])
        >>> interp(x, xp, fp)
        tensor([0.5000, 1.5000, 2.5000])

    r&   Nr0   r   )r%   r   r3   ÚgeÚclampÚlen)r   rJ   r+   ÚmÚbÚindicesr   r   r   Úinterp¨   s
   20rQ   ÚtensorÚnormalization)ÚsigmoidÚsoftmaxc                 C   s’   |s| S | j t  d¡kr(t | dk| dk ¡s&|dkr|  ¡ ntj| dd�} | S | dk | dkB  ¡ }t ||dkr@t | ¡| ¡S tj| dd�| ¡S )aÚ  Normalize logits if needed.

    If input tensor is outside the [0,1] we assume that logits are provided and apply the normalization.
    Use torch.where to prevent device-host sync.

    Args:
        tensor: input tensor that may be logits or probabilities
        normalization: normalization method, either 'sigmoid' or 'softmax'

    Returns:
        normalized tensor if needed

    Example:
        >>> import torch
        >>> tensor = torch.tensor([-1.0, 0.0, 1.0])
        >>> normalize_logits_if_needed(tensor, normalization="sigmoid")
        tensor([0.2689, 0.5000, 0.7311])
        >>> tensor = torch.tensor([[-1.0, 0.0, 1.0], [1.0, 0.0, -1.0]])
        >>> normalize_logits_if_needed(tensor, normalization="softmax")
        tensor([[0.0900, 0.2447, 0.6652],
                [0.6652, 0.2447, 0.0900]])
        >>> tensor = torch.tensor([0.0, 0.5, 1.0])
        >>> normalize_logits_if_needed(tensor, normalization="sigmoid")
        tensor([0.0000, 0.5000, 1.0000])

    Úcpur   r&   rT   r=   )r   r   rE   rT   rU   r!   r#   )rR   rS   Ú	conditionr   r   r   Únormalize_logits_if_neededÉ   s   ýýrX   )r   )r&   )r0   )F)Útypingr   r   r   r   Útyping_extensionsr   Útorchmetrics.utilitiesr   r   r   r   r%   ÚstrÚboolr    r5   Útupler:   rA   rH   rI   rQ   rX   r   r   r   r   Ú<module>   sR   ýÿþý
ü"ÿÿÿÿÿÿÿÿ
þ "!