
    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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defdZ	 	 	 ddededed
ed   dee   defdZ	 	 	 ddeded
ed   dee   def
dZy)    N)Optional)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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 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 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/cramers.py_cramers_v_updater       s\    (  %zzQELLOEE!'!1V]]1vF'v|EVWME6.ufkJJ    confmatbias_correctionc                    t        |       } | j                         }t        | |      }||z  }| j                  \  }}|rt	        ||||      \  }}}	t        j                  ||	      dk(  r6t        d       t        j                  t        d      | j                        S t        j                  |t        j                  |dz
  |	dz
        z        }
n(t        j                  |t        |dz
  |dz
        z        }
|
j                  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)metric_namenandevice        g      ?)r	   sumr   shaper   torchminr   tensorfloatr#   sqrtclamp)r   r   cm_sumchi_squaredphi_squarednum_rowsnum_colsphi_squared_correctedrows_correctedcols_correctedcramers_v_values              r   _cramers_v_computer6   :   s     (0G[[]F&w@K&K Hh@^8VA
=~~ 99^^492|L<<eW^^DD**%:UYY~XYGY[ilm[m=n%no**[3x!|XPQ\3R%RS  c**r   c                     t        ||       t        t        j                  | |g      j	                               }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 torch import randint, round
        >>> from torchmetrics.functional.nominal import cramers_v
        >>> preds = randint(0, 4, (100,))
        >>> target = round(preds + torch.randn(100)).clamp(0, 4)
        >>> cramers_v(preds, target)
        tensor(0.5284)

    )r   lenr'   catuniquer   r6   )r   r   r   r   r   r   r   s          r   	cramers_vr;   X   sP    ^ l,=>eii0779:Kv{LJ[\Gg77r   matrixc                    t        ||       | j                  d   }t        j                  ||| j                        }t        j                  t        |      d      D ]l  \  }}| dd|f   | dd|f   }	}t        t        j                  ||	g      j                               }
t        ||	|
||      }t        ||      x|||f<   |||f<   n |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 torch import randint
        >>> from torchmetrics.functional.nominal import cramers_v_matrix
        >>> matrix = 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'   onesr#   	itertoolscombinationsranger8   r9   r:   r   r6   )r<   r   r   r   num_variablescramers_v_matrix_valueijxyr   r   s               r   cramers_v_matrixrH      s    D l,=>LLOM"ZZ}V]][&&u]';Q?1ad|VAqD\1%))QF+2245#Aq+|EVWFXY`bqFrrq!t$'=ad'C	 @
 "!r   )r   r$   )Tr   r$   )r?   typingr   r'   r   typing_extensionsr   7torchmetrics.functional.classification.confusion_matrixr   %torchmetrics.functional.nominal.utilsr   r   r	   r
   r   r   intr*   r   boolr6   r;   rH    r   r   <module>rP      s/       % g  09),KKK K +,	K
  K K4+ + +& +B !/8),282828 28 +,	28
  28 28n !/8),	*"*"*" +,*"  	*"
 *"r   