o
    ²ôjo#  ã                	   @   s$  d dl Z d dlmZ d dlmZmZ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mZ d dlmZ d	Zd
eeee f defdd„Zd
edefdd„Zd
edefdd„Zd
edefdd„Zd
edefdd„Zd
edefdd„Zd
edeeef fdd„Z	d?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@d#ed$ed edefd%d&„Z"dAd
ed'edefd(d)„Z#d
edefd*d+„Z$d,edefd-d.„Z%d?d
ed/ee defd0d1„Z&dBd
ed ee d2eej' defd3d4„Z(d
edefd5d6„Z)d7ed8edefd9d:„Z*d
ed;ed<edefd=d>„Z+dS )Cé    N)ÚSequence)ÚAnyÚListÚOptionalÚUnion)Úapply_to_collection)ÚTensor)ÚTorchMetricsUserWarning)Ú_TORCH_LESS_THAN_2_6Ú_XLA_AVAILABLE)Úrank_zero_warng�íµ ÷Æ°>ÚxÚreturnc                 C   s8   t | tjƒr| S dd„ | D ƒ} | stdƒ‚tj| dd�S )z'Concatenation along the zero dimension.c                 S   s0   g | ]}|  ¡ d kr|jdkr| d¡n|‘qS )é   r   )ÚnumelÚndimÚ	unsqueeze)Ú.0Úy© r   ún/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/utilities/data.pyÚ
<listcomp>!   s   0 z dim_zero_cat.<locals>.<listcomp>zNo samples to concatenater   ©Údim)Ú
isinstanceÚtorchr   Ú
ValueErrorÚcat©r   r   r   r   Údim_zero_cat   s   r   c                 C   ó   t j| dd�S )z#Summation along the zero dimension.r   r   )r   Úsumr   r   r   r   Údim_zero_sum'   ó   r"   c                 C   r    )z!Average along the zero dimension.r   r   )r   Úmeanr   r   r   r   Údim_zero_mean,   r#   r%   c                 C   ó   t j| dd�jS )zMax along the zero dimension.r   r   )r   ÚmaxÚvaluesr   r   r   r   Údim_zero_max1   ó   r)   c                 C   r&   )zMin along the zero dimension.r   r   )r   Úminr(   r   r   r   r   Údim_zero_min6   r*   r,   c                 C   s   dd„ | D ƒS )z&Flatten list of list into single list.c                 S   s   g | ]	}|D ]}|‘qqS r   r   )r   ÚsublistÚitemr   r   r   r   =   s    z_flatten.<locals>.<listcomp>r   r   r   r   r   Ú_flatten;   r#   r/   c                 C   sh   i }d}|   ¡ D ]'\}}t|tƒr%|  ¡ D ]\}}||v rd}|||< qq||v r+d}|||< q||fS )zYFlatten dict of dicts into single dict and checking for duplicates in keys along the way.FT)Úitemsr   Údict)r   Únew_dictÚ
duplicatesÚkeyÚvalueÚkÚvr   r   r   Ú_flatten_dict@   s   

ý
r8   Úlabel_tensorÚnum_classesc                 C   sr   |du rt |  ¡  ¡  ¡ d ƒ}tj| jd |g| jdd… ¢R | j| jdœŽ}|  	¡  
d¡ |¡}| d|d¡S )a¥  Convert  a dense label tensor to one-hot format.

    Args:
        label_tensor: dense label tensor, with shape [N, d1, d2, ...]
        num_classes: number of classes C

    Returns:
        A sparse label tensor with shape [N, C, d1, d2, ...]

    Example:
        >>> x = torch.tensor([1, 2, 3])
        >>> to_onehot(x)
        tensor([[0, 1, 0, 0],
                [0, 0, 1, 0],
                [0, 0, 0, 1]])

    Nr   r   )ÚdtypeÚdeviceç      ð?)Úintr'   Údetachr.   r   ÚzerosÚshaper;   r<   Úlongr   Ú	expand_asÚscatter_)r9   r:   Ztensor_onehotÚindexr   r   r   Ú	to_onehotQ   s   þýûrF   r   r6   r   c                 C   sF   | j tjkr| jstj| |dd� |¡}| |d|¡S | j||d�jS )z3torch.top_k does not support half precision on CPU.T)r   Ústabler   ©r6   r   )	r;   r   ÚhalfÚis_cudaÚargsortÚflipÚnarrowÚtopkÚindices)r   r6   r   Úidxr   r   r   Ú"_top_k_with_half_precision_supportt   s   rQ   Úprob_tensorrN   c                 C   sX   t j| t jd�}|dkr| || j|dd�d¡ | ¡ S | |t| ||d�d¡ | ¡ S )aw  Convert a probability tensor to binary by selecting top-k the highest entries.

    Args:
        prob_tensor: dense tensor of shape ``[..., C, ...]``, where ``C`` is in the
            position defined by the ``dim`` argument
        topk: number of the highest entries to turn into 1s
        dim: dimension on which to compare entries

    Returns:
        A binary tensor of the same shape as the input tensor of type ``torch.int32``

    Example:
        >>> x = torch.tensor([[1.1, 2.0, 3.0], [2.0, 1.0, 0.5]])
        >>> select_topk(x, topk=2)
        tensor([[0, 1, 1],
                [1, 1, 0]], dtype=torch.int32)

    ©r;   r   T)r   Úkeepdimr=   rH   )r   Ú
zeros_liker>   rD   ÚargmaxrQ   )rR   rN   r   Ztopk_tensorr   r   r   Úselect_topk|   s   ÿrW   Ú
argmax_dimc                 C   s   t j| |d�S )aw  Convert  a tensor of probabilities to a dense label tensor.

    Args:
        x: probabilities to get the categorical label [N, d1, d2, ...]
        argmax_dim: dimension to apply

    Return:
        A tensor with categorical labels [N, d2, ...]

    Example:
        >>> x = torch.tensor([[0.2, 0.5], [0.9, 0.1]])
        >>> to_categorical(x)
        tensor([1, 0])

    r   )r   rV   )r   rX   r   r   r   Úto_categorical—   s   rY   c                 C   s   |   ¡ dkr
|  ¡ S | S )Nr   )r   Úsqueezer   r   r   r   Ú_squeeze_scalar_element_tensorª   s   r[   Údatac                 C   s   t | ttƒS ©N)r   r   r[   )r\   r   r   r   Ú_squeeze_if_scalar®   s   r^   Ú	minlengthc                 C   sn   |du rt t | ¡ƒ}t ¡ sts| jr0tj|| jd� t | ƒd¡}t 	|  
dd¡|¡jdd�S tj| |d�S )a   Implement custom bincount.

    PyTorch currently does not support ``torch.bincount`` when running in deterministic mode on GPU or when running
    MPS devices or when running on XLA device. This implementation therefore falls back to using a combination of
    `torch.arange` and `torch.eq` in these scenarios. A small performance hit can expected and higher memory consumption
    as `[batch_size, mincount]` tensor needs to be initialized compared to native ``torch.bincount``.

    Args:
        x: tensor to count
        minlength: minimum length to count

    Returns:
        Number of occurrences for each unique element in x

    Example:
        >>> x = torch.tensor([0,0,0,1,1,2,2,2,2])
        >>> _bincount(x, minlength=3)
        tensor([3, 2, 4])

    N)r<   r   éÿÿÿÿr   r   ©r_   )Úlenr   ÚuniqueÚ$are_deterministic_algorithms_enabledr   Úis_mpsÚaranger<   ÚrepeatÚeqÚreshaper!   Úbincount)r   r_   Úmeshr   r   r   Ú	_bincount²   s   rl   r;   c                 C   s\   t  ¡ o
| jo
|  ¡ }tr&|r&tjdkr&tdtƒ |  	¡ j
||d� | j¡S t j
| ||d�S )z\Implement custom cumulative summation for Torch versions which does not support it natively.Úwin32zåYou are trying to use a metric in deterministic mode on GPU that uses `torch.cumsum`, which is currently not supported. The tensor will be copied to the CPU memory to compute it and then copied back to GPU. Expect some slowdowns.)r   r;   )r   rd   rJ   Úis_floating_pointr
   ÚsysÚplatformr   r	   ÚcpuÚcumsumÚtor<   )r   r   r;   Zis_cuda_fp_deterministicr   r   r   Ú_cumsumÑ   s   ürt   c                 C   s"   t j| dd�\}}t|t|ƒd�S )zÎSimilar to `_bincount`, but works also with tensor that do not contain continuous values.

    Args:
        x: tensor to count

    Returns:
        Number of occurrences for each unique element in x

    T)Úreturn_inversera   )r   rc   rl   rb   )r   Zunique_xÚinverse_indicesr   r   r   Ú_flexible_bincountß   s   
rw   Útensor1Útensor2c                 C   s&   | j |j kr|j| j d�}t | |¡S )z:Wrap torch.allclose to be robust towards dtype difference.rS   )r;   rs   r   Úallclose)rx   ry   r   r   r   rz   í   s   rz   ÚxpÚfpc                 C   sŒ   t  |¡}|| }|| }|dd… |dd…  |dd… |dd…   }t  || ¡d }t  |dt|ƒd ¡}|| || | ||    S )zàInterpolation function comparable to numpy.interp.

    Args:
        x: x-coordinates where to evaluate the interpolated values
        xp: x-coordinates of the data points
        fp: y-coordinates of the data points

    r   Nr`   r   )r   rK   ÚsearchsortedÚclamprb   )r   r{   r|   Úsorted_indicesÚslopesrO   r   r   r   Úinterpô   s   

0r�   r]   )r   r   )r   )r   N),ro   Úcollections.abcr   Útypingr   r   r   r   r   Úlightning_utilitiesr   r   Ú!torchmetrics.utilities.exceptionsr	   Útorchmetrics.utilities.importsr
   r   Útorchmetrics.utilities.printsr   Z
METRIC_EPSr   r"   r%   r)   r,   Úlistr/   r1   ÚtupleÚboolr8   r>   rF   rQ   rW   rY   r[   r^   rl   r;   rt   rw   rz   r�   r   r   r   r   Ú<module>   sF   
þÿþ
ý#&