o
    .wi
                  
   @   sx   d dl mZ d dlZd dlmZ dedededeeef fdd	Zd
ededefddZddedededefddZdS )    )combinationsN)Tensordatalabelspreturnc                    s   |j dd\} fddtt|D }dd |D }tjjtjdd t|dD dd	d
d}tfddt||D }||fS )aT  Update and return variables required to compute the Dunn index.

    Args:
        data: feature vectors of shape (n_samples, n_features)
        labels: cluster labels
        p: p-norm (distance metric)

    Returns:
        intercluster_distance: intercluster distances
        max_intracluster_distance: max intracluster distances

    T)return_inversec                    s   g | ]} |k qS  r	   ).0	label_idx)r   inverse_indicesr	   j/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/functional/clustering/dunn_index.py
<listcomp>"       z&_dunn_index_update.<locals>.<listcomp>c                 S   s   g | ]}|j d dqS )r   dim)mean)r
   cr	   r	   r   r   #   r   c                 S   s   g | ]\}}|| qS r	   r	   )r
   abr	   r	   r   r   &   r      r   r      ordr   c                    s*   g | ]\}}t jj||  d d qS )r   r   )torchlinalgnormmax)r
   cimu)r   r	   r   r   )   s    )	uniquerangelenr   r   r   stackr   zip)r   r   r   unique_labelsclusters	centroidsintercluster_distancemax_intracluster_distancer	   )r   r   r   r   _dunn_index_update   s    r*   r(   r)   c                 C   s   |   |  S )zCompute the Dunn index based on updated state.

    Args:
        intercluster_distance: intercluster distances
        max_intracluster_distance: max intracluster distances

    Returns:
        scalar tensor with the dunn index

    )minr   )r(   r)   r	   r	   r   _dunn_index_compute0   s   r,   r   c                 C   s   t | ||\}}t||S )a  Compute the Dunn index.

    Args:
        data: feature vectors
        labels: cluster labels
        p: p-norm used for distance metric

    Returns:
        scalar tensor with the dunn index

    Example:
        >>> from torchmetrics.functional.clustering import dunn_index
        >>> data = torch.tensor([[0, 0], [0.5, 0], [1, 0], [0.5, 1]])
        >>> labels = torch.tensor([0, 0, 0, 1])
        >>> dunn_index(data, labels)
        tensor(2.)

    )r*   r,   )r   r   r   pairwise_distancemax_distancer	   r	   r   
dunn_index>   s   
r/   )r   )		itertoolsr   r   r   floattupler*   r,   r/   r	   r	   r	   r   <module>   s   " 