
    iq                     8   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edee	   ddfd	Z
d
edefdZd
ededefdZd
edefdZdededededef
dZdedededeeef   fdZdededededeeeef   f
dZ	 	 ddededed   dee	   deeef   f
dZdeddfdZy)    )OptionalN)Tensor)Literalrank_zero_warnnan_strategynan_replace_valuereturnc                 |    | dvrt        d|        | dk(  r%t        |t        t        f      st        d|       y y )NreplacedropzPArgument `nan_strategy` is expected to be one of `['replace', 'drop']`, but got r   zlArgument `nan_replace` is expected to be of a type `int` or `float` when `nan_strategy = 'replace`, but got )
ValueError
isinstancefloatint)r   r	   s     z/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/functional/nominal/utils.py_nominal_input_validationr      sb    ..^_k^lm
 	
 y 4Es|)T()+
 	
 *U     confmatc                     | j                  d      | j                  d      }}t        j                  d||      | j                         z  S )zDCompute the expected frequenceis from the provided confusion matrix.   r   z
r, c -> rc)sumtorcheinsum)r   margin_sum_rowsmargin_sum_colss      r   _compute_expected_freqsr   #   s9    '.{{1~w{{1~_O<<oG'++-WWr   bias_correctionc                    t        |       }|j                         t        |j                        z
  |j                  z   dz
  }|dk(  r!t        j                  d| j                        S |dk(  rW|rU|| z
  }|j                         }| |t        j                  dt        j                  |      z  |j                               z  z  } t        j                  | |z
  dz  |z        S )zChi-square test of independenc of variables in a confusion matrix table.

    Adapted from: https://github.com/scipy/scipy/blob/v1.9.2/scipy/stats/contingency.py.

    r   r           deviceg      ?   )r   numelr   shapendimr   tensorr#   signminimum	ones_likeabs)r   r   expected_freqsdfdiff	directions         r   _compute_chi_squaredr1   )   s     -W5N				#n&:&:";	;n>Q>Q	QTU	UB	Qw||C77	Qw?'IIK	9u}}S5??93M-My}}___99g.14~EFFr   c                 f    | | j                  d      dk7     } | dd| j                  d      dk7  f   S )a  Drop all rows and columns containing only zeros.

    Example:
        >>> from torch import randint
        >>> from torchmetrics.functional.nominal.utils import _drop_empty_rows_and_cols
        >>> matrix = randint(10, size=(4, 3))
        >>> matrix[1, :] = matrix[:, 1] = 0
        >>> matrix
        tensor([[2, 0, 6],
                [0, 0, 0],
                [0, 0, 0],
                [3, 0, 4]])
        >>> _drop_empty_rows_and_cols(matrix)
        tensor([[2, 6],
                [3, 4]])

    r   r   N)r   )r   s    r   _drop_empty_rows_and_colsr3   =   s8    $ gkk!n)*G1gkk!n))**r   phi_squarednum_rowsnum_colsconfmat_sumc                     t        j                  t        j                  d| j                        | |dz
  |dz
  z  |dz
  z  z
        S )z#Compute bias-corrected Phi Squared.r!   r"   r   )r   maxr(   r#   )r4   r5   r6   r7   s       r   _compute_phi_squared_correctedr:   S   sG     99S!3!341A6;?KK r   c                 N    | | dz
  dz  |dz
  z  z
  }||dz
  dz  |dz
  z  z
  }||fS )z2Compute bias-corrected number of rows and columns.r   r$    )r5   r6   r7   rows_correctedcols_correcteds        r    _compute_rows_and_cols_correctedr?   `   sE    A! 3{Q GGNA! 3{Q GGN>))r   c                 H    t        | |||      }t        |||      \  }}|||fS )zBCompute bias-corrected Phi Squared and number of rows and columns.)r:   r?   )r4   r5   r6   r7   phi_squared_correctedr=   r>   s          r   _compute_bias_corrected_valuesrB   g   s9     ;;RZ\gh%EhPXZe%f"NN ..@@r   predstargetr   c                     |dk(  r"| j                  |      |j                  |      fS t        j                  | j                         |j                               }| |    ||    fS )a0  Handle ``NaN`` values in input data.

    If ``nan_strategy = 'replace'``, all ``NaN`` values are replaced with ``nan_replace_value``.
    If ``nan_strategy = 'drop'``, all rows containing ``NaN`` in any of two vectors are dropped.

    Args:
        preds: 1D tensor of categorical (nominal) data
        target: 1D tensor of categorical (nominal) data
        nan_strategy: Indication of whether to replace or drop ``NaN`` values
        nan_replace_value: Value to replace ``NaN`s when ``nan_strategy = 'replace```

    Returns:
        Updated ``preds`` and ``target`` tensors which contain no ``Nan``

    Raises:
        ValueError: If ``nan_strategy`` is not from ``['replace', 'drop']``.
        ValueError: If ``nan_strategy = replace`` and ``nan_replace_value`` is not of a type ``int`` or ``float``.

    r   )
nan_to_numr   
logical_orisnan)rC   rD   r   r	   rows_contain_nans        r   _handle_nan_in_datarJ   p   sk    2 y  12F4E4EFW4XXX''v||~F""#V-=,=%>>>r   metric_namec                 "    t        d|  d       y )NzUnable to compute zG using bias correction. Please consider to set `bias_correction=False`.r   )rK   s    r   &_unable_to_use_bias_correction_warningrM      s    
[M)pqr   )r   r!   )typingr   r   r   typing_extensionsr   torchmetrics.utilities.printsr   strr   r   r   boolr1   r3   r   r:   tupler?   rB   rJ   rM   r<   r   r   <module>rT      s~      % 8	
C 	
HUO 	
X\ 	
XV X XG& G4 GF G(+v +& +,


 
 	

 
*s *c *PV *[`agioao[p *AA#&A25ADJA
666!"A 09),	??? +,?  	?
 66>?>  r   