§
    ’©ºj¬  ã                   ó4  — 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dS )é    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Úreplaceç        ÚpredsÚtargetÚnum_classesÚnan_strategy)r   ÚdropÚnan_replace_valueÚreturnc                 óÖ   — | 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 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        úw/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/functional/nominal/cramers.pyÚ_cramers_v_updater       sm   € ð(  %œz¨Qš˜ˆE�LŠL˜‰OŒOˆO°E€EØ!'¤°Ò!1Ð!1ˆV�]Š]˜1ÑÔÐ°v€FÝ'¨¨v°|ÐEVÑWÔW�M€Eˆ6Ý.¨u°f¸kÑJÔJÐJó    ÚconfmatÚbias_correctionc                 ó<  — t          | ¦  «        } |                      ¦   «         }t          | |¦  «        }||z  }| j        \  }}|r˜t	          ||||¦  «        \  }}}	t          j        ||	¦  «        dk    r8t          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  ¦  «        }
|
                     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©Údevicer   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Ô0€GØ�[Š[‰]Œ]€FÝ& w°Ñ@Ô@€KØ Ñ&€KØ œÑ€Hˆhàð 	TÝ@^Ø˜ 8¨VñA
ô A
Ñ=Ð˜~¨~õ Œ9�^ ^Ñ4Ô4¸Ò9Ð9Ý2¸|ÐLÑLÔLÐLÝ”<¥ e¡¤°W´^ÐDÑDÔDÐDÝœ*Ð%:½U¼YÀ~ÐXYÑGYÐ[iÐlmÑ[mÑ=nÔ=nÑ%nÑoÔoˆˆåœ* [µ3°xÀ!±|ÀXÐPQÁ\Ñ3RÔ3RÑ%RÑSÔSˆØ× Ò   cÑ*Ô*Ð*r   Tc                 óÒ   — t          ||¦  «         t          t          j        | |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 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   sc   € õ^ ˜lÐ,=Ñ>Ô>Ð>Ý•e”i ¨ Ñ0Ô0×7Ò7Ñ9Ô9Ñ:Ô:€KÝ  v¨{¸LÐJ[Ñ\Ô\€GÝ˜g Ñ7Ô7Ð7r   Úmatrixc                 óÀ  — t          ||¦  «         | j        d         }t          j        ||| j        ¬¦  «        }t          j        t          |¦  «        d¦  «        D ]�\  }}| dd…|f         | dd…|f         }	}t          t          j	        ||	g¦  «         
                    ¦   «         ¦  «        }
t          ||	|
||¦  «        }t          ||¦  «        x|||f<   |||f<   Œ‚|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 ”O€MÝ"œZ¨°}ÈVÌ]Ð[Ñ[Ô[ÐÝÔ&¥u¨]Ñ';Ô';¸QÑ?Ô?ð sð s‰ˆˆ1Ø�a�a�a˜�dŒ|˜V A A A q Dœ\ˆ1ˆÝ�%œ) Q¨ FÑ+Ô+×2Ò2Ñ4Ô4Ñ5Ô5ˆÝ# A q¨+°|ÐEVÑWÔWˆÝFXÐY`ÐbqÑFrÔFrÐrÐ˜q !˜tÑ$Ð'=¸aÀ¸dÑ'CÐ'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Ð gÐ gÐ gÐ gÐ gðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð 09Ø),ðKð KØðKàðKð ðKð Ð+Ô,ð	Kð
   ”ðKð ðKð Kð Kð Kð4+ ð +¸ð +À&ð +ð +ð +ð +ðB !Ø/8Ø),ð28ð 28Øð28àð28ð ð28ð Ð+Ô,ð	28ð
   ”ð28ð ð28ð 28ð 28ð 28ðn !Ø/8Ø),ð	*"ð *"Øð*"àð*"ð Ð+Ô,ð*"ð   ”ð	*"ð
 ð*"ð *"ð *"ð *"ð *"ð *"r   