Ë
    þÍ: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 Tschuprow's T 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/tschuprows.pyÚ_tschuprows_t_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  «      z  «      }
nvt        j                  ||j                  ¬«      }t        j                  ||j                  ¬«      }t        j                  |t        j                  |dz
  |dz
  z  «      z  «      }
|
j                  dd«      S )a  Compute Tschuprow's T 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:
        Tschuprow's T statistic

    r   zTschuprow's T)Ú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Útschuprows_t_valueÚn_rows_tensorÚn_cols_tensors                r   Ú_tschuprows_t_computer8   :   s0  € ô (¨Ó0€GØ�[‰[‹]€FÜ& w°Ó@€KØ Ñ&€KØ Ÿ™Ñ€HˆháÜ@^Ø˜ 8¨VóA
Ñ=Ð˜~¨~ô �9‰9�^ ^Ó4¸Ò9Ü2¸ÕOÜ—<‘<¤ e£°W·^±^ÔDÐDÜ"ŸZ™ZÐ(=ÄÇ
Á
ÈNÐ]^ÑL^ÐcqÐtuÑcuÑKvÓ@wÑ(wÓxÑäŸ™ X°k×6HÑ6HÔIˆÜŸ™ X°k×6HÑ6HÔIˆÜ"ŸZ™Z¨´e·j±jÀ-ÐRSÑBSÐXeÐhiÑXiÑAjÓ6kÑ(kÓlÐØ×#Ñ# C¨Ó-Ð-r   c                 ó¬   — t        ||«       t        t        j                  | |g«      j	                  «       «      }t        | ||||«      }t        ||«      S )a;  Compute `Tschuprow's T`_ statistic measuring the association between two categorical (nominal) data series.

    .. math::
        T = \sqrt{\frac{\chi^2 / n}{\sqrt{(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.

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

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

    )r   Úlenr'   ÚcatÚuniquer   r8   )r   r   r   r   r   r   r   s          r   Útschuprows_tr=   Z   sP   € ôf ˜lÐ,=Ô>Ü”e—i‘i ¨ Ó0×7Ñ7Ó9Ó:€KÜ" 5¨&°+¸|ÐM^Ó_€GÜ  ¨/Ó:Ð:r   Ú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 `Tschuprow's T`_ statistic between a set of multiple variables.

    This can serve as a convenient tool to compute Tschuprow's T 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:
        Tschuprow's T statistic for a dataset of categorical variables

    Example:
        >>> from torch import randint
        >>> from torchmetrics.functional.nominal import tschuprows_t_matrix
        >>> matrix = randint(0, 4, (200, 5))
        >>> tschuprows_t_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Úranger:   r;   r<   r   r8   )r>   r   r   r   Únum_variablesÚtschuprows_t_matrix_valueÚiÚjÚxÚyr   r   s               r   Útschuprows_t_matrixrJ   “   sÛ   € ôH ˜lÐ,=Ô>Ø—L‘L ‘O€MÜ %§
¡
¨=¸-ÐPV×P]ÑP]Ô ^ÐÜ×&Ñ&¤u¨]Ó';¸QÓ?ò 
‰ˆˆ1Ø’a˜�d‰|˜V¢A q D™\ˆ1ˆÜœ%Ÿ)™) Q¨ FÓ+×2Ñ2Ó4Ó5ˆÜ& q¨!¨[¸,ÐHYÓZˆÜLaØ�_óM
ð 	
Ð! ! Q $Ñ'Ð*CÀAÀqÀDÒ*Ið	
ð %Ð$r   )r   r$   )Tr   r$   )rA   Útypingr   r'   r   Útyping_extensionsr   Ú7torchmetrics.functional.classification.confusion_matrixr   Ú%torchmetrics.functional.nominal.utilsr   r   r	   r
   r   r   Úintr*   r   Úboolr8   r=   rJ   © r   r   ú<module>rR      s/  ðó Ý ã Ý Ý %å g÷÷ ð 09Ø),ñKØðKàðKð ðKð Ð+Ñ,ð	Kð
   ‘ðKð óKð4. 6ð .¸Dð .ÀVó .ðF !Ø/8Ø),ñ6;Øð6;àð6;ð ð6;ð Ð+Ñ,ð	6;ð
   ‘ð6;ð ó6;ðv !Ø/8Ø),ñ	.%Øð.%àð.%ð Ð+Ñ,ð.%ð   ‘ð	.%ð
 ô.%r   