o
    yiН                     @   s  d dl mZmZmZmZmZ d dlZd dlmZmZ d dl	m
Z d dlmZ d dlmZ d dlmZ d dlmZ 			dCd
ededee dedeeeef f
ddZ	dDdeeeee ef  deej dee fddZ		dDdeeeee ef  dee ddfddZ	dEd
ededee ddfddZ		dDd
ededeeeee ef  dee deeeee f f
ddZd
ededee deeeeef f fddZ		dFdeeeeef f dee dedeeeef fdd Z			!dGd
ededeeeee ef  dee d"edeeeef fd#d$Z		dDd%edeeeee ef  dee ddfd&d'Z 	dEd
eded%edee ddf
d(d)Z!		dDd
eded%edeeeee ef  dee deeeee f fd*d+Z"d
eded%edee deeeeef f f
d,d-Z#deeeeef f d%edee deeeeef eee ee ee f f fd.d/Z$			!dGd
eded%edeeeee ef  dee d"edeeeeef eee ee ee f f fd0d1Z%		dDd2edeeeee ef  dee ddfd3d4Z&	dEd
eded2edee ddf
d5d6Z'		dDd
eded2edeeeee ef  dee deeeee f fd7d8Z(d
eded2edee deeeeef f f
d9d:Z)	dEdeeeeef f d2edee dee deeeeef eee ee ee f f f
d;d<Z*			!dGd
eded2edeeeee ef  dee d"edeeeeef eee ee ee f f fd=d>Z+					!dHd
eded?ed@ deeeee ef  d%ee d2ee dee d"edeeeeef eee ee ee f f fdAdBZ,dS )I    )ListOptionalSequenceTupleUnionN)Tensortensor)
functional)Literal)_check_same_shape)_safe_divide)	_bincount   predstargetsample_weights	pos_labelreturnc           
      C   sD  t   |durt|tst|| jt jd}| j|jkr%| dddf } t j| dd}| | } || }|dur=|| }nd}t 	| dd | dd  d }t
j|ddg|dd d	}||kt j}t j|| dd
| }|durt jd| | dd
| }	nd| | }	|	|| | fW  d   S 1 sw   Y  dS )a  Calculates the tps and false positives for all unique thresholds in the preds tensor. Adapted from
    https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/metrics/_ranking.py.

    Args:
        preds: 1d tensor with predictions
        target: 1d tensor with true values
        sample_weights: a 1d tensor with a weight per sample
        pos_label: interger determining what the positive class in target tensor is

    Returns:
        fps: 1d tensor with false positives for different thresholds
        tps: 1d tensor with true positives for different thresholds
        thresholds: the unique thresholds use for calculating fps and tps
    N)devicedtyper   T)
descendingg      ?r   )value)dim)torchno_grad
isinstancer   r   r   floatndimargsortwhereFpadsizetolongcumsum)
r   r   r   r   desc_score_indicesweightdistinct_value_indicesthreshold_idxstpsfps r-   q/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/functional/classification/precision_recall_curve.py_binary_clf_curve   s(   

"$r/   
thresholdsr   c                 C   s8   t | trtjdd| |d} t | trtj| |d} | S )zTUtility function for converting the threshold arg for list and int to tensor format.r   r   r   )r   intr   linspacelistr   )r0   r   r-   r-   r.   _adjust_threshold_argR   s
   

r5   ignore_indexc                 C   s   | durt | tttfstd|  t | tr#| dk r#td|  t | tr8tdd | D s8td|  t | trF| jdksFtd	|durVt |tsXtd
| dS dS )zValidate non tensor input.

    - ``threshold`` has to be None | a 1d tensor | a list of floats in the [0,1] range | an int
    - ``ignore_index`` has to be None or int
    NzdExpected argument `thresholds` to either be an integer, list of floats or tensor of floats, but got    zQIf argument `thresholds` is an integer, expected it to be larger than 1, but got c                 s   s2    | ]}t |tod |  kodkn  V  qdS )r   r   N)r   r   ).0tr-   r-   r.   	<genexpr>p   s   0 z@_binary_precision_recall_curve_arg_validation.<locals>.<genexpr>zcIf argument `thresholds` is a list, expected all elements to be floats in the [0,1] range, but got r   zCIf argument `thresholds` is an tensor, expected the tensor to be 1dzLExpected argument `ignore_index` to either be `None` or an integer, but got )r   r4   r2   r   
ValueErrorallr   )r0   r6   r-   r-   r.   -_binary_precision_recall_curve_arg_validation]   s*   	r=   c                 C   s   t | | | rtd|j |  std| j t|}|du r2t|dk|dk@ }nt|dk|dk@ ||k@ }|rYtd| d|du rRddgg  n|g ddS )	zValidate tensor input.

    - tensors have to be of same shape
    - all values in target tensor that are not ignored have to be in {0, 1}
    - that the pred tensor is floating point
    zjExpected argument `target` to be an int or long tensor with ground truth labels but got tensor with dtype zlExpected argument `preds` to be an floating tensor with probability/logit scores, but got tensor with dtype Nr   r   z+Detected the following values in `target`: z( but expected only the following values .)r   is_floating_pointr;   r   r   uniqueanyRuntimeError)r   r   r6   unique_valuescheckr-   r-   r.   0_binary_precision_recall_curve_tensor_validation|   s0   
	
rE   c                 C   sd   |   } |  }|dur||k}| | } || }td| k| dk s'|  } t|| j}| ||fS )zConvert all input to the right format.

    - flattens additional dimensions
    - Remove all datapoints that should be ignored
    - Applies sigmoid if pred tensor not in [0,1] range
    - Format thresholds arg to be a tensor
    Nr   r   )flattenr   r<   sigmoidr5   r   )r   r   r0   r6   idxr-   r-   r.   %_binary_precision_recall_curve_format   s   
rI   c                 C   sx   |du r| |fS t |}| d|dk }|d|d  dtj||jd  }t| d| d}||ddS Returns the state to calculate the pr-curve with.

    If thresholds is `None` the direct preds and targets are used. If thresholds is not `None` we compute a multi
    threshold confusion matrix.
    Nr   r   r7      r1   	minlength)	len	unsqueezer%   r   aranger   r   rF   reshape)r   r   r0   len_tpreds_tunique_mappingbinsr-   r-   r.   %_binary_precision_recall_curve_update   s   
&rW   statec           
      C   sl  t | trQ| ddddf }| ddddf }| ddddf }t||| }t||| }t|tjd|j|jdg}t|tjd|j|jdg}|||fS t	| d | d |d\}}}|||  }||d  }t
||d kd d }td| d }	tt||	 tjd|j|jdg}tt||	 tjd|j|jdg}t||	   }|||fS )zComputes the final pr-curve.

    If state is a single tensor, then we calculate the pr-curve from a multi threshold confusion matrix. If state is
    original input, then we dynamically compute the binary classification curve.
    Nr   r   r   r   )r   r   )r   r   r   r   catonesr   r   zerosr/   r    sliceitemreverseddetachclone)
rX   r0   r   r+   r,   fns	precisionrecalllast_indslr-   r-   r.   &_binary_precision_recall_curve_compute   s$   


&&
rg   Tvalidate_argsc                 C   sD   |rt || t| || t| |||\} }}t| ||}t||S )a  Computes the precision-recall curve for binary tasks. The curve consist of multiple pairs of precision and
    recall values evaluated at different thresholds, such that the tradeoff between the two values can been seen.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(N, ...)``. Preds should be a tensor containing probabilities or logits for each
      observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
      sigmoid per element.
    - ``target`` (int tensor): ``(N, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain {0,1} values (except if `ignore_index` is specified). The value 1 always encodes the positive class.

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

    The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
    that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
    non-binned  version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
    argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
    size :math:`\mathcal{O}(n_{thresholds})` (constant memory).

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        thresholds:
            Can be one of:

            - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
              all the data. Most accurate but also most memory consuming approach.
            - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
              0 to 1 as bins for the calculation.
            - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
            - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
              bins for the calculation.

        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.

    Returns:
        (tuple): a tuple of 3 tensors containing:

        - precision: an 1d tensor of size (n_thresholds+1, ) with precision values
        - recall: an 1d tensor of size (n_thresholds+1, ) with recall values
        - thresholds: an 1d tensor of size (n_thresholds, ) with increasing threshold values

    Example:
        >>> from torchmetrics.functional.classification import binary_precision_recall_curve
        >>> preds = torch.tensor([0, 0.5, 0.7, 0.8])
        >>> target = torch.tensor([0, 1, 1, 0])
        >>> binary_precision_recall_curve(preds, target, thresholds=None)  # doctest: +NORMALIZE_WHITESPACE
        (tensor([0.6667, 0.5000, 0.0000, 1.0000]),
         tensor([1.0000, 0.5000, 0.0000, 0.0000]),
         tensor([0.5000, 0.7000, 0.8000]))
        >>> binary_precision_recall_curve(preds, target, thresholds=5)  # doctest: +NORMALIZE_WHITESPACE
        (tensor([0.5000, 0.6667, 0.6667, 0.0000, 0.0000, 1.0000]),
         tensor([1., 1., 1., 0., 0., 0.]),
         tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000]))
    )r=   rE   rI   rW   rg   )r   r   r0   r6   rh   rX   r-   r-   r.   binary_precision_recall_curve   s   ?

ri   num_classesc                 C   s.   t | tr	| dk rtd|  t|| dS )zValidate non tensor input.

    - ``num_classes`` has to be an int larger than 1
    - ``threshold`` has to be None | a 1d tensor | a list of floats in the [0,1] range | an int
    - ``ignore_index`` has to be None or int
    r7   zHExpected argument `num_classes` to be an integer larger than 1, but got N)r   r2   r;   r=   )rj   r0   r6   r-   r-   r.   1_multiclass_precision_recall_curve_arg_validation:  s   rk   c                 C   s$  | j |j d kstd| j  d|j  | r td|j |  s,td| j | jd |krAtd| jd  d| d| jd |jd ksY| jd	d
 |jdd
 kretd| j d|j tt|}|d
u ru||k}n||d k}|rtd|d
u r|n|d  d| dd
S )a!  Validate tensor input.

    - target should have one more dimension than preds and all dimensions except for preds.shape[1] should match
    exactly. preds.shape[1] should have size equal to number of classes
    - all values in target tensor that are not ignored have to be in {0, 1}
    r   zBExpected `preds` to have one more dimension than `target` but got z and zRExpected argument `target` to be an int or long tensor, but got tensor with dtype z/Expected `preds` to be a float tensor, but got zGExpected `preds.shape[1]` to be equal to the number of classes but got r>   r   r7   NziExpected the shape of `preds` should be (N, C, ...) and the shape of `target` should be (N, ...) but got zJDetected more unique values in `target` than `num_classes`. Expected only z but found z in `target`.)	r   r;   r?   r   shaperO   r   r@   rB   )r   r   rj   r6   num_unique_valuesrD   r-   r-   r.   4_multiclass_precision_recall_curve_tensor_validationJ  sN   	
0
rn   c                 C   st   |  dd|dj} | }|dur||k}| | } || }td| k| dk s/| d} t|| j}| ||fS )zConvert all input to the right format.

    - flattens additional dimensions
    - Remove all datapoints that should be ignored
    - Applies softmax if pred tensor not in [0,1] range
    - Format thresholds arg to be a tensor
    r   r   r   N)		transposerR   TrF   r   r<   softmaxr5   r   )r   r   rj   r0   r6   rH   r-   r-   r.   )_multiclass_precision_recall_curve_formatu  s   

rr   c           	      C   s   |du r| |fS t |}| d|ddk }tjjj||d}|d|d  }|dtj|| jddd 7 }|d| tj|| jd 7 }t	|
 d| | d}|||ddS )	rK   Nr   r   )rj   r7   rL   r1   rM   )rO   rP   r%   r   nnr	   one_hotrQ   r   r   rF   rR   )	r   r   rj   r0   rS   rT   target_trU   rV   r-   r-   r.   )_multiclass_precision_recall_curve_update  s   $rv   c           
   	   C   s4  t | tr^| ddddddf }| ddddddf }| ddddddf }t||| }t||| }t|tjd||j|jdg}t|tjd||j|jdg}|j	|j	|fS g g g }}}t
|D ]*}t| d dd|f | d gd|d}	||	d  ||	d  ||	d  qj|||fS zComputes the final pr-curve.

    If state is a single tensor, then we calculate the pr-curve from a multi threshold confusion matrix. If state is
    original input, then we dynamically compute the binary classification curve in an iterative way.
    Nr   r   rY   )r0   r   r7   r   r   r   r   rZ   r[   r   r   r\   rp   rangerg   append)
rX   rj   r0   r+   r,   rb   rc   rd   iresr-   r-   r.   *_multiclass_precision_recall_curve_compute  s    

  &
r}   c                 C   sN   |rt ||| t| ||| t| ||||\} }}t| |||}t|||S )az  Computes the precision-recall curve for multiclass tasks. The curve consist of multiple pairs of precision
    and recall values evaluated at different thresholds, such that the tradeoff between the two values can been
    seen.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
      observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
      softmax per sample.
    - ``target`` (int tensor): ``(N, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain values in the [0, n_classes-1] range (except if `ignore_index` is specified).

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

    The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
    that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
    non-binned  version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
    argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
    size :math:`\mathcal{O}(n_{thresholds} \times n_{classes})` (constant memory).

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        num_classes: Integer specifing the number of classes
        thresholds:
            Can be one of:

            - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
              all the data. Most accurate but also most memory consuming approach.
            - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
              0 to 1 as bins for the calculation.
            - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
            - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
              bins for the calculation.

        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.

    Returns:
        (tuple): a tuple of either 3 tensors or 3 lists containing

        - precision: if `thresholds=None` a list for each class is returned with an 1d tensor of size (n_thresholds+1, )
          with precision values (length may differ between classes). If `thresholds` is set to something else,
          then a single 2d tensor of size (n_classes, n_thresholds+1) with precision values is returned.
        - recall: if `thresholds=None` a list for each class is returned with an 1d tensor of size (n_thresholds+1, )
          with recall values (length may differ between classes). If `thresholds` is set to something else,
          then a single 2d tensor of size (n_classes, n_thresholds+1) with recall values is returned.
        - thresholds: if `thresholds=None` a list for each class is returned with an 1d tensor of size (n_thresholds, )
          with increasing threshold values (length may differ between classes). If `threshold` is set to something else,
          then a single 1d tensor of size (n_thresholds, ) is returned with shared threshold values for all classes.

    Example:
        >>> from torchmetrics.functional.classification import multiclass_precision_recall_curve
        >>> preds = torch.tensor([[0.75, 0.05, 0.05, 0.05, 0.05],
        ...                       [0.05, 0.75, 0.05, 0.05, 0.05],
        ...                       [0.05, 0.05, 0.75, 0.05, 0.05],
        ...                       [0.05, 0.05, 0.05, 0.75, 0.05]])
        >>> target = torch.tensor([0, 1, 3, 2])
        >>> precision, recall, thresholds = multiclass_precision_recall_curve(
        ...    preds, target, num_classes=5, thresholds=None
        ... )
        >>> precision  # doctest: +NORMALIZE_WHITESPACE
        [tensor([1., 1.]), tensor([1., 1.]), tensor([0.2500, 0.0000, 1.0000]),
         tensor([0.2500, 0.0000, 1.0000]), tensor([0., 1.])]
        >>> recall
        [tensor([1., 0.]), tensor([1., 0.]), tensor([1., 0., 0.]), tensor([1., 0., 0.]), tensor([nan, 0.])]
        >>> thresholds
        [tensor([0.7500]), tensor([0.7500]), tensor([0.0500, 0.7500]), tensor([0.0500, 0.7500]), tensor([0.0500])]
        >>> multiclass_precision_recall_curve(
        ...     preds, target, num_classes=5, thresholds=5
        ... )  # doctest: +NORMALIZE_WHITESPACE
        (tensor([[0.2500, 1.0000, 1.0000, 1.0000, 0.0000, 1.0000],
                 [0.2500, 1.0000, 1.0000, 1.0000, 0.0000, 1.0000],
                 [0.2500, 0.0000, 0.0000, 0.0000, 0.0000, 1.0000],
                 [0.2500, 0.0000, 0.0000, 0.0000, 0.0000, 1.0000],
                 [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 1.0000]]),
         tensor([[1., 1., 1., 1., 0., 0.],
                 [1., 1., 1., 1., 0., 0.],
                 [1., 0., 0., 0., 0., 0.],
                 [1., 0., 0., 0., 0., 0.],
                 [0., 0., 0., 0., 0., 0.]]),
         tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000]))
    )rk   rn   rr   rv   r}   )r   r   rj   r0   r6   rh   rX   r-   r-   r.   !multiclass_precision_recall_curve  s   [

r~   
num_labelsc                 C   s   t | || dS )zValidate non tensor input.

    - ``num_labels`` has to be an int larger than 1
    - ``threshold`` has to be None | a 1d tensor | a list of floats in the [0,1] range | an int
    - ``ignore_index`` has to be None or int
    N)rk   )r   r0   r6   r-   r-   r.   1_multilabel_precision_recall_curve_arg_validation,  s   r   c                 C   s8   t | || | jd |krtd| jd  d| dS )zValidate tensor input.

    - tensors have to be of same shape
    - preds.shape[1] is equal to the number of labels
    - all values in target tensor that are not ignored have to be in {0, 1}
    - that the pred tensor is floating point
    r   zaExpected both `target.shape[1]` and `preds.shape[1]` to be equal to the number of labels but got z and expected N)rE   rl   r;   )r   r   r   r6   r-   r-   r.   4_multilabel_precision_recall_curve_tensor_validation:  s   
r   c                 C   s   |  dd|dj} | dd|dj}td| k| dk s%|  } t|| j}|dur_|dur_|  } | }||k}d| |durJt	|nd | |< d| |durZt	|nd ||< | ||fS )zConvert all input to the right format.

    - flattens additional dimensions
    - Mask all datapoints that should be ignored with negative values
    - Applies sigmoid if pred tensor not in [0,1] range
    - Format thresholds arg to be a tensor
    r   r   r   N)
ro   rR   rp   r   r<   rG   r5   r   ra   rO   )r   r   r   r0   r6   rH   r-   r-   r.   )_multilabel_precision_recall_curve_formatL  s     
r   c                 C   s   |du r| |fS t |}| d|ddk }|d|d  }|dtj|| jddd 7 }|d| tj|| jd 7 }||dk }t|d| | d}|||ddS rJ   )rO   rP   r%   r   rQ   r   r   rR   )r   r   r   r0   rS   rT   rU   rV   r-   r-   r.   )_multilabel_precision_recall_curve_updatek  s   $r   c              	   C   sl  t | tr^| ddddddf }| ddddddf }| ddddddf }t||| }t||| }t|tjd||j|jdg}t|tjd||j|jdg}|j	|j	|fS g g g }}}t
|D ]F}	| d dd|	f }
| d dd|	f }|dur||k}|
|  }
||  }t|
|gddd}||d  ||d  ||d  qj|||fS rw   rx   )rX   r   r0   r6   r+   r,   rb   rc   rd   r{   r   r   rH   r|   r-   r-   r.   *_multilabel_precision_recall_curve_compute  s,   
  


r   c                 C   sP   |rt ||| t| ||| t| ||||\} }}t| |||}t||||S )a  Computes the precision-recall curve for multilabel tasks. The curve consist of multiple pairs of precision
    and recall values evaluated at different thresholds, such that the tradeoff between the two values can been
    seen.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
      observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
      sigmoid per element.
    - ``target`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain {0,1} values (except if `ignore_index` is specified).

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

    The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
    that is less accurate but more memory efficient. Setting the `thresholds` argument to `None` will activate the
    non-binned  version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
    argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
    size :math:`\mathcal{O}(n_{thresholds} \times n_{labels})` (constant memory).

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        num_labels: Integer specifing the number of labels
        thresholds:
            Can be one of:

            - If set to `None`, will use a non-binned approach where thresholds are dynamically calculated from
              all the data. Most accurate but also most memory consuming approach.
            - If set to an `int` (larger than 1), will use that number of thresholds linearly spaced from
              0 to 1 as bins for the calculation.
            - If set to an `list` of floats, will use the indicated thresholds in the list as bins for the calculation
            - If set to an 1d `tensor` of floats, will use the indicated thresholds in the tensor as
              bins for the calculation.

        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.

    Returns:
        (tuple): a tuple of either 3 tensors or 3 lists containing

        - precision: if `thresholds=None` a list for each label is returned with an 1d tensor of size (n_thresholds+1, )
          with precision values (length may differ between labels). If `thresholds` is set to something else,
          then a single 2d tensor of size (n_labels, n_thresholds+1) with precision values is returned.
        - recall: if `thresholds=None` a list for each label is returned with an 1d tensor of size (n_thresholds+1, )
          with recall values (length may differ between labels). If `thresholds` is set to something else,
          then a single 2d tensor of size (n_labels, n_thresholds+1) with recall values is returned.
        - thresholds: if `thresholds=None` a list for each label is returned with an 1d tensor of size (n_thresholds, )
          with increasing threshold values (length may differ between labels). If `threshold` is set to something else,
          then a single 1d tensor of size (n_thresholds, ) is returned with shared threshold values for all labels.

    Example:
        >>> from torchmetrics.functional.classification import multilabel_precision_recall_curve
        >>> preds = torch.tensor([[0.75, 0.05, 0.35],
        ...                       [0.45, 0.75, 0.05],
        ...                       [0.05, 0.55, 0.75],
        ...                       [0.05, 0.65, 0.05]])
        >>> target = torch.tensor([[1, 0, 1],
        ...                        [0, 0, 0],
        ...                        [0, 1, 1],
        ...                        [1, 1, 1]])
        >>> precision, recall, thresholds = multilabel_precision_recall_curve(
        ...    preds, target, num_labels=3, thresholds=None
        ... )
        >>> precision  # doctest: +NORMALIZE_WHITESPACE
        [tensor([0.5000, 0.5000, 1.0000, 1.0000]), tensor([0.6667, 0.5000, 0.0000, 1.0000]),
         tensor([0.7500, 1.0000, 1.0000, 1.0000])]
        >>> recall  # doctest: +NORMALIZE_WHITESPACE
        [tensor([1.0000, 0.5000, 0.5000, 0.0000]), tensor([1.0000, 0.5000, 0.0000, 0.0000]),
         tensor([1.0000, 0.6667, 0.3333, 0.0000])]
        >>> thresholds  # doctest: +NORMALIZE_WHITESPACE
        [tensor([0.0500, 0.4500, 0.7500]), tensor([0.5500, 0.6500, 0.7500]),
         tensor([0.0500, 0.3500, 0.7500])]
        >>> multilabel_precision_recall_curve(
        ...     preds, target, num_labels=3, thresholds=5
        ... )  # doctest: +NORMALIZE_WHITESPACE
        (tensor([[0.5000, 0.5000, 1.0000, 1.0000, 0.0000, 1.0000],
                 [0.5000, 0.6667, 0.6667, 0.0000, 0.0000, 1.0000],
                 [0.7500, 1.0000, 1.0000, 1.0000, 0.0000, 1.0000]]),
         tensor([[1.0000, 0.5000, 0.5000, 0.5000, 0.0000, 0.0000],
                 [1.0000, 1.0000, 1.0000, 0.0000, 0.0000, 0.0000],
                 [1.0000, 0.6667, 0.3333, 0.3333, 0.0000, 0.0000]]),
         tensor([0.0000, 0.2500, 0.5000, 0.7500, 1.0000]))
    )r   r   r   r   r   )r   r   r   r0   r6   rh   rX   r-   r-   r.   !multilabel_precision_recall_curve  s   \

r   task)binary
multiclass
multilabelc                 C   sv   |dkrt | ||||S |dkr t|tsJ t| |||||S |dkr4t|ts+J t| |||||S td| )at  Computes the precision-recall curve. The curve consist of multiple pairs of precision and recall values
    evaluated at different thresholds, such that the tradeoff between the two values can been seen.

    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_precision_recall_curve`, :func:`multiclass_precision_recall_curve` and
    :func:`multilabel_precision_recall_curve` for the specific details of each argument influence and examples.

    Legacy Example:
        >>> pred = torch.tensor([0.0, 1.0, 2.0, 3.0])
        >>> target = torch.tensor([0, 1, 1, 0])
        >>> precision, recall, thresholds = precision_recall_curve(pred, target, task='binary')
        >>> precision
        tensor([0.6667, 0.5000, 0.0000, 1.0000])
        >>> recall
        tensor([1.0000, 0.5000, 0.0000, 0.0000])
        >>> thresholds
        tensor([0.7311, 0.8808, 0.9526])

        >>> pred = torch.tensor([[0.75, 0.05, 0.05, 0.05, 0.05],
        ...                      [0.05, 0.75, 0.05, 0.05, 0.05],
        ...                      [0.05, 0.05, 0.75, 0.05, 0.05],
        ...                      [0.05, 0.05, 0.05, 0.75, 0.05]])
        >>> target = torch.tensor([0, 1, 3, 2])
        >>> precision, recall, thresholds = precision_recall_curve(pred, target, task='multiclass', num_classes=5)
        >>> precision
        [tensor([1., 1.]), tensor([1., 1.]), tensor([0.2500, 0.0000, 1.0000]),
         tensor([0.2500, 0.0000, 1.0000]), tensor([0., 1.])]
        >>> recall
        [tensor([1., 0.]), tensor([1., 0.]), tensor([1., 0., 0.]), tensor([1., 0., 0.]), tensor([nan, 0.])]
        >>> thresholds
        [tensor([0.7500]), tensor([0.7500]), tensor([0.0500, 0.7500]), tensor([0.0500, 0.7500]), tensor([0.0500])]
    r   r   r   z[Expected argument `task` to either be `'binary'`, `'multiclass'` or `'multilabel'` but got )ri   r   r2   r~   r   r;   )r   r   r   r0   rj   r   r6   rh   r-   r-   r.   precision_recall_curve  s   +r   )Nr   )NN)N)r   )NNT)NNNNT)-typingr   r   r   r   r   r   r   r   torch.nnr	   r!   typing_extensionsr
   torchmetrics.utilities.checksr   torchmetrics.utilities.computer   torchmetrics.utilities.datar   r2   r/   r   r   r5   r=   rE   rI   rW   rg   boolri   rk   rn   rr   rv   r}   r~   r   r   r   r   r   r   r   r-   r-   r-   r.   <module>   s&  
8

 
'


(
I

/

*
!*
g



*
(*
j*	