o
    .wij'                     @   sR  d dl mZmZ d dlZd dlmZmZ d dlmZ d dlm	Z	 d,dede
d	efd
dZ	d-ded d	dfddZded	efddZdedeeed f d	efddZ	d.dededee
 ded	ef
ddZded	efddZdeded	dfdd Zd!ed"ed	dfd#d$Zd%ed&ed	dfd'd(Z			d/dee dee d)ee d	efd*d+ZdS )0    )OptionalUnionN)Tensortensor)Literal)_check_same_shapeh㈵>xatolreturnc                 C   s   t | dkt | |k  S )zReturn True if all elements of tensor are nonnegative within certain tolerance.

    Args:
        x: tensor
        atol: absolute tolerance

    Returns:
        Boolean tensor indicating if all values are nonnegative

            )torch
logical_orabsall)r	   r
    r   e/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/functional/clustering/utils.pyis_nonnegative   s   r   
arithmeticaverage_methodmin	geometricr   maxc                 C   s   | dvrt d|  d S )Nr   zaExpected argument `average_method` to be one of  `min`, `geometric`, `arithmetic`, `max`,but got 
ValueError)r   r   r   r   _validate_average_method_arg%   s   r   c                 C   s   t | dkrtd| jdS ttj| ddd }||dk }| dkr,td| jdS | }t|| t|t|   S )a  Calculate entropy for a tensor of labels.

    Final calculation of entropy is performed in log form to account for roundoff error.

    Args:
        x: labels

    Returns:
        entropy: entropy of tensor

    Example:
        >>> from torchmetrics.functional.clustering.utils import calculate_entropy
        >>> labels = torch.tensor([1, 3, 2, 2, 1])
        >>> calculate_entropy(labels)
        tensor(1.0549)

    r         ?)deviceTreturn_inverse   r   )	lenr   r   r   bincountuniquesizesumlog)r	   pnr   r   r   calculate_entropy/   s   $r*   r(   c                 C   s   t | s	t| stdt|tr<|dkr|  S |dkr(t t | 	 S |dkr0|  S |dkr8| 
 S tdt t | |d|  S )at  Return generalized (power) mean of a tensor.

    Args:
        x: tensor
        p: power

    Returns:
        generalized_mean: generalized mean

    Example (p="min"):
        >>> from torchmetrics.functional.clustering.utils import calculate_generalized_mean
        >>> x = torch.tensor([1, 3, 2, 2, 1])
        >>> calculate_generalized_mean(x, "min")
        tensor(1)

    Example (p="geometric"):
        >>> from torchmetrics.functional.clustering.utils import calculate_generalized_mean
        >>> x = torch.tensor([1, 3, 2, 2, 1])
        >>> calculate_generalized_mean(x, "geometric")
        tensor(1.6438)

    z&`x` must contain positive real numbersr   r   r   r   z<'method' must be 'min', 'geometric', 'arirthmetic', or 'max'r   )r   
is_complexr   r   
isinstancestrr   expmeanr'   r   pow)r	   r(   r   r   r   calculate_generalized_meanN   s   
r1   Fpredstargetepssparsec                 C   s   |dur|du rt d| jdks|jdkr#t d| j d|j dtj| dd\}}tj|dd\}}|d	}|d	}	tt||ftj|j	d	 |j
|jd
|	|f}
|sd|
 }
|rd|
| }
|
S )ar  Calculate contingency matrix.

    Args:
        preds: predicted labels
        target: ground truth labels
        eps: value added to contingency matrix
        sparse: If True, returns contingency matrix as a sparse matrix. Else, return as dense matrix.
            `eps` must be `None` if `sparse` is `True`.

    Returns:
        contingency: contingency matrix of shape (n_classes_target, n_classes_preds)

    Example:
        >>> import torch
        >>> from torchmetrics.functional.clustering.utils import calculate_contingency_matrix
        >>> preds = torch.tensor([2, 1, 0, 1, 0])
        >>> target = torch.tensor([0, 2, 1, 1, 0])
        >>> calculate_contingency_matrix(preds, target, eps=1e-16)
        tensor([[1.0000e+00, 1.0000e-16, 1.0000e+00],
                [1.0000e+00, 1.0000e+00, 1.0000e-16],
                [1.0000e-16, 1.0000e+00, 1.0000e-16]])

    NTz.Cannot specify `eps` and return sparse tensor.r!   z)Expected 1d `preds` and `target` but got  and .r   r   dtyper   )r   ndimdimr   r$   r%   sparse_coo_tensorstackonesshaper9   r   to_dense)r2   r3   r4   r5   preds_classes	preds_idxtarget_classes
target_idxnum_classes_predsnum_classes_targetcontingencyr   r   r   calculate_contingency_matrixw   s.   

rH   c                 C   s2   | j dkrtd| j  dt| pt|  S )z/Check if tensor of labels is real and discrete.r!   z-Expected arguments to be 1-d tensors but got z-d tensors.)r:   r   r   is_floating_pointr+   )r	   r   r   r   _is_real_discrete_label   s   
rJ   c                 C   s8   t | | t| rt|std| j d|j ddS )zCheck shape of input tensors and if they are real, discrete tensors.

    Args:
        preds: predicted labels
        target: ground truth labels

    z2Expected real, discrete values for x but received r6   r7   N)r   rJ   r   r9   )r2   r3   r   r   r   check_cluster_labels   s   
rK   datalabelsc                 C   sV   | j dkrtd| j  d|  std| j d|j dkr)td|j  dd	S )
zDValidate that the input data and labels have correct shape and type.   zExpected 2D data, got zD data insteadz"Expected floating point data, got z data insteadr!   zExpected 1D labels, got zD labels insteadN)r:   r   rI   r9   )rL   rM   r   r   r    _validate_intrinsic_cluster_data   s   

rO   
num_labelsnum_samplesc                 C   s0   d|   k r
|k sn t d|  d| ddS )z<Validate that the number of labels are in the correct range.r!   z]Number of detected clusters must be greater than one and less than the number of samples.Got z clusters and z	 samples.Nr   )rP   rQ   r   r   r   %_validate_intrinsic_labels_to_samples   s   rR   rG   c                 C   s  | du r|du r|du rt d| dur |dur |dur t d| dur-|dur-t| |}|du r5t d| }|jdd}|jdd}|d  }tjdd|j|jd	}|| |d
< ||  | |d< |j|  | |d< |d |d  |d  | |d< |S )a<  Calculates the pair cluster confusion matrix.

    Can either be calculated from predicted cluster labels and target cluster labels or from a pre-computed
    contingency matrix. The pair cluster confusion matrix is a 2x2 matrix where that defines the similarity between
    two clustering by considering all pairs of samples and counting pairs that are assigned into same or different
    clusters in the predicted and target clusterings.

    Note that the matrix is not symmetric.

    Inspired by:
    https://scikit-learn.org/stable/modules/generated/sklearn.metrics.cluster.pair_confusion_matrix.html

    Args:
        preds: predicted cluster labels
        target: ground truth cluster labels
        contingency: contingency matrix

    Returns:
        A 2x2 tensor containing the pair cluster confusion matrix.

    Raises:
        ValueError:
            If neither `preds` and `target` nor `contingency` are provided.
        ValueError:
            If both `preds` and `target` and `contingency` are provided.

    Example:
        >>> import torch
        >>> from torchmetrics.functional.clustering.utils import calculate_pair_cluster_confusion_matrix
        >>> preds = torch.tensor([0, 0, 1, 1])
        >>> target = torch.tensor([1, 1, 0, 0])
        >>> calculate_pair_cluster_confusion_matrix(preds, target)
        tensor([[8, 0],
                [0, 4]])
        >>> preds = torch.tensor([0, 0, 1, 2])
        >>> target = torch.tensor([0, 0, 1, 1])
        >>> calculate_pair_cluster_confusion_matrix(preds, target)
        tensor([[8, 2],
                [0, 2]])

    Nz:Must provide either `preds` and `target` or `contingency`.zDMust provide either `preds` and `target` or `contingency`, not both.zDMust provide `contingency` if `preds` and `target` are not provided.r!   )r;   r   rN   r8   )r!   r!   )r!   r   )r   r!   )r   r   )r   rH   r&   r   zerosr9   r   T)r2   r3   rG   rQ   sum_csum_ksum_squaredpair_matrixr   r   r   'calculate_pair_cluster_confusion_matrix   s$   .
 rY   )r   )r   )NF)NNN)typingr   r   r   r   r   typing_extensionsr   torchmetrics.utilities.checksr   floatr   r   r*   intr1   boolrH   rJ   rK   rO   rR   rY   r   r   r   r   <module>   sT   

"*
9

