Ë
    þÍ:jSC  ã                   óD  — d dl mZ d dl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mZmZmZmZmZmZ d dlmZ d dlmZ 	 	 dded	eed
      dee   dedef
d„Z	 	 	 	 ddedededee   dededefd„Z	 	 d dedee   d	eed      ddfd„Z	 	 	 	 d!dededed	eed      dee   dededefd„Z	 	 	 d"dededee   d	eed      ddf
d„Z	 	 	 	 	 d#dedededed	eed      dee   dededefd„Z	 	 	 	 	 	 	 d$dededed   dedee   dee   d	eed      dee   dededefd„Z y)%é    )ÚOptionalN)ÚTensor)ÚLiteral)Ú'_binary_confusion_matrix_arg_validationÚ_binary_confusion_matrix_formatÚ*_binary_confusion_matrix_tensor_validationÚ_binary_confusion_matrix_updateÚ+_multiclass_confusion_matrix_arg_validationÚ#_multiclass_confusion_matrix_formatÚ._multiclass_confusion_matrix_tensor_validationÚ#_multiclass_confusion_matrix_updateÚ+_multilabel_confusion_matrix_arg_validationÚ#_multilabel_confusion_matrix_formatÚ._multilabel_confusion_matrix_tensor_validationÚ#_multilabel_confusion_matrix_update)Ú_safe_divide)ÚClassificationTaskÚconfmatÚaverage)ÚmicroÚmacroÚweightedÚnoneÚbinaryÚignore_indexÚzero_divisionÚreturnc                 ó¶  — g d¢}||vrt        d|› d|› d�«      ‚| j                  «       } |dk(  r t        | d   | d   | d   z   | d   z   |¬	«      S |d
uxr d|cxk  xr | j                  d   k  nc }| j                  dk(  }|r+| d
d
…ddf   }| d
d
…ddf   | d
d
…ddf   z   | d
d
…ddf   z   }n;t        j                  | «      }| j                  d«      | j                  d«      z   |z
  }|dk(  r*|j                  «       }|j                  «       |r||   ndz
  }t        |||¬	«      }	|�
|dk(  s|dk(  r|	S |dk(  r6| j                  dk(  r| d
d
…ddf   | d
d
…ddf   z   n| j                  d«      }
nGt        j                  |	«      }
|rd|
|<   |s)d|
| j                  d«      | j                  d«      z   dk(  <   |
|	z  |
j                  «       z  j                  «       S )a'  Perform reduction of an un-normalized confusion matrix into jaccard score.

    Args:
        confmat: tensor with un-normalized confusionmatrix
        average: reduction method

            - ``'binary'``: binary reduction, expects a 2x2 matrix
            - ``'macro'``: Calculate the metric for each class separately, and average the
              metrics across classes (with equal weights for each class).
            - ``'micro'``: Calculate the metric globally, across all samples and classes.
            - ``'weighted'``: Calculate the metric for each class separately, and average the
              metrics across classes, weighting each class by its support (``tp + fn``).
            - ``'none'`` or ``None``: Calculate the metric for each class separately, and return
              the metric for every class.

        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        zero_division:
            Value to replace when there is a division by zero. Should be `0` or `1`.

    )r   r   r   r   r   NzThe `average` has to be one of z, got ú.r   )é   r    )r   r    )r    r   )r   Nr   é   r    r   ç        r   r   )	Ú
ValueErrorÚfloatr   ÚshapeÚndimÚtorchÚdiagÚsumÚ	ones_like)r   r   r   r   Úallowed_averageÚignore_index_condÚ
multilabelÚnumÚdenomÚjaccardÚweightss              úƒ/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/torchmetrics/functional/classification/jaccard.pyÚ_jaccard_index_reducer3   &   s  € ò6 M€OØ�oÑ%ÜÐ:¸?Ð:KÈ6ÐRYÐQZÐZ[Ð\Ó]Ð]Ø�m‰m‹o€GØ�(ÒÜ˜G D™M¨G°D©M¸GÀD¹MÑ,IÈGÐTXÉMÑ,YÐjwÔxÐxà$¨DÐ0ÒY°Q¸,Ö5YÈÏÉÐWXÑIYÔ5YÐØ—‘ Ñ"€JÙØ’a˜˜A�gÑˆØš˜1˜a˜Ñ  7ª1¨a°¨7Ñ#3Ñ3°gºaÀÀA¸gÑ6FÑF‰ä�j‰j˜Ó!ˆØ—‘˜A“ §¡¨Q£Ñ/°#Ñ5ˆà�'ÒØ�g‰g‹iˆØ—	‘	“Ñ6G˜u \Ò2ÈSÑQˆä˜3 °]ÔC€Gà€˜' VÒ+¨w¸'Ò/AØˆØ�*ÒØ9@¿¹ÈÒ9J�'š!˜Q ˜'Ñ" WªQ°°1¨WÑ%5Ò5ÐPW×P[ÑP[Ð\]ÓP^‰ä—/‘/ 'Ó*ˆÙØ$'ˆG�LÑ!ÙØ<?ˆG�G—K‘K “N W§[¡[°£^Ñ3°qÑ8Ñ9Ø�wÑ '§+¡+£-Ñ/×4Ñ4Ó6Ð6ó    ÚpredsÚtargetÚ	thresholdÚvalidate_argsc                 óŽ   — |rt        ||«       t        | ||«       t        | |||«      \  } }t        | |«      }t	        |d|¬«      S )aì  Calculate the Jaccard index for binary tasks.

    The `Jaccard index`_ (also known as the intersection over union or jaccard similarity coefficient) is an statistic
    that can be used to determine the similarity and diversity of a sample set. It is defined as the size of the
    intersection divided by the union of the sample sets:

    .. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}

    Accepts the following input tensors:

    - ``preds`` (int or float tensor): ``(N, ...)``. If preds is a floating point tensor with values outside
      [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
      we convert to int tensor with thresholding using the value in ``threshold``.
    - ``target`` (int tensor): ``(N, ...)``

    Additional dimension ``...`` will be flattened into the batch dimension.

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        threshold: Threshold for transforming probability to binary (0,1) predictions
        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.
        zero_division:
            Value to replace when there is a division by zero. Should be `0` or `1`.

    Example (preds is int tensor):
        >>> from torch import tensor
        >>> from torchmetrics.functional.classification import binary_jaccard_index
        >>> target = tensor([1, 1, 0, 0])
        >>> preds = tensor([0, 1, 0, 0])
        >>> binary_jaccard_index(preds, target)
        tensor(0.5000)

    Example (preds is float tensor):
        >>> from torchmetrics.functional.classification import binary_jaccard_index
        >>> target = tensor([1, 1, 0, 0])
        >>> preds = tensor([0.35, 0.85, 0.48, 0.01])
        >>> binary_jaccard_index(preds, target)
        tensor(0.5000)

    r   )r   r   )r   r   r   r	   r3   )r5   r6   r7   r   r8   r   r   s          r2   Úbinary_jaccard_indexr:   d   sM   € ñh Ü/°	¸<ÔHÜ2°5¸&À,ÔOÜ3°E¸6À9ÈlÓ[�M€Eˆ6Ü-¨e°VÓ<€GÜ  °(È-ÔXÐXr4   Únum_classes)r   r   r   r   c                 óL   — t        | |«       d}||vrt        d|› d|› d�«      ‚y ©N)r   r   r   r   Nz)Expected argument `average` to be one of z
, but got r   )r
   r#   )r;   r   r   r+   s       r2   Ú(_multiclass_jaccard_index_arg_validationr>       s@   € ô
 0°¸\ÔJØB€OØ�oÑ%ÜÐDÀ_ÐDUÐU_Ð`gÐ_hÐhiÐjÓkÐkð &r4   c                 ó”   — |rt        |||«       t        | |||«       t        | ||«      \  } }t        | ||«      }t	        ||||¬«      S )a"
  Calculate the Jaccard index for multiclass tasks.

    The `Jaccard index`_ (also known as the intersection over union or jaccard similarity coefficient) is an statistic
    that can be used to determine the similarity and diversity of a sample set. It is defined as the size of the
    intersection divided by the union of the sample sets:

    .. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}

    Accepts the following input tensors:

    - ``preds``: ``(N, ...)`` (int tensor) or ``(N, C, ..)`` (float tensor). If preds is a floating point
      we apply ``torch.argmax`` along the ``C`` dimension to automatically convert probabilities/logits into
      an int tensor.
    - ``target`` (int tensor): ``(N, ...)``

    Additional dimension ``...`` will be flattened into the batch dimension.

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        num_classes: Integer specifying the number of classes
        average:
            Defines the reduction that is applied over labels. Should be one of the following:

            - ``micro``: Sum statistics over all labels
            - ``macro``: Calculate statistics for each label and average them
            - ``weighted``: calculates statistics for each label and computes weighted average using their support
            - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction

        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.
        zero_division:
            Value to replace when there is a division by zero. Should be `0` or `1`.

    Example (pred is integer tensor):
        >>> from torch import tensor
        >>> from torchmetrics.functional.classification import multiclass_jaccard_index
        >>> target = tensor([2, 1, 0, 0])
        >>> preds = tensor([2, 1, 0, 1])
        >>> multiclass_jaccard_index(preds, target, num_classes=3)
        tensor(0.6667)

    Example (pred is float tensor):
        >>> from torchmetrics.functional.classification import multiclass_jaccard_index
        >>> target = tensor([2, 1, 0, 0])
        >>> preds = tensor([[0.16, 0.26, 0.58],
        ...                 [0.22, 0.61, 0.17],
        ...                 [0.71, 0.09, 0.20],
        ...                 [0.05, 0.82, 0.13]])
        >>> multiclass_jaccard_index(preds, target, num_classes=3)
        tensor(0.6667)

    ©r   r   r   )r>   r   r   r   r3   )r5   r6   r;   r   r   r8   r   r   s           r2   Úmulticlass_jaccard_indexrA   «   sU   € ñ@ Ü0°¸lÈGÔTÜ6°u¸fÀkÐS_Ô`Ü7¸¸vÀ|ÓT�M€Eˆ6Ü1°%¸ÀÓM€GÜ  °'ÈÐdqÔrÐrr4   Ú
num_labelsc                 óN   — t        | ||«       d}||vrt        d|› d|› d�«      ‚y r=   )r   r#   )rB   r7   r   r   r+   s        r2   Ú(_multilabel_jaccard_index_arg_validationrD   ó   sB   € ô 0°
¸IÀ|ÔTØB€OØ�oÑ%ÜÐDÀ_ÐDUÐU_Ð`gÐ_hÐhiÐjÓkÐkð &r4   c                 ó˜   — |rt        |||«       t        | |||«       t        | ||||«      \  } }t        | ||«      }t	        ||||¬«      S )aZ
  Calculate the Jaccard index for multilabel tasks.

    The `Jaccard index`_ (also known as the intersection over union or jaccard similarity coefficient) is an statistic
    that can be used to determine the similarity and diversity of a sample set. It is defined as the size of the
    intersection divided by the union of the sample sets:

    .. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}

    Accepts the following input tensors:

    - ``preds`` (int or float tensor): ``(N, C, ...)``. If preds is a floating point tensor with values outside
      [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
      we convert to int tensor with thresholding using the value in ``threshold``.
    - ``target`` (int tensor): ``(N, C, ...)``

    Additional dimension ``...`` will be flattened into the batch dimension.

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        num_labels: Integer specifying the number of labels
        threshold: Threshold for transforming probability to binary (0,1) predictions
        average:
            Defines the reduction that is applied over labels. Should be one of the following:

            - ``micro``: Sum statistics over all labels
            - ``macro``: Calculate statistics for each label and average them
            - ``weighted``: calculates statistics for each label and computes weighted average using their support
            - ``"none"`` or ``None``: calculates statistic for each label and applies no reduction

        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.
        zero_division:
            Value to replace when there is a division by zero. Should be `0` or `1`.

    Example (preds is int tensor):
        >>> from torch import tensor
        >>> from torchmetrics.functional.classification import multilabel_jaccard_index
        >>> target = tensor([[0, 1, 0], [1, 0, 1]])
        >>> preds = tensor([[0, 0, 1], [1, 0, 1]])
        >>> multilabel_jaccard_index(preds, target, num_labels=3)
        tensor(0.5000)

    Example (preds is float tensor):
        >>> from torchmetrics.functional.classification import multilabel_jaccard_index
        >>> target = tensor([[0, 1, 0], [1, 0, 1]])
        >>> preds = tensor([[0.11, 0.22, 0.84], [0.73, 0.33, 0.92]])
        >>> multilabel_jaccard_index(preds, target, num_labels=3)
        tensor(0.5000)

    r@   )rD   r   r   r   r3   )	r5   r6   rB   r7   r   r   r8   r   r   s	            r2   Úmultilabel_jaccard_indexrF   ÿ   s[   € ñ~ Ü0°¸YÈÔUÜ6°u¸fÀjÐR^Ô_Ü7¸¸vÀzÐS\Ð^jÓk�M€Eˆ6Ü1°%¸ÀÓL€GÜ  °'ÈÐdqÔrÐrr4   Útask)r   Ú
multiclassr-   c
           
      óÀ  — t        j                  |«      }|t         j                  k(  rt        | |||||	«      S |t         j                  k(  r9t        |t        «      st        dt        |«      › d�«      ‚t        | ||||||	«      S |t         j                  k(  r:t        |t        «      st        dt        |«      › d�«      ‚t        | |||||||	«      S t        d|› �«      ‚)a¿  Calculate the Jaccard index.

    The `Jaccard index`_ (also known as the intersection over union or jaccard similarity coefficient) is an statistic
    that can be used to determine the similarity and diversity of a sample set. It is defined as the size of the
    intersection divided by the union of the sample sets:

    .. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}

    This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
    ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
    :func:`~torchmetrics.functional.classification.binary_jaccard_index`,
    :func:`~torchmetrics.functional.classification.multiclass_jaccard_index` and
    :func:`~torchmetrics.functional.classification.multilabel_jaccard_index` for
    the specific details of each argument influence and examples.

    Legacy Example:
        >>> from torch import randint, tensor
        >>> target = randint(0, 2, (10, 25, 25))
        >>> pred = tensor(target)
        >>> pred[2:5, 7:13, 9:15] = 1 - pred[2:5, 7:13, 9:15]
        >>> jaccard_index(pred, target, task="multiclass", num_classes=2)
        tensor(0.9660)

    z+`num_classes` is expected to be `int` but `z was passed.`z*`num_labels` is expected to be `int` but `zNot handled value: )r   Úfrom_strÚBINARYr:   Ú
MULTICLASSÚ
isinstanceÚintr#   ÚtyperA   Ú
MULTILABELrF   )
r5   r6   rG   r7   r;   rB   r   r   r8   r   s
             r2   Újaccard_indexrQ   F  sò   € ôH ×&Ñ& tÓ,€DØÔ!×(Ñ(Ò(Ü# E¨6°9¸lÈMÐ[hÓiÐiØÔ!×,Ñ,Ò,Ü˜+¤sÔ+ÜÐJÌ4ÐP[ÓK\ÐJ]Ð]jÐkÓlÐlÜ'¨¨v°{ÀGÈ\Ð[hÐjwÓxÐxØÔ!×,Ñ,Ò,Ü˜*¤cÔ*ÜÐIÌ$ÈzÓJZÐI[Ð[hÐiÓjÐjÜ'Ø�6˜: y°'¸<ÈÐXeó
ð 	
ô Ð*¨4¨&Ð1Ó
2Ð2r4   )Nr"   )ç      à?NTr"   )NN)r   NTr"   )rR   Nr   )rR   r   NTr"   )rR   NNr   NTr"   )!Útypingr   r'   r   Útyping_extensionsr   Ú7torchmetrics.functional.classification.confusion_matrixr   r   r   r	   r
   r   r   r   r   r   r   r   Útorchmetrics.utilities.computer   Útorchmetrics.utilities.enumsr   rN   r$   r3   Úboolr:   r>   rA   rD   rF   rQ   © r4   r2   ú<module>rZ      s*  ðõ ã Ý Ý %÷÷ ÷ ó õ 8Ý ;ð #'Øñ	;7Øð;7à�gÐLÑMÑNð;7ð ˜3‘-ð;7ð ð	;7ð
 ó;7ðB Ø"&ØØñ9YØð9Yàð9Yð ð9Yð ˜3‘-ð	9Yð
 ð9Yð ð9Yð ó9Yð| #'ØGKñlØðlà˜3‘-ðlð �gÐBÑCÑDðlð 
ó	lð HOØ"&ØØñEsØðEsàðEsð ðEsð �gÐBÑCÑDð	Esð
 ˜3‘-ðEsð ðEsð ðEsð óEsðT Ø"&ØGNñ		lØð	làð	lð ˜3‘-ð	lð �gÐBÑCÑDð		lð
 
ó	lð  ØGNØ"&ØØñDsØðDsàðDsð ðDsð ð	Dsð
 �gÐBÑCÑDðDsð ˜3‘-ðDsð ðDsð ðDsð óDsðV Ø!%Ø $ØGNØ"&ØØñ13Øð13àð13ð Ð6Ñ
7ð13ð ð	13ð
 ˜#‘ð13ð ˜‘ð13ð �gÐBÑCÑDð13ð ˜3‘-ð13ð ð13ð ð13ð ô13r4   