o
    yi,>                     @   s  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edeed	  d
ee defddZ			d'dededed
ee dedefddZ		d(ded
ee deed  ddfddZ			d)dedededeed  d
ee dedefddZ			d*deded
ee deed  ddf
ddZ				d+dededededeed  d
ee dedefd 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fd$d%ZdS )-    )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confmataverage)micromacroweightednonebinaryignore_indexreturnc           	      C   s  g d}||vrt d| d| d|  } |dkr+| d | d | d  | d   S |d	uo=d
|  ko;| jd
 kn  }| jdkrh| d	d	ddf }| d	d	ddf | d	d	d
df  | d	d	dd
f  }nt| }| d
| d | }|dkr| }| |r|| nd }t||}|d	u s|dks|dkr|S |dkr| jdkr| d	d	ddf | d	d	dd
f  n| d}nt|}|rd||< || |   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
    )r   r   r   r   r   NzThe `average` has to be one of z, got .r   )   r   )r   r   )r   r   Nr      r   r   g        r   r   )	
ValueErrorfloatshapendimtorchdiagsumr   	ones_like)	r   r   r   allowed_averageignore_index_condnumdenomjaccardweights r,   b/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/functional/classification/jaccard.py_jaccard_index_reduce%   s0    &
8

:
r.         ?Tpredstarget	thresholdvalidate_argsc                 C   sB   |rt || t| || t| |||\} }t| |}t|ddS )aw  Calculates the Jaccard index for binary tasks. The `Jaccard index`_ (also known as the intersetion 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. Addtionally,
      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:
        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.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example (preds is int tensor):
        >>> from torchmetrics.functional.classification import binary_jaccard_index
        >>> target = torch.tensor([1, 1, 0, 0])
        >>> preds = torch.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 = torch.tensor([1, 1, 0, 0])
        >>> preds = torch.tensor([0.35, 0.85, 0.48, 0.01])
        >>> binary_jaccard_index(preds, target)
        tensor(0.5000)
    r   )r   )r   r   r   r   r.   )r0   r1   r2   r   r3   r   r,   r,   r-   binary_jaccard_index\   s   -

r4   num_classes)r   r   r   r   c                 C   s0   t | | d}||vrtd| d| dd S N)r   r   r   r   Nz)Expected argument `average` to be one of z
, but got r   )r	   r   )r5   r   r   r&   r,   r,   r-   (_multiclass_jaccard_index_arg_validation   s
   
r7   r   c                 C   sH   |rt ||| t| ||| t| ||\} }t| ||}t|||dS )a	  Calculates the Jaccard index for multiclass tasks. The `Jaccard index`_ (also known as the intersetion 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:
        num_classes: Integer specifing 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.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example (pred is integer tensor):
        >>> from torchmetrics.functional.classification import multiclass_jaccard_index
        >>> target = torch.tensor([2, 1, 0, 0])
        >>> preds = torch.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 = torch.tensor([2, 1, 0, 0])
        >>> preds = torch.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   )r7   r   r
   r   r.   )r0   r1   r5   r   r   r3   r   r,   r,   r-   multiclass_jaccard_index   s   ;r9   
num_labelsc                 C   s2   t | || d}||vrtd| d| dd S r6   )r   r   )r:   r2   r   r   r&   r,   r,   r-   (_multilabel_jaccard_index_arg_validation   s
   r;   c                 C   sL   |rt ||| t| ||| t| ||||\} }t| ||}t|||dS )a	  Calculates the Jaccard index for multilabel tasks. The `Jaccard index`_ (also known as the intersetion 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. Addtionally,
      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:
        num_classes: Integer specifing 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.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example (preds is int tensor):
        >>> from torchmetrics.functional.classification import multilabel_jaccard_index
        >>> target = torch.tensor([[0, 1, 0], [1, 0, 1]])
        >>> preds = torch.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 = torch.tensor([[0, 1, 0], [1, 0, 1]])
        >>> preds = torch.tensor([[0.11, 0.22, 0.84], [0.73, 0.33, 0.92]])
        >>> multilabel_jaccard_index(preds, target, num_labels=3)
        tensor(0.5000)
    r8   )r;   r   r   r   r.   )r0   r1   r:   r2   r   r   r3   r   r,   r,   r-   multilabel_jaccard_index   s   8r<   task)r   
multiclass
multilabelc	           	      C   sx   |dkrt | ||||S |dkr t|tsJ t| |||||S |dkr5t|ts+J t| ||||||S td| )a  Calculates the Jaccard index. The `Jaccard index`_ (also known as the intersetion 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:`binary_jaccard_index`, :func:`multiclass_jaccard_index` and :func:`multilabel_jaccard_index` for
    the specific details of each argument influence and examples.

    Legacy Example:
        >>> target = torch.randint(0, 2, (10, 25, 25))
        >>> pred = torch.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)
    r   r>   r?   z[Expected argument `task` to either be `'binary'`, `'multiclass'` or `'multilabel'` but got )r4   
isinstanceintr9   r<   r   )	r0   r1   r=   r2   r5   r:   r   r   r3   r,   r,   r-   jaccard_index+  s   rB   )N)r/   NT)NN)r   NT)r/   Nr   )r/   r   NT)r/   NNr   NT)typingr   r"   r   typing_extensionsr   7torchmetrics.functional.classification.confusion_matrixr   r   r   r   r	   r
   r   r   r   r   r   r   torchmetrics.utilities.computer   rA   r.   r   boolr4   r7   r9   r;   r<   rB   r,   r,   r,   r-   <module>   s   8

:
7



E



D
	
