
    i                         d dl Z d dl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 	 	 ddeded	ed
ed   dee   defdZdedefdZ	 	 ddeded
ed   dee   def
dZ	 	 dded
ed   dee   defdZy)    N)Optional)Tensor)Literal)#_multiclass_confusion_matrix_update)_compute_chi_squared_drop_empty_rows_and_cols_handle_nan_in_data_nominal_input_validationpredstargetnum_classesnan_strategy)replacedropnan_replace_valuereturnc                     | j                   dk(  r| j                  d      n| } |j                   dk(  r|j                  d      n|}t        | |||      \  } }t        | ||      S )a  Compute the bins to update the confusion matrix with for Pearson's Contingency Coefficient calculation.

    Args:
        preds: 1D or 2D tensor of categorical (nominal) data
        target: 1D or 2D tensor of categorical (nominal) data
        num_classes: Integer specifying 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

          )ndimargmaxr	   r   )r   r   r   r   r   s        |/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/functional/nominal/pearson.py(_pearsons_contingency_coefficient_updater      s\    (  %zzQELLOEE!'!1V]]1vF'v|EVWME6.ufkJJ    confmatc                     t        |       } | j                         }t        | d      }||z  }t        j                  |d|z   z        }|j                  dd      S )zCompute Pearson's Contingency Coefficient based on a pre-computed confusion matrix.

    Args:
        confmat: Confusion matrix for observed data

    Returns:
        Pearson's Contingency Coefficient

    F)bias_correctionr           g      ?)r   sumr   torchsqrtclamp)r   cm_sumchi_squaredphi_squaredtschuprows_t_values        r   )_pearsons_contingency_coefficient_computer'   8   sZ     (0G[[]F&wFK&KK1{?$CD##C--r   c                     t        ||       t        t        j                  | |g      j	                               }t        | ||||      }t        |      S )aJ  Compute `Pearson's Contingency Coefficient`_ for measuring the association between two categorical data series.

    .. math::
        Pearson = \sqrt{\frac{\chi^2 / n}{1 + \chi^2 / n}}

    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.

    Pearson's Contingency Coefficient is a symmetric coefficient, i.e.
    :math:`Pearson(preds, target) = Pearson(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)

        nan_strategy: Indication of whether to replace or drop ``NaN`` values
        nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``

    Returns:
        Pearson's Contingency Coefficient

    Example:
        >>> from torch import randint, round
        >>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient
        >>> preds = randint(0, 4, (100,))
        >>> target = round(preds + torch.randn(100)).clamp(0, 4)
        >>> pearsons_contingency_coefficient(preds, target)
        tensor(0.6948)

    )r
   lenr    catuniquer   r'   )r   r   r   r   r   r   s         r    pearsons_contingency_coefficientr,   K   sO    d l,=>eii0779:K6ufkS_arsG4W==r   matrixc                    t        ||       | j                  d   }t        j                  ||| j                        }t        j                  t        |      d      D ]m  \  }}| dd|f   | dd|f   }}t        t        j                  ||g      j                               }	t        |||	||      }
t        |
      }|x|||f<   |||f<   o |S )a   Compute `Pearson's Contingency Coefficient`_ statistic between a set of multiple variables.

    This can serve as a convenient tool to compute Pearson's Contingency Coefficient 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

        nan_strategy: Indication of whether to replace or drop ``NaN`` values
        nan_replace_value: Value to replace ``NaN``s when ``nan_strategy = 'replace'``

    Returns:
        Pearson's Contingency Coefficient statistic for a dataset of categorical variables

    Example:
        >>> from torch import randint
        >>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient_matrix
        >>> matrix = randint(0, 4, (200, 5))
        >>> pearsons_contingency_coefficient_matrix(matrix)
        tensor([[1.0000, 0.2326, 0.1959, 0.2262, 0.2989],
                [0.2326, 1.0000, 0.1386, 0.1895, 0.1329],
                [0.1959, 0.1386, 1.0000, 0.1840, 0.2335],
                [0.2262, 0.1895, 0.1840, 1.0000, 0.2737],
                [0.2989, 0.1329, 0.2335, 0.2737, 1.0000]])

    r   )devicer   N)r
   shaper    onesr/   	itertoolscombinationsranger)   r*   r+   r   r'   )r-   r   r   num_variablespearsons_cont_coef_matrix_valueijxyr   r   vals               r   'pearsons_contingency_coefficient_matrixr<      s    D l,=>LLOM&+jjV\VcVc&d#&&u]';Q?1ad|VAqD\1%))QF+2245:1al\mn7@X[['1-0OPQSTPT0U @ +*r   )r   r   )r2   typingr   r    r   typing_extensionsr   7torchmetrics.functional.classification.confusion_matrixr   %torchmetrics.functional.nominal.utilsr   r   r	   r
   intfloatr   r'   r,   r<    r   r   <module>rD      s       % g  09),KKK K +,	K
  K K4.v .& ., 09),	5>5>5> +,5>  	5>
 5>t 09),+++++,++  ++ 	++r   