Ë
    þÍ:j¬  ã                   ó  — 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        ú|/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/torchmetrics/functional/nominal/cramers.pyÚ_cramers_v_updater       s\   € ð(  %Ÿz™z¨QšˆE�L‰L˜ŒO°E€EØ!'§¡°Ò!1ˆV�]‰]˜1Ô°v€FÜ'¨¨v°|ÐEVÓW�M€Eˆ6Ü.¨u°f¸kÓJÐJó    ÚconfmatÚbias_correctionc                 ó  — t        | «      } | j                  «       }t        | |«      }||z  }| j                  \  }}|r”t	        ||||«      \  }}}	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 )zýCompute 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ô   € ô (¨Ó0€GØ�[‰[‹]€FÜ& w°Ó@€KØ Ñ&€KØ Ÿ™Ñ€HˆháÜ@^Ø˜ 8¨VóA
Ñ=Ð˜~¨~ô �9‰9�^ ^Ó4¸Ò9Ü2¸|ÕLÜ—<‘<¤ e£°W·^±^ÔDÐDÜŸ*™*Ð%:¼U¿Y¹YÀ~ÐXYÑGYÐ[iÐlmÑ[mÓ=nÑ%nÓo‰äŸ*™* [´3°xÀ!±|ÀXÐPQÁ\Ó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Ð,=Ô>Ü”e—i‘i ¨ Ó0×7Ñ7Ó9Ó:€KÜ  v¨{¸LÐJ[Ó\€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Ð,=Ô>Ø—L‘L ‘O€MÜ"ŸZ™Z¨°}ÈVÏ]É]Ô[ÐÜ×&Ñ&¤u¨]Ó';¸QÓ?ò s‰ˆˆ1Ø’a˜�d‰|˜V¢A q D™\ˆ1ˆÜœ%Ÿ)™) Q¨ FÓ+×2Ñ2Ó4Ó5ˆÜ# A q¨+°|ÐEVÓWˆÜFXÐY`ÐbqÓFrÐrÐ˜q !˜tÑ$Ð'=¸aÀ¸dÒ'Cð	sð
 "Ð!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8ðn !Ø/8Ø),ñ	*"Øð*"àð*"ð Ð+Ñ,ð*"ð   ‘ð	*"ð
 ô*"r   