a
    df                     @   s  d dl mZmZmZ d dlZd dlmZ d dlmZ d dlm	Z	 e
eeeef  ddddZeed	d
dZeeedddZeed	ddZeeeeedddZeeeeeef dddZeeeeeeeef dddZd"eeed ee eeef dddZe
ddd d!ZdS )#    )OptionalTupleUnionN)Tensor)Literalrank_zero_warn)nan_strategynan_replace_valuereturnc                 C   s>   | dvrt d|  | dkr:t|ttfs:t d| d S )NreplaceZ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intfloat)r	   r
    r   n/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/functional/nominal/utils.py_nominal_input_validation   s    r   )confmatr   c                 C   s,   |  d|  d }}td|||    S )zDCompute the expected frequenceis from the provided confusion matrix.   r   z
r, c -> rc)sumtorchZeinsum)r   Zmargin_sum_rowsZmargin_sum_colsr   r   r   _compute_expected_freqs#   s    r   )r   bias_correctionr   c                 C   s   t | }| t|j |j d }|dkr<tjd| jdS |dkrz|rz||  }| }| |t	dt
| |  7 } t| | d | 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   Znumelr   shapendimr   tensorr   signZminimumZ	ones_likeabs)r   r   Zexpected_freqsZdfdiff	directionr   r   r   _compute_chi_squared)   s    "r&   c                 C   s,   | |  ddk } | dd|  ddkf S )a  Drop all rows and columns containing only zeros.

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

    r   r   N)r   )r   r   r   r   _drop_empty_rows_and_cols=   s    r'   )phi_squaredn_rowsn_colsconfmat_sumr   c                 C   s0   t t jd| jd| |d |d  |d   S )z#Compute bias-corrected Phi Squared.r   r   r   )r   maxr!   r   )r(   r)   r*   r+   r   r   r   _compute_phi_squared_correctedS   s    (r-   )r)   r*   r+   r   c                 C   s8   | | d d |d   }||d d |d   }||fS )z2Compute bias-corrected number of rows and columns.r   r   r   )r)   r*   r+   rows_correctedcols_correctedr   r   r    _compute_rows_and_cols_corrected_   s    r0   c                 C   s(   t | |||}t|||\}}|||fS )zBCompute bias-corrected Phi Squared and number of rows and columns.)r-   r0   )r(   r)   r*   r+   Zphi_squared_correctedr.   r/   r   r   r   _compute_bias_corrected_valuesf   s    r1   r   r   r   )predstargetr	   r
   r   c                 C   sD   |dkr|  || |fS t|  | }| |  ||  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   )Z
nan_to_numr   
logical_orisnan)r2   r3   r	   r
   Zrows_contain_nanr   r   r   _handle_nan_in_datao   s    r6   )metric_namer   c                 C   s   t d|  d d S )NzUnable to compute zG using bias correction. Please consider to set `bias_correction=False`.r   )r7   r   r   r   &_unable_to_use_bias_correction_warning   s    
r8   )r   r   )typingr   r   r   r   r   Ztyping_extensionsr   Ztorchmetrics.utilities.printsr   strr   r   r   r   boolr&   r'   r-   r0   r1   r6   r8   r   r   r   r   <module>   s8     
