a
    d                  	   @   s   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mZmZmZmZmZ deeeed	 eeeef  ed
ddZeeedddZdeeeed	 eeeef  edddZdeeed	 eeeef  edddZdS )    N)OptionalUnion)Tensor)Literal)#_multiclass_confusion_matrix_update)_compute_bias_corrected_values_compute_chi_squared_drop_empty_rows_and_cols_handle_nan_in_data_nominal_input_validation&_unable_to_use_bias_correction_warningreplace        )r   Zdrop)predstargetnum_classesnan_strategynan_replace_valuereturnc                 C   sN   | j dkr| dn| } |j dkr,|dn|}t| |||\} }t| ||S )a  Compute the bins to update the confusion matrix with for Cramer's V calculation.

    Args:
        preds: 1D or 2D tensor of categorical (nominal) data
        target: 1D or 2D tensor of categorical (nominal) data
        num_classes: Integer specifing the number of classes
        nan_strategy: Indication of whether to replace or drop ``NaN`` values
        nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```

    Returns:
        Non-reduced confusion matrix

          )ndimZargmaxr
   r   )r   r   r   r   r    r   p/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/functional/nominal/cramers.py_cramers_v_update    s    r   )confmatbias_correctionr   c                 C   s   t | } |  }t| |}|| }| j\}}|rt||||\}}}	t||	dkrrtdd tjt	d| j
dS t|t|d |	d  }
nt|t|d |d  }
|
ddS )zCompute Cramers' V statistic based on a pre-computed confusion matrix.

    Args:
        confmat: Confusion matrix for observed data
        bias_correction: Indication of whether to use bias correction.

    Returns:
        Cramer's V statistic

    r   z
Cramer's V)Zmetric_namenandevicer   g      ?)r	   sumr   shaper   torchminr   Ztensorfloatr   sqrtclamp)r   r   Zcm_sumZchi_squaredZphi_squaredZn_rowsZn_colsZphi_squared_correctedZrows_correctedZcols_correctedZcramers_v_valuer   r   r   _cramers_v_compute:   s    



 r'   T)r   r   r   r   r   r   c                 C   s:   t || tt| |g }t| ||||}t||S )a%  Compute `Cramer's V`_ statistic measuring the association between two categorical (nominal) data series.

    .. math::
        V = \sqrt{\frac{\chi^2 / n}{\min(r - 1, k - 1)}}

    where

    .. math::
        \chi^2 = \sum_{i,j} \ frac{\left(n_{ij} - \frac{n_{i.} n_{.j}}{n}\right)^2}{\frac{n_{i.} n_{.j}}{n}}

    where :math:`n_{ij}` denotes the number of times the values :math:`(A_i, B_j)` are observed with :math:`A_i, B_j`
    represent frequencies of values in ``preds`` and ``target``, respectively.

    Cramer's V is a symmetric coefficient, i.e. :math:`V(preds, target) = V(target, preds)`.

    The output values lies in [0, 1] with 1 meaning the perfect association.

    Args:
        preds: 1D or 2D tensor of categorical (nominal) data
            - 1D shape: (batch_size,)
            - 2D shape: (batch_size, num_classes)
        target: 1D or 2D tensor of categorical (nominal) data
            - 1D shape: (batch_size,)
            - 2D shape: (batch_size, num_classes)
        bias_correction: Indication of whether to use bias correction.
        nan_strategy: Indication of whether to replace or drop ``NaN`` values
        nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``

    Returns:
        Cramer's V statistic

    Example:
        >>> from torchmetrics.functional.nominal import cramers_v
        >>> _ = torch.manual_seed(42)
        >>> preds = torch.randint(0, 4, (100,))
        >>> target = torch.round(preds + torch.randn(100)).clamp(0, 4)
        >>> cramers_v(preds, target)
        tensor(0.5284)

    )r   lenr"   catuniquer   r'   )r   r   r   r   r   r   r   r   r   r   	cramers_vX   s    /
r+   )matrixr   r   r   r   c                 C   s   t || | jd }tj||| jd}tt|dD ]n\}}| dd|f | dd|f  }}	tt	||	g
 }
t||	|
||}t|| |||f< |||f< q6|S )a  Compute `Cramer's V`_ statistic between a set of multiple variables.

    This can serve as a convenient tool to compute Cramer's V statistic for analyses of correlation between categorical
    variables in your dataset.

    Args:
        matrix: A tensor of categorical (nominal) data, where:
            - rows represent a number of data points
            - columns represent a number of categorical (nominal) features
        bias_correction: Indication of whether to use bias correction.
        nan_strategy: Indication of whether to replace or drop ``NaN`` values
        nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``

    Returns:
        Cramer's V statistic for a dataset of categorical variables

    Example:
        >>> from torchmetrics.functional.nominal import cramers_v_matrix
        >>> _ = torch.manual_seed(42)
        >>> matrix = torch.randint(0, 4, (200, 5))
        >>> cramers_v_matrix(matrix)
        tensor([[1.0000, 0.0637, 0.0000, 0.0542, 0.1337],
                [0.0637, 1.0000, 0.0000, 0.0000, 0.0000],
                [0.0000, 0.0000, 1.0000, 0.0000, 0.0649],
                [0.0542, 0.0000, 0.0000, 1.0000, 0.1100],
                [0.1337, 0.0000, 0.0649, 0.1100, 1.0000]])

    r   r   r   N)r   r!   r"   Zonesr   	itertoolscombinationsranger(   r)   r*   r   r'   )r,   r   r   r   Znum_variablesZcramers_v_matrix_valueijxyr   r   r   r   r   cramers_v_matrix   s    "

" r4   )r   r   )Tr   r   )Tr   r   )r-   typingr   r   r"   r   Ztyping_extensionsr   Z7torchmetrics.functional.classification.confusion_matrixr   Z%torchmetrics.functional.nominal.utilsr   r   r	   r
   r   r   intr$   r   boolr'   r+   r4   r   r   r   r   <module>   sL      !   7   